001: package org.apache.commons.net.ntp;
002:
003: /*
004: * Copyright 2001-2005 The Apache Software Foundation
005: *
006: * Licensed under the Apache License, Version 2.0 (the "License");
007: * you may not use this file except in compliance with the License.
008: * You may obtain a copy of the License at
009: *
010: * http://www.apache.org/licenses/LICENSE-2.0
011: *
012: * Unless required by applicable law or agreed to in writing, software
013: * distributed under the License is distributed on an "AS IS" BASIS,
014: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015: * See the License for the specific language governing permissions and
016: * limitations under the License.
017: */
018:
019: import java.util.TimeZone;
020: import java.util.Date;
021: import java.util.Locale;
022: import java.lang.ref.SoftReference;
023: import java.text.SimpleDateFormat;
024: import java.text.DateFormat;
025:
026: /***
027: * TimeStamp class represents the Network Time Protocol (NTP) timestamp
028: * as defined in RFC-1305 and SNTP (RFC-2030). It is represented as a
029: * 64-bit unsigned fixed-point number in seconds relative to 0-hour on 1-January-1900.
030: * The 32-bit low-order bits are the fractional seconds whose precision is
031: * about 200 picoseconds. Assumes overflow date when date passes MAX_LONG
032: * and reverts back to 0 is 2036 and not 1900. Test for most significant
033: * bit: if MSB=0 then 2036 basis is used otherwise 1900 if MSB=1.
034: * <p>
035: * Methods exist to convert NTP timestamps to and from the equivalent Java date
036: * representation, which is the number of milliseconds since the standard base
037: * time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
038: * </p>
039: *
040: * @author Jason Mathews, MITRE Corp
041: * @version $Revision: 165675 $ $Date: 2005-05-02 15:09:55 -0500 (Mon, 02 May 2005) $
042: * @see java.util.Date
043: */
044: public class TimeStamp implements java.io.Serializable, Comparable {
045:
046: /**
047: * baseline NTP time if bit-0=0 -> 7-Feb-2036 @ 06:28:16 UTC
048: */
049: protected static final long msb0baseTime = 2085978496000L;
050:
051: /**
052: * baseline NTP time if bit-0=1 -> 1-Jan-1900 @ 01:00:00 UTC
053: */
054: protected static final long msb1baseTime = -2208988800000L;
055:
056: /**
057: * Default NTP date string format. E.g. Fri, Sep 12 2003 21:06:23.860.
058: * See <code>java.text.SimpleDateFormat</code> for code descriptions.
059: */
060: public final static String NTP_DATE_FORMAT = "EEE, MMM dd yyyy HH:mm:ss.SSS";
061:
062: /*
063: * Caches for the DateFormatters used by various toString methods.
064: */
065: private static SoftReference simpleFormatter = null;
066: private static SoftReference utcFormatter = null;
067:
068: /**
069: * NTP timestamp value: 64-bit unsigned fixed-point number as defined in RFC-1305
070: * with high-order 32 bits the seconds field and the low-order 32-bits the
071: * fractional field.
072: */
073: private long ntpTime;
074:
075: private static final long serialVersionUID = 8139806907588338737L;
076:
077: // initialization of static time bases
078: /*
079: static {
080: TimeZone utcZone = TimeZone.getTimeZone("UTC");
081: Calendar calendar = Calendar.getInstance(utcZone);
082: calendar.set(1900, Calendar.JANUARY, 1, 0, 0, 0);
083: calendar.set(Calendar.MILLISECOND, 0);
084: msb1baseTime = calendar.getTime().getTime();
085: calendar.set(2036, Calendar.FEBRUARY, 7, 6, 28, 16);
086: calendar.set(Calendar.MILLISECOND, 0);
087: msb0baseTime = calendar.getTime().getTime();
088: }
089: */
090:
091: /***
092: * Constructs a newly allocated NTP timestamp object
093: * that represents the native 64-bit long argument.
094: */
095: public TimeStamp(long ntpTime) {
096: this .ntpTime = ntpTime;
097: }
098:
099: /***
100: * Constructs a newly allocated NTP timestamp object
101: * that represents the value represented by the string
102: * in hexdecimal form (e.g. "c1a089bd.fc904f6d").
103: *
104: * @throws NumberFormatException - if the string does not contain a parsable timestamp.
105: */
106: public TimeStamp(String s) throws NumberFormatException {
107: ntpTime = decodeNtpHexString(s);
108: }
109:
110: /***
111: * Constructs a newly allocated NTP timestamp object
112: * that represents the Java Date argument.
113: *
114: * @param d - the Date to be represented by the Timestamp object.
115: */
116: public TimeStamp(Date d) {
117: ntpTime = (d == null) ? 0 : toNtpTime(d.getTime());
118: }
119:
120: /***
121: * Returns the value of this Timestamp as a long value.
122: *
123: * @return the 64-bit long value represented by this object.
124: */
125: public long ntpValue() {
126: return ntpTime;
127: }
128:
129: /***
130: * Returns high-order 32-bits representing the seconds of this NTP timestamp.
131: *
132: * @return seconds represented by this NTP timestamp.
133: */
134: public long getSeconds() {
135: return (ntpTime >>> 32) & 0xffffffffL;
136: }
137:
138: /***
139: * Returns low-order 32-bits representing the fractional seconds.
140: *
141: * @return fractional seconds represented by this NTP timestamp.
142: */
143: public long getFraction() {
144: return ntpTime & 0xffffffffL;
145: }
146:
147: /***
148: * Convert NTP timestamp to Java standard time.
149: *
150: * @return NTP Timestamp in Java time
151: */
152: public long getTime() {
153: return getTime(ntpTime);
154: }
155:
156: /***
157: * Convert NTP timestamp to Java Date object.
158: *
159: * @return NTP Timestamp in Java Date
160: */
161: public Date getDate() {
162: long time = getTime(ntpTime);
163: return new Date(time);
164: }
165:
166: /***
167: * Convert 64-bit NTP timestamp to Java standard time.
168: *
169: * Note that java time (milliseconds) by definition has less precision
170: * then NTP time (picoseconds) so converting NTP timestamp to java time and back
171: * to NTP timestamp loses precision. For example, Tue, Dec 17 2002 09:07:24.810 EST
172: * is represented by a single Java-based time value of f22cd1fc8a, but its
173: * NTP equivalent are all values ranging from c1a9ae1c.cf5c28f5 to c1a9ae1c.cf9db22c.
174: *
175: * @param ntpTimeValue
176: * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
177: * represented by this NTP timestamp value.
178: */
179: public static long getTime(long ntpTimeValue) {
180: long seconds = (ntpTimeValue >>> 32) & 0xffffffffL; // high-order 32-bits
181: long fraction = ntpTimeValue & 0xffffffffL; // low-order 32-bits
182:
183: // Use round-off on fractional part to preserve going to lower precision
184: fraction = Math.round(1000D * fraction / 0x100000000L);
185:
186: /*
187: * If the most significant bit (MSB) on the seconds field is set we use
188: * a different time base. The following text is a quote from RFC-2030 (SNTP v4):
189: *
190: * If bit 0 is set, the UTC time is in the range 1968-2036 and UTC time
191: * is reckoned from 0h 0m 0s UTC on 1 January 1900. If bit 0 is not set,
192: * the time is in the range 2036-2104 and UTC time is reckoned from
193: * 6h 28m 16s UTC on 7 February 2036.
194: */
195: long msb = seconds & 0x80000000L;
196: if (msb == 0) {
197: // use base: 7-Feb-2036 @ 06:28:16 UTC
198: return msb0baseTime + (seconds * 1000) + fraction;
199: } else {
200: // use base: 1-Jan-1900 @ 01:00:00 UTC
201: return msb1baseTime + (seconds * 1000) + fraction;
202: }
203: }
204:
205: /***
206: * Helper method to convert Java time to NTP timestamp object.
207: * Note that Java time (milliseconds) by definition has less precision
208: * then NTP time (picoseconds) so converting Ntptime to Javatime and back
209: * to Ntptime loses precision. For example, Tue, Dec 17 2002 09:07:24.810
210: * is represented by a single Java-based time value of f22cd1fc8a, but its
211: * NTP equivalent are all values from c1a9ae1c.cf5c28f5 to c1a9ae1c.cf9db22c.
212: * @param date the milliseconds since January 1, 1970, 00:00:00 GMT.
213: * @return NTP timestamp object at the specified date.
214: */
215: public static TimeStamp getNtpTime(long date) {
216: return new TimeStamp(toNtpTime(date));
217: }
218:
219: /***
220: * Constructs a NTP timestamp object and initializes it so that
221: * it represents the time at which it was allocated, measured to the
222: * nearest millisecond.
223: * @return NTP timestamp object set to the current time.
224: * @see java.lang.System#currentTimeMillis()
225: */
226: public static TimeStamp getCurrentTime() {
227: return getNtpTime(System.currentTimeMillis());
228: }
229:
230: /***
231: * Convert NTP timestamp hexstring (e.g. "c1a089bd.fc904f6d") to the NTP
232: * 64-bit unsigned fixed-point number.
233: *
234: * @return NTP 64-bit timestamp value.
235: * @throws NumberFormatException - if the string does not contain a parsable timestamp.
236: */
237: protected static long decodeNtpHexString(String s)
238: throws NumberFormatException {
239: if (s == null) {
240: throw new NumberFormatException("null");
241: }
242: int ind = s.indexOf('.');
243: if (ind == -1) {
244: if (s.length() == 0)
245: return 0;
246: return Long.parseLong(s, 16) << 32; // no decimal
247: }
248:
249: return Long.parseLong(s.substring(0, ind), 16) << 32
250: | Long.parseLong(s.substring(ind + 1), 16);
251: }
252:
253: /***
254: * Parses the string argument as a NTP hexidecimal timestamp representation string
255: * (e.g. "c1a089bd.fc904f6d").
256: *
257: * @param s - hexstring.
258: * @return the Timestamp represented by the argument in hexidecimal.
259: * @throws NumberFormatException - if the string does not contain a parsable timestamp.
260: */
261: public static TimeStamp parseNtpString(String s)
262: throws NumberFormatException {
263: return new TimeStamp(decodeNtpHexString(s));
264: }
265:
266: /***
267: * Converts Java time to 64-bit NTP time representation.
268: *
269: * @param t Java time
270: * @return NTP timestamp representation of Java time value.
271: */
272: protected static long toNtpTime(long t) {
273: boolean useBase1 = t < msb0baseTime; // time < Feb-2036
274: long baseTime;
275: if (useBase1) {
276: baseTime = t - msb1baseTime; // dates <= Feb-2036
277: } else {
278: // if base0 needed for dates >= Feb-2036
279: baseTime = t - msb0baseTime;
280: }
281:
282: long seconds = baseTime / 1000;
283: long fraction = ((baseTime % 1000) * 0x100000000L) / 1000;
284:
285: if (useBase1) {
286: seconds |= 0x80000000L; // set high-order bit if msb1baseTime 1900 used
287: }
288:
289: long time = seconds << 32 | fraction;
290: return time;
291: }
292:
293: /***
294: * Computes a hashcode for this Timestamp. The result is the exclusive
295: * OR of the two halves of the primitive <code>long</code> value
296: * represented by this <code>TimeStamp</code> object. That is, the hashcode
297: * is the value of the expression:
298: * <blockquote><pre>
299: * (int)(this.ntpValue()^(this.ntpValue() >>> 32))
300: * </pre></blockquote>
301: *
302: * @return a hash code value for this object.
303: */
304: public int hashCode() {
305: return (int) (ntpTime ^ (ntpTime >>> 32));
306: }
307:
308: /***
309: * Compares this object against the specified object.
310: * The result is <code>true</code> if and only if the argument is
311: * not <code>null</code> and is a <code>Long</code> object that
312: * contains the same <code>long</code> value as this object.
313: *
314: * @param obj the object to compare with.
315: * @return <code>true</code> if the objects are the same;
316: * <code>false</code> otherwise.
317: */
318: public boolean equals(Object obj) {
319: if (obj instanceof TimeStamp) {
320: return ntpTime == ((TimeStamp) obj).ntpValue();
321: }
322: return false;
323: }
324:
325: /***
326: * Converts this <code>TimeStamp</code> object to a <code>String</code>.
327: * The NTP timestamp 64-bit long value is represented as hex string with
328: * seconds separated by fractional seconds by a decimal point;
329: * e.g. c1a089bd.fc904f6d <=> Tue, Dec 10 2002 10:41:49.986
330: *
331: * @return NTP timestamp 64-bit long value as hex string with seconds
332: * separated by fractional seconds.
333: */
334: public String toString() {
335: return toString(ntpTime);
336: }
337:
338: /***
339: * Left-pad 8-character hex string with 0's
340: *
341: * @param buf - StringBuffer which is appended with leading 0's.
342: * @param l - a long.
343: */
344: private static void appendHexString(StringBuffer buf, long l) {
345: String s = Long.toHexString(l);
346: for (int i = s.length(); i < 8; i++)
347: buf.append('0');
348: buf.append(s);
349: }
350:
351: /***
352: * Converts 64-bit NTP timestamp value to a <code>String</code>.
353: * The NTP timestamp value is represented as hex string with
354: * seconds separated by fractional seconds by a decimal point;
355: * e.g. c1a089bd.fc904f6d <=> Tue, Dec 10 2002 10:41:49.986
356: *
357: * @return NTP timestamp 64-bit long value as hex string with seconds
358: * separated by fractional seconds.
359: */
360: public static String toString(long ntpTime) {
361: StringBuffer buf = new StringBuffer();
362: // high-order second bits (32..63) as hexstring
363: appendHexString(buf, (ntpTime >>> 32) & 0xffffffffL);
364:
365: // low-order fractional seconds bits (0..31) as hexstring
366: buf.append('.');
367: appendHexString(buf, ntpTime & 0xffffffffL);
368:
369: return buf.toString();
370: }
371:
372: /***
373: * Converts this <code>TimeStamp</code> object to a <code>String</code>
374: * of the form:
375: * <blockquote><pre>
376: * EEE, MMM dd yyyy HH:mm:ss.SSS</pre></blockquote>
377: * See java.text.SimpleDataFormat for code descriptions.
378: *
379: * @return a string representation of this date.
380: */
381: public String toDateString() {
382: DateFormat formatter = null;
383: if (simpleFormatter != null) {
384: formatter = (DateFormat) simpleFormatter.get();
385: }
386: if (formatter == null) {
387: // No cache yet, or cached formatter GC'd
388: formatter = new SimpleDateFormat(NTP_DATE_FORMAT, Locale.US);
389: formatter.setTimeZone(TimeZone.getDefault());
390: simpleFormatter = new SoftReference(formatter);
391: }
392: Date ntpDate = getDate();
393: synchronized (formatter) {
394: return formatter.format(ntpDate);
395: }
396: }
397:
398: /***
399: * Converts this <code>TimeStamp</code> object to a <code>String</code>
400: * of the form:
401: * <blockquote><pre>
402: * EEE, MMM dd yyyy HH:mm:ss.SSS UTC</pre></blockquote>
403: * See java.text.SimpleDataFormat for code descriptions.
404: *
405: * @return a string representation of this date in UTC.
406: */
407: public String toUTCString() {
408: DateFormat formatter = null;
409: if (utcFormatter != null)
410: formatter = (DateFormat) utcFormatter.get();
411: if (formatter == null) {
412: // No cache yet, or cached formatter GC'd
413: formatter = new SimpleDateFormat(
414: NTP_DATE_FORMAT + " 'UTC'", Locale.US);
415: formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
416: utcFormatter = new SoftReference(formatter);
417: }
418: Date ntpDate = getDate();
419: synchronized (formatter) {
420: return formatter.format(ntpDate);
421: }
422: }
423:
424: /***
425: * Compares two Timestamps numerically.
426: *
427: * @param anotherTimeStamp - the <code>TimeStamp</code> to be compared.
428: * @return the value <code>0</code> if the argument TimeStamp is equal to
429: * this TimeStamp; a value less than <code>0</code> if this TimeStamp
430: * is numerically less than the TimeStamp argument; and a
431: * value greater than <code>0</code> if this TimeStamp is
432: * numerically greater than the TimeStamp argument
433: * (signed comparison).
434: */
435: public int compareTo(TimeStamp anotherTimeStamp) {
436: long this Val = this .ntpTime;
437: long anotherVal = anotherTimeStamp.ntpTime;
438: return (this Val < anotherVal ? -1 : (this Val == anotherVal ? 0
439: : 1));
440: }
441:
442: /***
443: * Compares this TimeStamp to another Object. If the Object is a TimeStamp,
444: * this function behaves like <code>compareTo(TimeStamp)</code>. Otherwise,
445: * it throws a <code>ClassCastException</code> (as TimeStamps are comparable
446: * only to other TimeStamps).
447: *
448: * @param o the <code>Object</code> to be compared.
449: * @return the value <code>0</code> if the argument is a TimeStamp
450: * numerically equal to this TimeStamp; a value less than
451: * <code>0</code> if the argument is a TimeStamp numerically
452: * greater than this TimeStamp; and a value greater than
453: * <code>0</code> if the argument is a TimeStamp numerically
454: * less than this TimeStamp.
455: * @exception ClassCastException if the argument is not a
456: * <code>TimeStamp</code>.
457: * @see java.lang.Comparable
458: */
459: public int compareTo(Object o) {
460: return compareTo((TimeStamp) o);
461: }
462:
463: }
|