    001    package 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
    021    import java.text.DateFormat;
    022    import java.text.SimpleDateFormat;
    023    import java.util.Date;
    024    import java.util.Locale;
    025    import 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     * @author Jason Mathews, MITRE Corp
    042     * @version $Revision: 1084392 $ $Date: 2011-03-22 22:39:08 +0000 (Tue, 22 Mar 2011) $
    043     * @see java.util.Date
    044     */
    045    public class TimeStamp implements java.io.Serializable, Comparable<TimeStamp>
    046    {
    047        private static final long serialVersionUID = 8139806907588338737L;
    048
    049        /**
    050         * baseline NTP time if bit-0=0 -> 7-Feb-2036 @ 06:28:16 UTC
    051         */
    052        protected static final long msb0baseTime = 2085978496000L;
    053
    054        /**
    055         *  baseline NTP time if bit-0=1 -> 1-Jan-1900 @ 01:00:00 UTC
    056         */
    057        protected static final long msb1baseTime = -2208988800000L;
    058
    059        /**
    060         * Default NTP date string format. E.g. Fri, Sep 12 2003 21:06:23.860.
    061         * See <code>java.text.SimpleDateFormat</code> for code descriptions.
    062         */
    063        public final static String NTP_DATE_FORMAT = "EEE, MMM dd yyyy HH:mm:ss.SSS";
    064
    065        /**
    066         * NTP timestamp value: 64-bit unsigned fixed-point number as defined in RFC-1305
    067         * with high-order 32 bits the seconds field and the low-order 32-bits the
    068         * fractional field.
    069         */
    070        private final long ntpTime;
    071
    072        private DateFormat simpleFormatter;
    073        private DateFormat utcFormatter;
    074
    075        // initialization of static time bases
    076        /*
    077        static {
    078            TimeZone utcZone = TimeZone.getTimeZone("UTC");
    079            Calendar calendar = Calendar.getInstance(utcZone);
    080            calendar.set(1900, Calendar.JANUARY, 1, 0, 0, 0);
    081            calendar.set(Calendar.MILLISECOND, 0);
    082            msb1baseTime = calendar.getTime().getTime();
    083            calendar.set(2036, Calendar.FEBRUARY, 7, 6, 28, 16);
    084            calendar.set(Calendar.MILLISECOND, 0);
    085            msb0baseTime = calendar.getTime().getTime();
    086        }
    087        */
    088
    089        /***
    090         * Constructs a newly allocated NTP timestamp object
    091         * that represents the native 64-bit long argument.
    092         */
    093        public TimeStamp(long ntpTime)
    094        {
    095            this.ntpTime = ntpTime;
    096        }
    097
    098        /***
    099         * Constructs a newly allocated NTP timestamp object
    100         * that represents the value represented by the string
    101         * in hexdecimal form (e.g. "c1a089bd.fc904f6d").
    102         *
    103         * @throws NumberFormatException - if the string does not contain a parsable timestamp.
    104         */
    105        public TimeStamp(String s) throws NumberFormatException
    106        {
    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        {
    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         * Convert NTP timestamp to Java standard time.
    153         *
    154         * @return NTP Timestamp in Java time
    155         */
    156        public long getTime()
    157        {
    158            return getTime(ntpTime);
    159        }
    160
    161        /***
    162         * Convert NTP timestamp to Java Date object.
    163         *
    164         * @return NTP Timestamp in Java Date
    165         */
    166        public Date getDate()
    167        {
    168            long time = getTime(ntpTime);
    169            return new Date(time);
    170        }
    171
    172        /***
    173         * Convert 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
    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(long ntpTimeValue)
    186        {
    187            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            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            } else {
    207                // use base: 1-Jan-1900 @ 01:00:00 UTC
    208                return msb1baseTime + (seconds * 1000) + fraction;
    209            }
    210        }
    211
    212        /***
    213         * Helper method to convert Java time to NTP timestamp object.
    214         * Note that Java time (milliseconds) by definition has less precision
    215         * then NTP time (picoseconds) so converting Ntptime to Javatime and back
    216         * to Ntptime loses precision. For example, Tue, Dec 17 2002 09:07:24.810
    217         * is represented by a single Java-based time value of f22cd1fc8a, but its
    218         * NTP equivalent are all values from c1a9ae1c.cf5c28f5 to c1a9ae1c.cf9db22c.
    219         * @param   date   the milliseconds since January 1, 1970, 00:00:00 GMT.
    220         * @return NTP timestamp object at the specified date.
    221         */
    222        public static TimeStamp getNtpTime(long date)
    223        {
    224            return new TimeStamp(toNtpTime(date));
    225        }
    226
    227        /***
    228         * Constructs a NTP timestamp object and initializes it so that
    229         * it represents the time at which it was allocated, measured to the
    230         * nearest millisecond.
    231         * @return NTP timestamp object set to the current time.
    232         * @see     java.lang.System#currentTimeMillis()
    233         */
    234        public static TimeStamp getCurrentTime()
    235        {
    236            return getNtpTime(System.currentTimeMillis());
    237        }
    238
    239        /***
    240         * Convert NTP timestamp hexstring (e.g. "c1a089bd.fc904f6d") to the NTP
    241         * 64-bit unsigned fixed-point number.
    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(String s)
    247                throws NumberFormatException
    248        {
    249            if (s == null) {
    250                throw new NumberFormatException("null");
    251            }
    252            int ind = s.indexOf('.');
    253            if (ind == -1) {
    254                if (s.length() == 0) return 0;
    255                return Long.parseLong(s, 16) << 32; // no decimal
    256            }
    257
    258            return Long.parseLong(s.substring(0, ind), 16) << 32 |
    259                    Long.parseLong(s.substring(ind + 1), 16);
    260        }
    261
    262        /***
    263         * Parses the string argument as a NTP hexidecimal timestamp representation string
    264         * (e.g. "c1a089bd.fc904f6d").
    265         *
    266         * @param s - hexstring.
    267         * @return the Timestamp represented by the argument in hexidecimal.
    268         * @throws NumberFormatException - if the string does not contain a parsable timestamp.
    269         */
    270        public static TimeStamp parseNtpString(String s)
    271                throws NumberFormatException
    272        {
    273            return new TimeStamp(decodeNtpHexString(s));
    274        }
    275
    276        /***
    277         * Converts Java time to 64-bit NTP time representation.
    278         *
    279         * @param t Java time
    280         * @return NTP timestamp representation of Java time value.
    281         */
    282        protected static long toNtpTime(long t)
    283        {
    284            boolean useBase1 = t < msb0baseTime;    // time < Feb-2036
    285            long baseTime;
    286            if (useBase1) {
    287                baseTime = t - msb1baseTime; // dates <= Feb-2036
    288            } else {
    289                // if base0 needed for dates >= Feb-2036
    290                baseTime = t - msb0baseTime;
    291            }
    292
    293            long seconds = baseTime / 1000;
    294            long fraction = ((baseTime % 1000) * 0x100000000L) / 1000;
    295
    296            if (useBase1) {
    297                seconds |= 0x80000000L; // set high-order bit if msb1baseTime 1900 used
    298            }
    299
    300            long time = seconds << 32 | fraction;
    301            return time;
    302        }
    303
    304        /***
    305         * Computes a hashcode for this Timestamp. The result is the exclusive
    306         * OR of the two halves of the primitive <code>long</code> value
    307         * represented by this <code>TimeStamp</code> object. That is, the hashcode
    308         * is the value of the expression:
    309         * <blockquote><pre>
    310         * (int)(this.ntpValue()^(this.ntpValue() >>> 32))
    311         * </pre></blockquote>
    312         *
    313         * @return  a hash code value for this object.
    314         */
    315        @Override
    316        public int hashCode()
    317        {
    318            return (int) (ntpTime ^ (ntpTime >>> 32));
    319        }
    320
    321        /***
    322         * Compares this object against the specified object.
    323         * The result is <code>true</code> if and only if the argument is
    324         * not <code>null</code> and is a <code>Long</code> object that
    325         * contains the same <code>long</code> value as this object.
    326         *
    327         * @param   obj   the object to compare with.
    328         * @return  <code>true</code> if the objects are the same;
    329         *          <code>false</code> otherwise.
    330         */
    331        @Override
    332        public boolean equals(Object obj)
    333        {
    334            if (obj instanceof TimeStamp) {
    335                return ntpTime == ((TimeStamp) obj).ntpValue();
    336            }
    337            return false;
    338        }
    339
    340        /***
    341         * Converts this <code>TimeStamp</code> object to a <code>String</code>.
    342         * The NTP timestamp 64-bit long value is represented as hex string with
    343         * seconds separated by fractional seconds by a decimal point;
    344         * e.g. c1a089bd.fc904f6d <=> Tue, Dec 10 2002 10:41:49.986
    345         *
    346         * @return NTP timestamp 64-bit long value as hex string with seconds
    347         * separated by fractional seconds.
    348         */
    349        @Override
    350        public String toString()
    351        {
    352            return toString(ntpTime);
    353        }
    354
    355        /***
    356         * Left-pad 8-character hex string with 0's
    357         *
    358         * @param buf - StringBuilder which is appended with leading 0's.
    359         * @param l - a long.
    360         */
    361        private static void appendHexString(StringBuilder buf, long l)
    362        {
    363            String s = Long.toHexString(l);
    364            for (int i = s.length(); i < 8; i++)
    365                buf.append('0');
    366            buf.append(s);
    367        }
    368
    369        /***
    370         * Converts 64-bit NTP timestamp value to a <code>String</code>.
    371         * The NTP timestamp value is represented as hex string with
    372         * seconds separated by fractional seconds by a decimal point;
    373         * e.g. c1a089bd.fc904f6d <=> Tue, Dec 10 2002 10:41:49.986
    374         *
    375         * @return NTP timestamp 64-bit long value as hex string with seconds
    376         * separated by fractional seconds.
    377         */
    378        public static String toString(long ntpTime)
    379        {
    380            StringBuilder buf = new StringBuilder();
    381            // high-order second bits (32..63) as hexstring
    382            appendHexString(buf, (ntpTime >>> 32) & 0xffffffffL);
    383
    384            // low-order fractional seconds bits (0..31) as hexstring
    385            buf.append('.');
    386            appendHexString(buf, ntpTime & 0xffffffffL);
    387
    388            return buf.toString();
    389        }
    390
    391        /***
    392         * Converts this <code>TimeStamp</code> object to a <code>String</code>
    393         * of the form:
    394         * <blockquote><pre>
    395         * EEE, MMM dd yyyy HH:mm:ss.SSS</pre></blockquote>
    396         * See java.text.SimpleDataFormat for code descriptions.
    397         *
    398         * @return  a string representation of this date.
    399         */
    400        public String toDateString()
    401        {
    402            if (simpleFormatter == null) {
    403                simpleFormatter = new SimpleDateFormat(NTP_DATE_FORMAT, Locale.US);
    404                simpleFormatter.setTimeZone(TimeZone.getDefault());
    405            }
    406            Date ntpDate = getDate();
    407            return simpleFormatter.format(ntpDate);
    408        }
    409
    410        /***
    411         * Converts this <code>TimeStamp</code> object to a <code>String</code>
    412         * of the form:
    413         * <blockquote><pre>
    414         * EEE, MMM dd yyyy HH:mm:ss.SSS UTC</pre></blockquote>
    415         * See java.text.SimpleDataFormat for code descriptions.
    416         *
    417         * @return  a string representation of this date in UTC.
    418         */
    419        public String toUTCString()
    420        {
    421            if (utcFormatter == null) {
    422                utcFormatter = new SimpleDateFormat(NTP_DATE_FORMAT + " 'UTC'",
    423                        Locale.US);
    424                utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    425            }
    426            Date ntpDate = getDate();
    427            return utcFormatter.format(ntpDate);
    428        }
    429
    430        /***
    431         * Compares two Timestamps numerically.
    432         *
    433         * @param   anotherTimeStamp - the <code>TimeStamp</code> to be compared.
    434         * @return  the value <code>0</code> if the argument TimeStamp is equal to
    435         *          this TimeStamp; a value less than <code>0</code> if this TimeStamp
    436         *          is numerically less than the TimeStamp argument; and a
    437         *          value greater than <code>0</code> if this TimeStamp is
    438         *          numerically greater than the TimeStamp argument
    439         *          (signed comparison).
    440         */
    441        public int compareTo(TimeStamp anotherTimeStamp)
    442        {
    443            long thisVal = this.ntpTime;
    444            long anotherVal = anotherTimeStamp.ntpTime;
    445            return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));
    446        }
    447
    448    }