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
.event
;
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
.TimeZone
;
23 import java
.util
.regex
.Matcher
;
24 import java
.util
.regex
.Pattern
;
26 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfSignalManager
;
27 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfTimestampFormatUpdateSignal
;
30 * A formatting and parsing facility that can handle timestamps that span the
31 * epoch with a precision down to the nanosecond. It can be understood as a
32 * simplified and more constrained version of SimpleDateFormat as it limits the
33 * number of allowed pattern characters and the acceptable timestamp formats.
35 * The timestamp representation is broken down into a number of optional
36 * components that can be assembled into a fairly simple way.
38 * <h4>Date Pattern</h4>
40 * <table border=0 cellspacing=3 cellpadding=0 >
41 * <tr bgcolor="#ccccff">
42 * <th align=left>Format
43 * <th align=left>Description
44 * <th align=left>Value Range
45 * <th align=left>Example
47 * <td><code>yyyy</code>
49 * <td><code>1970-...</code>
50 * <td><code>2012</code>
51 * <tr bgcolor="#eeeeff">
54 * <td><code>01-12</code>
59 * <td><code>01-31</code>
64 * <h4>Time Pattern</h4>
66 * <table border=0 cellspacing=3 cellpadding=0 >
67 * <tr bgcolor="#ccccff">
68 * <th align=left>Format
69 * <th align=left>Description
70 * <th align=left>Value Range
71 * <th align=left>Example
75 * <td><code>00-23</code>
77 * <tr bgcolor="#eeeeff">
80 * <td><code>00-59</code>
84 * <td>Second in minute
85 * <td><code>00-59</code>
87 * <tr bgcolor="#eeeeff">
89 * <td>The seconds since the epoch
90 * <td><code>00-...</code>
91 * <td><code>1332170682</code>
95 * <h4>Sub-Seconds Pattern</h4>
97 * <table border=0 cellspacing=3 cellpadding=0 >
98 * <tr bgcolor="#ccccff">
99 * <th align=left>Format
100 * <th align=left>Description
101 * <th align=left>Value Range
102 * <th align=left>Example
104 * <td><code>SSS</code>
105 * <td>Millisecond in second
106 * <td><code>000-999</code>
107 * <td><code>123</code>
108 * <tr bgcolor="#eeeeff">
109 * <td><code>CCC</code>
110 * <td>Microseconds in ms
111 * <td><code>000-999</code>
112 * <td><code>456</code>
114 * <td><code>NNN</code>
115 * <td>Nanosecond in µs
116 * <td><code>000-999</code>
117 * <td><code>789</code>
121 * <strong>Note: </strong>If "T" is used, no other Date or Time pattern
122 * can be used. Also, "T" should be used for time intervals.
124 * <strong>Note: </strong>Each sub-field can be separated by a single,
125 * optional character delimiter. However, the between Date/Time and the
126 * Sub-seconds pattern is mandatory (if there is a fractional part) and
127 * has to be separated from Date/time by "." (period).
129 * The recognized delimiters are:
131 * <li>Space ("<code> </code>")
132 * <li>Period (<code>".</code>")
133 * <li>Comma ("<code>,</code>")
134 * <li>Dash ("<code>-</code>")
135 * <li>Underline ("<code>_</code>")
136 * <li>Colon ("<code>:</code>")
137 * <li>Semicolon ("<code>;</code>")
138 * <li>Slash ("<code>/</code>")
139 * <li>Double-quote ("<code>"</code>")
143 * The following examples show how timestamp patterns are interpreted in
144 * the U.S. locale. The given timestamp is 1332170682539677389L, the number
145 * of nanoseconds since 1970/01/01.
148 * <table border=0 cellspacing=3 cellpadding=0>
149 * <tr bgcolor="#ccccff">
150 * <th align=left>Date and Time Pattern
151 * <th align=left>Result
153 * <td><code>"yyyy-MM-dd HH:mm:ss.SSS.CCC.NNN"</code>
154 * <td><code>2012-03-19 11:24:42.539.677.389</code>
155 * <tr bgcolor="#eeeeff">
156 * <td><code>"yyyy-MM-dd HH:mm:ss.SSS.CCC"</code>
157 * <td><code>2012-03-19 11:24:42.539.677</code>
159 * <td><code>"yyyy-D HH:mm:ss.SSS.CCC"</code>
160 * <td><code>2012-79 11:24:42.539.677</code>
161 * <tr bgcolor="#eeeeff">
162 * <td><code>"ss.SSSCCCNNN"</code>
163 * <td><code>42.539677389</code>
165 * <td><code>"T.SSS CCC NNN"</code>
166 * <td><code>1332170682.539 677 389</code>
167 * <tr bgcolor="#eeeeff">
168 * <td><code>"T"</code>
169 * <td><code>1332170682</code>
175 * @author Francois Chouinard
177 public class TmfTimestampFormat
extends SimpleDateFormat
{
179 // ------------------------------------------------------------------------
181 // ------------------------------------------------------------------------
184 * This class' serialization ID
186 private static final long serialVersionUID
= 2835829763122454020L;
189 * The default timestamp pattern
191 public static final String DEFAULT_TIME_PATTERN
= "HH:mm:ss.SSS CCC NNN"; //$NON-NLS-1$
194 * The LTTng 0.x legacy timestamp format
196 public static final String DEFAULT_INTERVAL_PATTERN
= "TTT.SSS CCC NNN"; //$NON-NLS-1$
198 // Fractions of seconds supported patterns
199 private static final String DOT_RE
= "\\."; //$NON-NLS-1$
200 private static final String SEP_RE
= "[ \\.,-_:;/\\\"]?"; //$NON-NLS-1$
201 private static final String DGTS_3_RE
= "(\\d{3})"; //$NON-NLS-1$
202 private static final String DGTS_13_RE
= "(\\d{1,3})"; //$NON-NLS-1$
204 private static final String MILLISEC_RE
= DOT_RE
+ DGTS_13_RE
;
205 private static final String MICROSEC_RE
= DOT_RE
+ DGTS_3_RE
+ SEP_RE
+ DGTS_13_RE
;
206 private static final String NANOSEC_RE
= DOT_RE
+ DGTS_3_RE
+ SEP_RE
+ DGTS_3_RE
+ SEP_RE
+ DGTS_13_RE
;
208 private static final Pattern MILLISEC_PAT
= Pattern
.compile(MILLISEC_RE
);
209 private static final Pattern MICROSEC_PAT
= Pattern
.compile(MICROSEC_RE
);
210 private static final Pattern NANOSEC_PAT
= Pattern
.compile(NANOSEC_RE
);
212 // ------------------------------------------------------------------------
214 // ------------------------------------------------------------------------
216 // The default timestamp pattern
217 private static String fDefaultTimePattern
= null;
218 private static TmfTimestampFormat fDefaultTimeFormat
= null;
220 // The default time interval format
221 private static String fDefaultIntervalPattern
= null;
222 private static TmfTimestampFormat fDefaultIntervalFormat
= null;
224 // The timestamp pattern
225 private String fPattern
;
227 // The timestamp pattern
228 private List
<String
> fSupplPatterns
= new ArrayList
<String
>();
231 * The supplementary pattern letters. Can be redefined by sub-classes
232 * to either override existing letters or augment the letter set.
233 * If so, the format() method must provide the (re-)implementation of the
236 protected String fSupplPatternLetters
= "TSCN"; //$NON-NLS-1$
239 * The bracketing symbols used to mitigate the risk of a format string
240 * that contains escaped sequences that would conflict with our format
243 /** The open bracket symbol */
244 protected String fOpenBracket
= "[&"; //$NON-NLS-1$
246 /** The closing bracket symbol */
247 protected String fCloseBracket
= "&]"; //$NON-NLS-1$
249 // ------------------------------------------------------------------------
251 // ------------------------------------------------------------------------
254 * The default constructor (uses the default pattern)
256 public TmfTimestampFormat() {
257 this(fDefaultTimePattern
);
261 * The normal constructor
263 * @param pattern the format pattern
265 public TmfTimestampFormat(String pattern
) {
266 calendar
.setTimeZone(TimeZone
.getTimeZone("UTC")); //$NON-NLS-1$
267 applyPattern(pattern
);
271 * The copy constructor
273 * @param other the other format pattern
275 public TmfTimestampFormat(TmfTimestampFormat other
) {
276 this(other
.fPattern
);
279 // ------------------------------------------------------------------------
281 // ------------------------------------------------------------------------
284 * @param pattern the new default time pattern
286 public static void setDefaultTimeFormat(final String pattern
) {
287 fDefaultTimePattern
= pattern
;
288 fDefaultTimeFormat
= new TmfTimestampFormat(fDefaultTimePattern
);
289 TmfSignalManager
.dispatchSignal(new TmfTimestampFormatUpdateSignal(null));
293 * @return the default time format pattern
295 public static TmfTimestampFormat
getDefaulTimeFormat() {
296 if (fDefaultTimeFormat
== null) {
297 fDefaultTimeFormat
= new TmfTimestampFormat(DEFAULT_TIME_PATTERN
);
299 return fDefaultTimeFormat
;
303 * @param pattern the new default interval pattern
305 public static void setDefaultIntervalFormat(final String pattern
) {
306 fDefaultIntervalPattern
= pattern
;
307 fDefaultIntervalFormat
= new TmfTimestampFormat(fDefaultIntervalPattern
);
308 TmfSignalManager
.dispatchSignal(new TmfTimestampFormatUpdateSignal(null));
312 * @return the default interval format pattern
314 public static TmfTimestampFormat
getDefaulIntervalFormat() {
315 if (fDefaultIntervalFormat
== null) {
316 fDefaultIntervalFormat
= new TmfTimestampFormat(DEFAULT_INTERVAL_PATTERN
);
318 return fDefaultIntervalFormat
;
322 * @see java.text.SimpleDateFormat#applyPattern(java.lang.String)
325 public void applyPattern(String pattern
) {
327 String quotedPattern
= quoteSpecificTags(pattern
);
328 super.applyPattern(quotedPattern
);
332 * @see java.text.SimpleDateFormat#toPattern()
335 public String
toPattern() {
339 // ------------------------------------------------------------------------
341 // ------------------------------------------------------------------------
344 * Format the timestamp according to its pattern.
346 * @param value the timestamp value to format (in ns)
347 * @return the formatted timestamp
349 public String
format(long value
) {
351 // Split the timestamp value into its sub-components
352 long sec
= value
/ 1000000000; // seconds
353 long ms
= value
% 1000000000 / 1000000; // milliseconds
354 long cs
= value
% 1000000 / 1000; // microseconds
355 long ns
= value
% 1000; // nanoseconds
357 // Let the base class fill the stuff it knows about
358 StringBuffer result
= new StringBuffer(super.format(sec
* 1000 + ms
));
360 // In the case where there is no separation between 2 supplementary
361 // fields, the pattern will have the form "..'[pat-1]''[pat-2]'.." and
362 // the base class format() will interpret the 2 adjacent quotes as a
363 // wanted character in the result string as ("..[pat-1]'[pat-2]..").
364 // Remove these extra quotes before filling the supplementary fields.
365 int loc
= result
.indexOf(fCloseBracket
+ "'" + fOpenBracket
); //$NON-NLS-1$
367 result
.deleteCharAt(loc
+ fCloseBracket
.length());
368 loc
= result
.indexOf(fCloseBracket
+ "'" + fOpenBracket
); //$NON-NLS-1$
371 // Fill in our extensions
372 for (String pattern
: fSupplPatterns
) {
373 int length
= pattern
.length();
375 // Prepare the format buffer
376 StringBuffer fmt
= new StringBuffer(length
);
377 for (int i
= 0; i
< length
; i
++) {
378 fmt
.append("0"); //$NON-NLS-1$
380 DecimalFormat dfmt
= new DecimalFormat(fmt
.toString());
381 String fmtVal
= ""; //$NON-NLS-1$;
383 // Format the proper value as per the pattern
384 switch (pattern
.charAt(0)) {
386 fmtVal
= dfmt
.format(sec
);
389 fmtVal
= dfmt
.format(ms
);
392 fmtVal
= dfmt
.format(cs
);
395 fmtVal
= dfmt
.format(ns
);
401 // Substitute the placeholder with the formatted value
402 String ph
= new StringBuffer(fOpenBracket
+ pattern
+ fCloseBracket
).toString();
403 loc
= result
.indexOf(ph
);
404 result
.replace(loc
, loc
+ length
+ fOpenBracket
.length() + fCloseBracket
.length(), fmtVal
);
407 return result
.toString();
411 * Parse a string according to the format pattern
413 * @param string the source string
414 * @param ref the reference (base) time
415 * @return the parsed value
416 * @throws ParseException if the string has an invalid format
418 public long parseValue(final String string
, final long ref
) throws ParseException
{
421 if (string
== null || string
.length() == 0) {
425 // The timestamp sub-components
431 // Since we are processing the fractional part, substitute it with
432 // its pattern so the base parser doesn't complain
433 StringBuilder sb
= new StringBuilder(string
);
434 int dot
= string
.indexOf('.');
437 dot
= string
.length();
439 sb
= new StringBuilder(string
.substring(0, dot
));
440 String basePattern
= super.toPattern();
441 int dot2
= basePattern
.indexOf('.');
443 sb
.append(basePattern
.substring(dot2
));
446 // Fill in our extensions
447 for (String pattern
: fSupplPatterns
) {
448 String pat
= fOpenBracket
+ pattern
+ fCloseBracket
;
451 // Extract the substring corresponding to the extra pattern letters
452 // and replace with the pattern so the base parser can do its job.
453 switch (pattern
.charAt(0)) {
455 // Remove everything up to the first "." and compute the
456 // number of seconds since the epoch. If there is no period,
457 // assume an integer value and return immediately
459 return new DecimalFormat("0").parse(string
).longValue() * 1000000000; //$NON-NLS-1$
461 seconds
= new DecimalFormat("0").parse(string
.substring(0, dot
)).longValue(); //$NON-NLS-1$
466 matcher
= MILLISEC_PAT
.matcher(string
.substring(dot
));
467 if (matcher
.find()) {
468 millisec
= new Long(matcher
.group(1));
469 for (int l
= matcher
.group(1).length(); l
< 3; l
++) {
473 stripQuotes(sb
, pattern
);
476 matcher
= MICROSEC_PAT
.matcher(string
.substring(dot
));
477 if (matcher
.find()) {
478 microsec
= new Long(matcher
.group(2));
479 for (int l
= matcher
.group(2).length(); l
< 3; l
++) {
483 stripQuotes(sb
, pattern
);
486 matcher
= NANOSEC_PAT
.matcher(string
.substring(dot
));
487 if (matcher
.find()) {
488 nanosec
= new Long(matcher
.group(3));
489 for (int l
= matcher
.group(3).length(); l
< 3; l
++) {
493 stripQuotes(sb
, pattern
);
500 // If there was no "T" (thus not an interval), parse as a date
502 Date baseDate
= super.parse(sb
.toString());
504 Calendar refTime
= Calendar
.getInstance(TimeZone
.getTimeZone("UTC")); //$NON-NLS-1$
505 refTime
.setTimeInMillis(ref
/ 1000000);
506 Calendar newTime
= Calendar
.getInstance(TimeZone
.getTimeZone("UTC")); //$NON-NLS-1$
507 newTime
.setTimeInMillis(baseDate
.getTime());
509 int[] fields
= new int[] { Calendar
.YEAR
, Calendar
.DAY_OF_YEAR
, Calendar
.MONTH
, Calendar
.DATE
, Calendar
.HOUR
, Calendar
.MINUTE
, Calendar
.SECOND
};
510 for (int field
: fields
) {
511 int value
= newTime
.get(field
);
512 // Do some adjustments...
513 if (field
== Calendar
.YEAR
) {
515 } else if (field
== Calendar
.DATE
|| field
== Calendar
.DAY_OF_YEAR
) {
518 // ... and fill-in the empty fields
520 newTime
.set(field
, refTime
.get(field
));
521 } else if (field
== Calendar
.DAY_OF_YEAR
) {
522 newTime
.set(field
, value
);
524 break; // Get out as soon as we have a significant value
527 seconds
= newTime
.getTimeInMillis() / 1000;
530 // Compute the value in ns
531 return seconds
* 1000000000 + millisec
* 1000000 + microsec
* 1000 + nanosec
;
535 * Parse a string according to the format pattern
537 * @param string the source string
538 * @return the parsed value
539 * @throws ParseException if the string has an invalid format
541 public long parseValue(final String string
) throws ParseException
{
542 long result
= parseValue(string
, 0);
547 // ------------------------------------------------------------------------
549 // ------------------------------------------------------------------------
552 * Copy the pattern but quote (bracket with "[&" and "&]") the
553 * TmfTimestampFormat specific tags so these fields are treated as
554 * comments by the base class.
556 * It also keeps track of the corresponding quoted fields so they can be
557 * properly populated later on (by format()).
559 * @param pattern the 'extended' pattern
560 * @return the quoted and bracketed pattern
562 private String
quoteSpecificTags(final String pattern
) {
564 StringBuffer result
= new StringBuffer();
566 int length
= pattern
.length();
567 boolean inQuote
= false;
569 for (int i
= 0; i
< length
; i
++) {
570 char c
= pattern
.charAt(i
);
573 // '' is treated as a single quote regardless of being
574 // in a quoted section.
575 if ((i
+ 1) < length
) {
576 c
= pattern
.charAt(i
+ 1);
587 if (fSupplPatternLetters
.indexOf(c
) != -1) {
588 StringBuilder pat
= new StringBuilder();
590 result
.insert(result
.length() - 1, "'" + fOpenBracket
); //$NON-NLS-1$
591 while ((i
+ 1) < length
&& pattern
.charAt(i
+ 1) == c
) {
596 result
.append(fCloseBracket
+ "'"); //$NON-NLS-1$
597 fSupplPatterns
.add(pat
.toString());
601 return result
.toString();
605 * Remove the quotes from the pattern
610 private void stripQuotes(StringBuilder sb
, String pattern
) {
611 String pt
= "'" + fOpenBracket
+ pattern
+ fCloseBracket
+ "'"; //$NON-NLS-1$//$NON-NLS-2$
612 int l
= sb
.indexOf(pt
);
614 sb
.delete(l
+ pt
.length() - 1, l
+ pt
.length());