1 /*******************************************************************************
2 * Copyright (c) 2012 Ericsson
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * Francois Chouinard - Initial API and implementation
11 *******************************************************************************/
13 package org
.eclipse
.linuxtools
.tmf
.core
.timestamp
;
15 import java
.text
.DecimalFormat
;
16 import java
.text
.ParseException
;
17 import java
.text
.SimpleDateFormat
;
18 import java
.util
.ArrayList
;
19 import java
.util
.Calendar
;
20 import java
.util
.Date
;
21 import java
.util
.List
;
22 import java
.util
.regex
.Matcher
;
23 import java
.util
.regex
.Pattern
;
25 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfSignalManager
;
26 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfTimestampFormatUpdateSignal
;
29 * A formatting and parsing facility that can handle timestamps that span the
30 * epoch with a precision down to the nanosecond. It can be understood as a
31 * simplified and more constrained version of SimpleDateFormat as it limits the
32 * number of allowed pattern characters and the acceptable timestamp formats.
34 * The timestamp representation is broken down into a number of optional
35 * components that can be assembled into a fairly simple way.
37 * <h4>Date Pattern</h4>
39 * <table border=0 cellspacing=3 cellpadding=0 >
40 * <tr bgcolor="#ccccff">
41 * <th align=left>Format
42 * <th align=left>Description
43 * <th align=left>Value Range
44 * <th align=left>Example
46 * <td><code>yyyy</code>
48 * <td><code>1970-...</code>
49 * <td><code>2012</code>
50 * <tr bgcolor="#eeeeff">
53 * <td><code>01-12</code>
58 * <td><code>01-31</code>
63 * <h4>Time Pattern</h4>
65 * <table border=0 cellspacing=3 cellpadding=0 >
66 * <tr bgcolor="#ccccff">
67 * <th align=left>Format
68 * <th align=left>Description
69 * <th align=left>Value Range
70 * <th align=left>Example
74 * <td><code>00-23</code>
76 * <tr bgcolor="#eeeeff">
79 * <td><code>00-59</code>
83 * <td>Second in minute
84 * <td><code>00-59</code>
86 * <tr bgcolor="#eeeeff">
88 * <td>The seconds since the epoch
89 * <td><code>00-...</code>
90 * <td><code>1332170682</code>
94 * <h4>Sub-Seconds Pattern</h4>
96 * <table border=0 cellspacing=3 cellpadding=0 >
97 * <tr bgcolor="#ccccff">
98 * <th align=left>Format
99 * <th align=left>Description
100 * <th align=left>Value Range
101 * <th align=left>Example
103 * <td><code>SSS</code>
104 * <td>Millisecond in second
105 * <td><code>000-999</code>
106 * <td><code>123</code>
107 * <tr bgcolor="#eeeeff">
108 * <td><code>CCC</code>
109 * <td>Microseconds in ms
110 * <td><code>000-999</code>
111 * <td><code>456</code>
113 * <td><code>NNN</code>
114 * <td>Nanosecond in µs
115 * <td><code>000-999</code>
116 * <td><code>789</code>
120 * <strong>Note: </strong>If "T" is used, no other Date or Time pattern
121 * can be used. Also, "T" should be used for time intervals.
123 * <strong>Note: </strong>Each sub-field can be separated by a single,
124 * optional character delimiter. However, the between Date/Time and the
125 * Sub-seconds pattern is mandatory (if there is a fractional part) and
126 * has to be separated from Date/time by "." (period).
128 * The recognized delimiters are:
130 * <li>Space ("<code> </code>")
131 * <li>Period (<code>".</code>")
132 * <li>Comma ("<code>,</code>")
133 * <li>Dash ("<code>-</code>")
134 * <li>Underline ("<code>_</code>")
135 * <li>Colon ("<code>:</code>")
136 * <li>Semicolon ("<code>;</code>")
137 * <li>Slash ("<code>/</code>")
138 * <li>Double-quote ("<code>"</code>")
142 * The following examples show how timestamp patterns are interpreted in
143 * the U.S. locale. The given timestamp is 1332170682539677389L, the number
144 * of nanoseconds since 1970/01/01.
147 * <table border=0 cellspacing=3 cellpadding=0>
148 * <tr bgcolor="#ccccff">
149 * <th align=left>Date and Time Pattern
150 * <th align=left>Result
152 * <td><code>"yyyy-MM-dd HH:mm:ss.SSS.CCC.NNN"</code>
153 * <td><code>2012-03-19 11:24:42.539.677.389</code>
154 * <tr bgcolor="#eeeeff">
155 * <td><code>"yyyy-MM-dd HH:mm:ss.SSS.CCC"</code>
156 * <td><code>2012-03-19 11:24:42.539.677</code>
158 * <td><code>"yyyy-D HH:mm:ss.SSS.CCC"</code>
159 * <td><code>2012-79 11:24:42.539.677</code>
160 * <tr bgcolor="#eeeeff">
161 * <td><code>"ss.SSSCCCNNN"</code>
162 * <td><code>42.539677389</code>
164 * <td><code>"T.SSS CCC NNN"</code>
165 * <td><code>1332170682.539 677 389</code>
166 * <tr bgcolor="#eeeeff">
167 * <td><code>"T"</code>
168 * <td><code>1332170682</code>
174 * @author Francois Chouinard
176 public class TmfTimestampFormat
extends SimpleDateFormat
{
178 // ------------------------------------------------------------------------
180 // ------------------------------------------------------------------------
183 * This class' serialization ID
185 private static final long serialVersionUID
= 2835829763122454020L;
188 * The default timestamp pattern
190 public static final String DEFAULT_TIME_PATTERN
= "HH:mm:ss.SSS CCC NNN"; //$NON-NLS-1$
193 * The LTTng 0.x legacy timestamp format
195 public static final String DEFAULT_INTERVAL_PATTERN
= "TTT.SSS CCC NNN"; //$NON-NLS-1$
197 // Fractions of seconds supported patterns
198 private static final String DOT_RE
= "\\."; //$NON-NLS-1$
199 private static final String SEP_RE
= "[ \\.,-_:;/\\\"]?"; //$NON-NLS-1$
200 private static final String DGTS_3_RE
= "(\\d{3})"; //$NON-NLS-1$
201 private static final String DGTS_13_RE
= "(\\d{1,3})"; //$NON-NLS-1$
203 private static final String MILLISEC_RE
= DOT_RE
+ DGTS_13_RE
;
204 private static final String MICROSEC_RE
= DOT_RE
+ DGTS_3_RE
+ SEP_RE
+ DGTS_13_RE
;
205 private static final String NANOSEC_RE
= DOT_RE
+ DGTS_3_RE
+ SEP_RE
+ DGTS_3_RE
+ SEP_RE
+ DGTS_13_RE
;
207 private static final Pattern MILLISEC_PAT
= Pattern
.compile(MILLISEC_RE
);
208 private static final Pattern MICROSEC_PAT
= Pattern
.compile(MICROSEC_RE
);
209 private static final Pattern NANOSEC_PAT
= Pattern
.compile(NANOSEC_RE
);
211 // ------------------------------------------------------------------------
213 // ------------------------------------------------------------------------
215 // The default timestamp pattern
216 private static String fDefaultTimePattern
= null;
217 private static TmfTimestampFormat fDefaultTimeFormat
= null;
219 // The default time interval format
220 private static String fDefaultIntervalPattern
= null;
221 private static TmfTimestampFormat fDefaultIntervalFormat
= null;
223 // The timestamp pattern
224 private String fPattern
;
226 // The timestamp pattern
227 private List
<String
> fSupplPatterns
= new ArrayList
<String
>();
230 * The supplementary pattern letters. Can be redefined by sub-classes
231 * to either override existing letters or augment the letter set.
232 * If so, the format() method must provide the (re-)implementation of the
235 protected String fSupplPatternLetters
= "TSCN"; //$NON-NLS-1$
238 * The bracketing symbols used to mitigate the risk of a format string
239 * that contains escaped sequences that would conflict with our format
242 /** The open bracket symbol */
243 protected String fOpenBracket
= "[&"; //$NON-NLS-1$
245 /** The closing bracket symbol */
246 protected String fCloseBracket
= "&]"; //$NON-NLS-1$
248 // ------------------------------------------------------------------------
250 // ------------------------------------------------------------------------
253 * The default constructor (uses the default pattern)
255 public TmfTimestampFormat() {
256 this(fDefaultTimePattern
);
260 * The normal constructor
262 * @param pattern the format pattern
264 public TmfTimestampFormat(String pattern
) {
265 applyPattern(pattern
);
269 * The copy constructor
271 * @param other the other format pattern
273 public TmfTimestampFormat(TmfTimestampFormat other
) {
274 this(other
.fPattern
);
277 // ------------------------------------------------------------------------
279 // ------------------------------------------------------------------------
282 * @param pattern the new default time pattern
284 public static void setDefaultTimeFormat(final String pattern
) {
285 fDefaultTimePattern
= pattern
;
286 fDefaultTimeFormat
= new TmfTimestampFormat(fDefaultTimePattern
);
287 TmfSignalManager
.dispatchSignal(new TmfTimestampFormatUpdateSignal(null));
291 * @return the default time format pattern
293 public static TmfTimestampFormat
getDefaulTimeFormat() {
294 if (fDefaultTimeFormat
== null) {
295 fDefaultTimeFormat
= new TmfTimestampFormat(DEFAULT_TIME_PATTERN
);
297 return fDefaultTimeFormat
;
301 * @param pattern the new default interval pattern
303 public static void setDefaultIntervalFormat(final String pattern
) {
304 fDefaultIntervalPattern
= pattern
;
305 fDefaultIntervalFormat
= new TmfTimestampFormat(fDefaultIntervalPattern
);
306 TmfSignalManager
.dispatchSignal(new TmfTimestampFormatUpdateSignal(null));
310 * @return the default interval format pattern
312 public static TmfTimestampFormat
getDefaulIntervalFormat() {
313 if (fDefaultIntervalFormat
== null) {
314 fDefaultIntervalFormat
= new TmfTimestampFormat(DEFAULT_INTERVAL_PATTERN
);
316 return fDefaultIntervalFormat
;
320 * @see java.text.SimpleDateFormat#applyPattern(java.lang.String)
323 public void applyPattern(String pattern
) {
325 String quotedPattern
= quoteSpecificTags(pattern
);
326 super.applyPattern(quotedPattern
);
330 * @see java.text.SimpleDateFormat#toPattern()
333 public String
toPattern() {
337 // ------------------------------------------------------------------------
339 // ------------------------------------------------------------------------
342 * Format the timestamp according to its pattern.
344 * @param value the timestamp value to format (in ns)
345 * @return the formatted timestamp
347 public synchronized String
format(long value
) {
349 // Split the timestamp value into its sub-components
350 long sec
= value
/ 1000000000; // seconds
351 long ms
= value
% 1000000000 / 1000000; // milliseconds
352 long cs
= value
% 1000000 / 1000; // microseconds
353 long ns
= value
% 1000; // nanoseconds
355 // Let the base class fill the stuff it knows about
356 StringBuffer result
= new StringBuffer(super.format(sec
* 1000 + ms
));
358 // In the case where there is no separation between 2 supplementary
359 // fields, the pattern will have the form "..'[pat-1]''[pat-2]'.." and
360 // the base class format() will interpret the 2 adjacent quotes as a
361 // wanted character in the result string as ("..[pat-1]'[pat-2]..").
362 // Remove these extra quotes before filling the supplementary fields.
363 int loc
= result
.indexOf(fCloseBracket
+ "'" + fOpenBracket
); //$NON-NLS-1$
365 result
.deleteCharAt(loc
+ fCloseBracket
.length());
366 loc
= result
.indexOf(fCloseBracket
+ "'" + fOpenBracket
); //$NON-NLS-1$
369 // Fill in our extensions
370 for (String pattern
: fSupplPatterns
) {
371 int length
= pattern
.length();
373 // Prepare the format buffer
374 StringBuffer fmt
= new StringBuffer(length
);
375 for (int i
= 0; i
< length
; i
++) {
376 fmt
.append("0"); //$NON-NLS-1$
378 DecimalFormat dfmt
= new DecimalFormat(fmt
.toString());
379 String fmtVal
= ""; //$NON-NLS-1$;
381 // Format the proper value as per the pattern
382 switch (pattern
.charAt(0)) {
384 fmtVal
= dfmt
.format(sec
);
387 fmtVal
= dfmt
.format(ms
);
390 fmtVal
= dfmt
.format(cs
);
393 fmtVal
= dfmt
.format(ns
);
399 // Substitute the placeholder with the formatted value
400 String ph
= new StringBuffer(fOpenBracket
+ pattern
+ fCloseBracket
).toString();
401 loc
= result
.indexOf(ph
);
402 result
.replace(loc
, loc
+ length
+ fOpenBracket
.length() + fCloseBracket
.length(), fmtVal
);
405 return result
.toString();
409 * Parse a string according to the format pattern
411 * @param string the source string
412 * @param ref the reference (base) time
413 * @return the parsed value
414 * @throws ParseException if the string has an invalid format
416 public synchronized long parseValue(final String string
, final long ref
) throws ParseException
{
419 if (string
== null || string
.length() == 0) {
423 // The timestamp sub-components
429 // Since we are processing the fractional part, substitute it with
430 // its pattern so the base parser doesn't complain
431 StringBuilder sb
= new StringBuilder(string
);
432 int dot
= string
.indexOf('.');
435 dot
= string
.length();
437 sb
= new StringBuilder(string
.substring(0, dot
));
438 String basePattern
= super.toPattern();
439 int dot2
= basePattern
.indexOf('.');
441 sb
.append(basePattern
.substring(dot2
));
444 // Fill in our extensions
445 for (String pattern
: fSupplPatterns
) {
446 String pat
= fOpenBracket
+ pattern
+ fCloseBracket
;
449 // Extract the substring corresponding to the extra pattern letters
450 // and replace with the pattern so the base parser can do its job.
451 switch (pattern
.charAt(0)) {
453 // Remove everything up to the first "." and compute the
454 // number of seconds since the epoch. If there is no period,
455 // assume an integer value and return immediately
457 return new DecimalFormat("0").parse(string
).longValue() * 1000000000; //$NON-NLS-1$
459 seconds
= new DecimalFormat("0").parse(string
.substring(0, dot
)).longValue(); //$NON-NLS-1$
464 matcher
= MILLISEC_PAT
.matcher(string
.substring(dot
));
465 if (matcher
.find()) {
466 millisec
= new Long(matcher
.group(1));
467 for (int l
= matcher
.group(1).length(); l
< 3; l
++) {
471 stripQuotes(sb
, pattern
);
474 matcher
= MICROSEC_PAT
.matcher(string
.substring(dot
));
475 if (matcher
.find()) {
476 microsec
= new Long(matcher
.group(2));
477 for (int l
= matcher
.group(2).length(); l
< 3; l
++) {
481 stripQuotes(sb
, pattern
);
484 matcher
= NANOSEC_PAT
.matcher(string
.substring(dot
));
485 if (matcher
.find()) {
486 nanosec
= new Long(matcher
.group(3));
487 for (int l
= matcher
.group(3).length(); l
< 3; l
++) {
491 stripQuotes(sb
, pattern
);
498 // If there was no "T" (thus not an interval), parse as a date
500 Date baseDate
= super.parse(sb
.toString());
502 Calendar refTime
= Calendar
.getInstance(getTimeZone());
503 refTime
.setTimeInMillis(ref
/ 1000000);
504 Calendar newTime
= Calendar
.getInstance(getTimeZone());
505 newTime
.setTimeInMillis(baseDate
.getTime());
507 int[] fields
= new int[] { Calendar
.YEAR
, Calendar
.MONTH
, Calendar
.DATE
, Calendar
.HOUR_OF_DAY
, Calendar
.MINUTE
, Calendar
.SECOND
};
508 for (int field
: fields
) {
509 int value
= newTime
.get(field
);
510 // Do some adjustments...
511 if (field
== Calendar
.YEAR
) {
513 } else if (field
== Calendar
.DATE
) {
516 // ... and fill-in the empty fields
518 newTime
.set(field
, refTime
.get(field
));
520 break; // Get out as soon as we have a significant value
523 seconds
= newTime
.getTimeInMillis() / 1000;
526 // Compute the value in ns
527 return seconds
* 1000000000 + millisec
* 1000000 + microsec
* 1000 + nanosec
;
531 * Parse a string according to the format pattern
533 * @param string the source string
534 * @return the parsed value
535 * @throws ParseException if the string has an invalid format
537 public long parseValue(final String string
) throws ParseException
{
538 long result
= parseValue(string
, 0);
543 // ------------------------------------------------------------------------
545 // ------------------------------------------------------------------------
548 * Copy the pattern but quote (bracket with "[&" and "&]") the
549 * TmfTimestampFormat specific tags so these fields are treated as
550 * comments by the base class.
552 * It also keeps track of the corresponding quoted fields so they can be
553 * properly populated later on (by format()).
555 * @param pattern the 'extended' pattern
556 * @return the quoted and bracketed pattern
558 private String
quoteSpecificTags(final String pattern
) {
560 StringBuffer result
= new StringBuffer();
562 int length
= pattern
.length();
563 boolean inQuote
= false;
565 for (int i
= 0; i
< length
; i
++) {
566 char c
= pattern
.charAt(i
);
569 // '' is treated as a single quote regardless of being
570 // in a quoted section.
571 if ((i
+ 1) < length
) {
572 c
= pattern
.charAt(i
+ 1);
583 if (fSupplPatternLetters
.indexOf(c
) != -1) {
584 StringBuilder pat
= new StringBuilder();
586 result
.insert(result
.length() - 1, "'" + fOpenBracket
); //$NON-NLS-1$
587 while ((i
+ 1) < length
&& pattern
.charAt(i
+ 1) == c
) {
592 result
.append(fCloseBracket
+ "'"); //$NON-NLS-1$
593 fSupplPatterns
.add(pat
.toString());
597 return result
.toString();
601 * Remove the quotes from the pattern
606 private void stripQuotes(StringBuilder sb
, String pattern
) {
607 String pt
= "'" + fOpenBracket
+ pattern
+ fCloseBracket
+ "'"; //$NON-NLS-1$//$NON-NLS-2$
608 int l
= sb
.indexOf(pt
);
610 sb
.delete(l
+ pt
.length() - 1, l
+ pt
.length());