TimeStamp.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.net.ntp;

  18. import java.io.Serializable;
  19. import java.text.DateFormat;
  20. import java.text.SimpleDateFormat;
  21. import java.util.Date;
  22. import java.util.Locale;
  23. import java.util.TimeZone;

  24. /**
  25.  * TimeStamp class represents the Network Time Protocol (NTP) timestamp as defined in RFC-1305 and SNTP (RFC-2030). It is represented as a 64-bit unsigned
  26.  * fixed-point number in seconds relative to 0-hour on 1-January-1900. The 32-bit low-order bits are the fractional seconds whose precision is about 200
  27.  * picoseconds. Assumes overflow date when date passes MAX_LONG and reverts back to 0 is 2036 and not 1900. Test for most significant bit: if MSB=0 then 2036
  28.  * basis is used otherwise 1900 if MSB=1.
  29.  * <p>
  30.  * Methods exist to convert NTP timestamps to and from the equivalent Java date representation, which is the number of milliseconds since the standard base time
  31.  * known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
  32.  * </p>
  33.  *
  34.  * @see java.util.Date
  35.  */
  36. public class TimeStamp implements Serializable, Comparable<TimeStamp> {
  37.     private static final long serialVersionUID = 8139806907588338737L;

  38.     /**
  39.      * Baseline NTP time if bit-0=0 is 7-Feb-2036 @ 06:28:16 UTC
  40.      */
  41.     protected static final long msb0baseTime = 2085978496000L;

  42.     /**
  43.      * Baseline NTP time if bit-0=1 is 1-Jan-1900 @ 01:00:00 UTC
  44.      */
  45.     protected static final long msb1baseTime = -2208988800000L;

  46.     /**
  47.      * Default NTP date string format. E.g. Fri, Sep 12 2003 21:06:23.860. See <code>java.text.SimpleDateFormat</code> for code descriptions.
  48.      */
  49.     public static final String NTP_DATE_FORMAT = "EEE, MMM dd yyyy HH:mm:ss.SSS";

  50.     /**
  51.      * Left-pad 8-character hexadecimal string with 0's
  52.      *
  53.      * @param buf - StringBuilder which is appended with leading 0's.
  54.      * @param l   - a long.
  55.      */
  56.     private static void appendHexString(final StringBuilder buf, final long l) {
  57.         final String s = Long.toHexString(l);
  58.         for (int i = s.length(); i < 8; i++) {
  59.             buf.append('0');
  60.         }
  61.         buf.append(s);
  62.     }

  63.     /**
  64.      * Convert NTP timestamp hexstring (e.g. "c1a089bd.fc904f6d") to the NTP 64-bit unsigned fixed-point number.
  65.      *
  66.      * @param hexString the string to convert
  67.      *
  68.      * @return NTP 64-bit timestamp value.
  69.      * @throws NumberFormatException - if the string does not contain a parsable timestamp.
  70.      */
  71.     protected static long decodeNtpHexString(final String hexString) throws NumberFormatException {
  72.         if (hexString == null) {
  73.             throw new NumberFormatException("null");
  74.         }
  75.         final int ind = hexString.indexOf('.');
  76.         if (ind == -1) {
  77.             if (hexString.isEmpty()) {
  78.                 return 0;
  79.             }
  80.             return Long.parseLong(hexString, 16) << 32; // no decimal
  81.         }

  82.         return Long.parseLong(hexString.substring(0, ind), 16) << 32 | Long.parseLong(hexString.substring(ind + 1), 16);
  83.     }

  84.     /**
  85.      * Constructs a NTP timestamp object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
  86.      *
  87.      * @return NTP timestamp object set to the current time.
  88.      * @see System#currentTimeMillis()
  89.      */
  90.     public static TimeStamp getCurrentTime() {
  91.         return getNtpTime(System.currentTimeMillis());
  92.     }

  93.     // initialization of static time bases
  94.     /*
  95.      * static { TimeZone utcZone = TimeZone.getTimeZone("UTC"); Calendar calendar = Calendar.getInstance(utcZone); calendar.set(1900, Calendar.JANUARY, 1, 0, 0,
  96.      * 0); calendar.set(Calendar.MILLISECOND, 0); msb1baseTime = calendar.getTime().getTime(); calendar.set(2036, Calendar.FEBRUARY, 7, 6, 28, 16);
  97.      * calendar.set(Calendar.MILLISECOND, 0); msb0baseTime = calendar.getTime().getTime(); }
  98.      */

  99.     /**
  100.      * Helper method to convert Java time to NTP timestamp object. Note that Java time (milliseconds) by definition has less precision than NTP time
  101.      * (picoseconds) so converting Ntptime to Javatime and back to Ntptime loses precision. For example, Tue, Dec 17 2002 09:07:24.810 is represented by a
  102.      * single Java-based time value of f22cd1fc8a, but its NTP equivalent are all values from c1a9ae1c.cf5c28f5 to c1a9ae1c.cf9db22c.
  103.      *
  104.      * @param dateMillis the milliseconds since January 1, 1970, 00:00:00 GMT.
  105.      * @return NTP timestamp object at the specified date.
  106.      */
  107.     public static TimeStamp getNtpTime(final long dateMillis) {
  108.         return new TimeStamp(toNtpTime(dateMillis));
  109.     }

  110.     /**
  111.      * Converts 64-bit NTP timestamp to Java standard time.
  112.      *
  113.      * Note that java time (milliseconds) by definition has less precision than NTP time (picoseconds) so converting NTP timestamp to Java time and back to NTP
  114.      * timestamp loses precision. For example, Tue, Dec 17 2002 09:07:24.810 EST is represented by a single Java-based time value of f22cd1fc8a, but its NTP
  115.      * equivalent are all values ranging from c1a9ae1c.cf5c28f5 to c1a9ae1c.cf9db22c.
  116.      *
  117.      * @param ntpTimeValue the input time
  118.      * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this NTP timestamp value.
  119.      */
  120.     public static long getTime(final long ntpTimeValue) {
  121.         final long seconds = ntpTimeValue >>> 32 & 0xffffffffL; // high-order 32-bits
  122.         long fraction = ntpTimeValue & 0xffffffffL; // low-order 32-bits

  123.         // Use round-off on fractional part to preserve going to lower precision
  124.         fraction = Math.round(1000D * fraction / 0x100000000L);

  125.         /*
  126.          * If the most significant bit (MSB) on the seconds field is set we use a different time base. The following text is a quote from RFC-2030 (SNTP v4):
  127.          *
  128.          * If bit 0 is set, the UTC time is in the range 1968-2036 and UTC time is reckoned from 0h 0m 0s UTC on 1 January 1900. If bit 0 is not set, the time
  129.          * is in the range 2036-2104 and UTC time is reckoned from 6h 28m 16s UTC on 7 February 2036.
  130.          */
  131.         final long msb = seconds & 0x80000000L;
  132.         if (msb == 0) {
  133.             // use base: 7-Feb-2036 @ 06:28:16 UTC
  134.             return msb0baseTime + seconds * 1000 + fraction;
  135.         }
  136.         // use base: 1-Jan-1900 @ 01:00:00 UTC
  137.         return msb1baseTime + seconds * 1000 + fraction;
  138.     }

  139.     /**
  140.      * Parses the string argument as a NTP hexidecimal timestamp representation string (e.g. "c1a089bd.fc904f6d").
  141.      *
  142.      * @param s - hexstring.
  143.      * @return the Timestamp represented by the argument in hexidecimal.
  144.      * @throws NumberFormatException - if the string does not contain a parsable timestamp.
  145.      */
  146.     public static TimeStamp parseNtpString(final String s) throws NumberFormatException {
  147.         return new TimeStamp(decodeNtpHexString(s));
  148.     }

  149.     /**
  150.      * Converts Java time to 64-bit NTP time representation.
  151.      *
  152.      * @param millis Java time
  153.      * @return NTP timestamp representation of Java time value.
  154.      */
  155.     protected static long toNtpTime(final long millis) {
  156.         final boolean useBase1 = millis < msb0baseTime; // time < Feb-2036
  157.         final long baseTimeMillis;
  158.         if (useBase1) {
  159.             baseTimeMillis = millis - msb1baseTime; // dates <= Feb-2036
  160.         } else {
  161.             // if base0 needed for dates >= Feb-2036
  162.             baseTimeMillis = millis - msb0baseTime;
  163.         }

  164.         long seconds = baseTimeMillis / 1000;
  165.         final long fraction = baseTimeMillis % 1000 * 0x100000000L / 1000;

  166.         if (useBase1) {
  167.             seconds |= 0x80000000L; // set high-order bit if msb1baseTime 1900 used
  168.         }

  169.         return seconds << 32 | fraction;
  170.     }

  171.     /**
  172.      * Converts 64-bit NTP timestamp value to a <code>String</code>. The NTP timestamp value is represented as hexadecimal string with seconds separated by
  173.      * fractional seconds by a decimal point; e.g. c1a089bd.fc904f6d == Tue, Dec 10 2002 10:41:49.986
  174.      *
  175.      * @param ntpTime the 64 bit timestamp
  176.      *
  177.      * @return NTP timestamp 64-bit long value as hexadecimal string with seconds separated by fractional seconds.
  178.      */
  179.     public static String toString(final long ntpTime) {
  180.         final StringBuilder buf = new StringBuilder();
  181.         // high-order second bits (32..63) as hexstring
  182.         appendHexString(buf, ntpTime >>> 32 & 0xffffffffL);

  183.         // low-order fractional seconds bits (0..31) as hexstring
  184.         buf.append('.');
  185.         appendHexString(buf, ntpTime & 0xffffffffL);

  186.         return buf.toString();
  187.     }

  188.     /**
  189.      * NTP timestamp value: 64-bit unsigned fixed-point number as defined in RFC-1305 with high-order 32 bits the seconds field and the low-order 32-bits the
  190.      * fractional field.
  191.      */
  192.     private final long ntpTime;

  193.     private DateFormat simpleFormatter;

  194.     private DateFormat utcFormatter;

  195.     /**
  196.      * Constructs a newly allocated NTP timestamp object that represents the Java Date argument.
  197.      *
  198.      * @param d - the Date to be represented by the Timestamp object.
  199.      */
  200.     public TimeStamp(final Date d) {
  201.         ntpTime = d == null ? 0 : toNtpTime(d.getTime());
  202.     }

  203.     /**
  204.      * Constructs a newly allocated NTP timestamp object that represents the native 64-bit long argument.
  205.      *
  206.      * @param ntpTime the timestamp
  207.      */
  208.     public TimeStamp(final long ntpTime) {
  209.         this.ntpTime = ntpTime;
  210.     }

  211.     /**
  212.      * Constructs a newly allocated NTP timestamp object that represents the value represented by the string in hexdecimal form (e.g. "c1a089bd.fc904f6d").
  213.      *
  214.      * @param hexStamp the hexadecimal timestamp
  215.      *
  216.      * @throws NumberFormatException - if the string does not contain a parsable timestamp.
  217.      */
  218.     public TimeStamp(final String hexStamp) throws NumberFormatException {
  219.         ntpTime = decodeNtpHexString(hexStamp);
  220.     }

  221.     /**
  222.      * Compares two Timestamps numerically.
  223.      *
  224.      * @param anotherTimeStamp - the <code>TimeStamp</code> to be compared.
  225.      * @return the value <code>0</code> if the argument TimeStamp is equal to this TimeStamp; a value less than <code>0</code> if this TimeStamp is numerically
  226.      *         less than the TimeStamp argument; and a value greater than <code>0</code> if this TimeStamp is numerically greater than the TimeStamp argument
  227.      *         (signed comparison).
  228.      */
  229.     @Override
  230.     public int compareTo(final TimeStamp anotherTimeStamp) {
  231.         final long thisVal = this.ntpTime;
  232.         final long anotherVal = anotherTimeStamp.ntpTime;
  233.         return Long.compare(thisVal, anotherVal);
  234.     }

  235.     /**
  236.      * Compares this object against the specified object. The result is {@code true} if and only if the argument is not {@code null} and is a
  237.      * <code>Long</code> object that contains the same <code>long</code> value as this object.
  238.      *
  239.      * @param obj the object to compare with.
  240.      * @return {@code true} if the objects are the same; {@code false} otherwise.
  241.      */
  242.     @Override
  243.     public boolean equals(final Object obj) {
  244.         if (obj instanceof TimeStamp) {
  245.             return ntpTime == ((TimeStamp) obj).ntpValue();
  246.         }
  247.         return false;
  248.     }

  249.     /**
  250.      * Converts NTP timestamp to Java Date object.
  251.      *
  252.      * @return NTP Timestamp in Java Date
  253.      */
  254.     public Date getDate() {
  255.         return new Date(getTime(ntpTime));
  256.     }

  257.     /**
  258.      * Returns low-order 32-bits representing the fractional seconds.
  259.      *
  260.      * @return fractional seconds represented by this NTP timestamp.
  261.      */
  262.     public long getFraction() {
  263.         return ntpTime & 0xffffffffL;
  264.     }

  265.     /**
  266.      * Returns high-order 32-bits representing the seconds of this NTP timestamp.
  267.      *
  268.      * @return seconds represented by this NTP timestamp.
  269.      */
  270.     public long getSeconds() {
  271.         return ntpTime >>> 32 & 0xffffffffL;
  272.     }

  273.     /**
  274.      * Converts NTP timestamp to Java standard time.
  275.      *
  276.      * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this NTP timestamp value.
  277.      */
  278.     public long getTime() {
  279.         return getTime(ntpTime);
  280.     }

  281.     /**
  282.      * Computes a hash code for this Timestamp. The result is the exclusive OR of the two halves of the primitive <code>long</code> value represented by this
  283.      * <code>TimeStamp</code> object. That is, the hash code is the value of the expression: <blockquote>
  284.      *
  285.      * <pre>
  286.      * {@code
  287.      * (int) (this.ntpValue() ^ (this.ntpValue() >>> 32))
  288.      * }
  289.      * </pre>
  290.      *
  291.      * </blockquote>
  292.      *
  293.      * @return a hash code value for this object.
  294.      */
  295.     @Override
  296.     public int hashCode() {
  297.         return (int) (ntpTime ^ ntpTime >>> 32);
  298.     }

  299.     /**
  300.      * Returns the value of this Timestamp as a long value.
  301.      *
  302.      * @return the 64-bit long value represented by this object.
  303.      */
  304.     public long ntpValue() {
  305.         return ntpTime;
  306.     }

  307.     private void readObject(final java.io.ObjectInputStream in) {
  308.         throw new UnsupportedOperationException("Serialization is not supported");
  309.     }

  310.     /**
  311.      * Converts this <code>TimeStamp</code> object to a <code>String</code> of the form: <blockquote>
  312.      *
  313.      * <pre>
  314.      * EEE, MMM dd yyyy HH:mm:ss.SSS
  315.      * </pre>
  316.      *
  317.      * </blockquote> See java.text.SimpleDataFormat for code descriptions.
  318.      *
  319.      * @return a string representation of this date.
  320.      */
  321.     public String toDateString() {
  322.         if (simpleFormatter == null) {
  323.             simpleFormatter = new SimpleDateFormat(NTP_DATE_FORMAT, Locale.US);
  324.             simpleFormatter.setTimeZone(TimeZone.getDefault());
  325.         }
  326.         final Date ntpDate = getDate();
  327.         return simpleFormatter.format(ntpDate);
  328.     }

  329.     /**
  330.      * Converts this <code>TimeStamp</code> object to a <code>String</code>. The NTP timestamp 64-bit long value is represented as hexadecimal string with
  331.      * seconds separated by fractional seconds by a decimal point; e.g. c1a089bd.fc904f6d == Tue, Dec 10 2002 10:41:49.986
  332.      *
  333.      * @return NTP timestamp 64-bit long value as hexadecimal string with seconds separated by fractional seconds.
  334.      */
  335.     @Override
  336.     public String toString() {
  337.         return toString(ntpTime);
  338.     }

  339.     /*
  340.      * Serialization is unnecessary for this class. Reject attempts to do so until such time as the Serializable attribute can be dropped.
  341.      */

  342.     /**
  343.      * Converts this <code>TimeStamp</code> object to a <code>String</code> of the form: <blockquote>
  344.      *
  345.      * <pre>
  346.      * EEE, MMM dd yyyy HH:mm:ss.SSS UTC
  347.      * </pre>
  348.      *
  349.      * </blockquote> See java.text.SimpleDataFormat for code descriptions.
  350.      *
  351.      * @return a string representation of this date in UTC.
  352.      */
  353.     public String toUTCString() {
  354.         if (utcFormatter == null) {
  355.             utcFormatter = new SimpleDateFormat(NTP_DATE_FORMAT + " 'UTC'", Locale.US);
  356.             utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
  357.         }
  358.         final Date ntpDate = getDate();
  359.         return utcFormatter.format(ntpDate);
  360.     }

  361.     private void writeObject(final java.io.ObjectOutputStream out) {
  362.         throw new UnsupportedOperationException("Serialization is not supported");
  363.     }

  364. }