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