Example usage for org.apache.commons.net.ntp TimeInfo getReturnTime

List of usage examples for org.apache.commons.net.ntp TimeInfo getReturnTime

Introduction

In this page you can find the example usage for org.apache.commons.net.ntp TimeInfo getReturnTime.

Prototype

public long getReturnTime() 

Source Link

Document

Returns time at which time message packet was received by local machine.

Usage

From source file:com.cscao.apps.ntplib.NTPClient.java

/**
 * Process <code>TimeInfo</code> object and print its details and return the offset.
 *
 * @param info <code>TimeInfo</code> object.
 *//*  w  w  w  .ja  va 2s.  c o m*/
private long processResponse(TimeInfo info) {
    NtpV3Packet message = info.getMessage();
    if (message == null) {
        return 0;
    }

    int stratum = message.getStratum();
    String refType;
    if (stratum <= 0) {
        refType = "(Unspecified or Unavailable)";
    } else if (stratum == 1) {
        refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
    } else {
        refType = "(Secondary Reference; e.g. via NTP or SNTP)";
    }
    // stratum should be 0..15...
    //        System.out.println(" Stratum: " + stratum + " " + refType);
    details += " Stratum: " + stratum + " " + refType + "\n";

    int version = message.getVersion();
    int li = message.getLeapIndicator();
    //        System.out.println(" leap=" + li + ", version="
    //                + version + ", precision=" + message.getPrecision());

    details += " leap=" + li + ", version=" + version + ", precision=" + message.getPrecision() + "\n";
    details += " mode: " + message.getModeName() + " (" + message.getMode() + ")" + "\n";

    //        System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");
    int poll = message.getPoll();
    // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
    //        System.out.println(" poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll))
    //                + " seconds" + " (2 ** " + poll + ")");

    details += " poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")"
            + "\n";

    double disp = message.getRootDispersionInMillisDouble();

    //        System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
    //                + ", rootdispersion(ms): " + numberFormat.format(disp));

    details += " rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
            + ", rootdispersion(ms): " + numberFormat.format(disp) + "\n";

    int refId = message.getReferenceId();
    String refAddr = NtpUtils.getHostAddress(refId);
    String refName = null;
    if (refId != 0) {
        if (refAddr.equals("127.127.1.0")) {
            refName = "LOCAL"; // This is the ref address for the Local Clock
        } else if (stratum >= 2) {
            // If reference id has 127.127 prefix then it uses its own reference clock
            // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
            // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
            if (!refAddr.startsWith("127.127")) {
                try {
                    InetAddress addr = InetAddress.getByName(refAddr);
                    String name = addr.getHostName();
                    if (name != null && !name.equals(refAddr)) {
                        refName = name;
                    }
                } catch (UnknownHostException e) {
                    // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2)
                    // ref not valid host maybe it's a reference clock name?
                    // otherwise just show the ref IP address.
                    refName = NtpUtils.getReferenceClock(message);
                }
            }
        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
            refName = NtpUtils.getReferenceClock(message);
            // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
        }
        // otherwise give up on naming the beast...
    }
    if (refName != null && refName.length() > 1) {
        refAddr += " (" + refName + ")";
    }
    //        System.out.println(" Reference Identifier:\t" + refAddr);

    details += " Reference Identifier:\t" + refAddr + "\n";

    TimeStamp refNtpTime = message.getReferenceTimeStamp();
    //        System.out.println(" Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());

    details += " Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString() + "\n";

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();
    //        System.out.println(" Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString());

    details += " Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString() + "\n";

    long destTime = info.getReturnTime();
    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
    //        System.out.println(" Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());

    details += " Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString() + "\n";

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
    //        System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString());

    details += " Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString() + "\n";

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
    //        System.out.println(" Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString());

    details += " Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString() + "\n";

    info.computeDetails(); // compute offset/delay if not already done
    Long offsetValue = info.getOffset();
    Long delayValue = info.getDelay();
    String delay = (delayValue == null) ? "N/A" : delayValue.toString();
    String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

    //        System.out.println(" Roundtrip delay(ms)=" + delay
    //                + ", clock offset(ms)=" + offset); // offset in ms
    details += " Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset + "\n";

    // calibrate local clock
    //        return (offsetValue == null) ? -1 : (destNtpTime.getTime() + offsetValue);

    // return offset
    return (offsetValue == null) ? 0 : offsetValue;
}

From source file:ntp.NTPClient.java

/**
 * Process <code>TimeInfo</code> object and print its details.
 * @param info <code>TimeInfo</code> object.
 *///from   w w  w  .j  av  a 2 s . co  m
public static void processResponse(TimeInfo info) {
    NtpV3Packet message = info.getMessage();
    int stratum = message.getStratum();
    String refType;
    if (stratum <= 0) {
        refType = "(Unspecified or Unavailable)";
    } else if (stratum == 1) {
        refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
    } else {
        refType = "(Secondary Reference; e.g. via NTP or SNTP)";
    }
    // stratum should be 0..15...
    System.out.println(" Stratum: " + stratum + " " + refType);
    int version = message.getVersion();
    int li = message.getLeapIndicator();
    System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision());

    System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");
    int poll = message.getPoll();
    // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
    System.out.println(
            " poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")");
    double disp = message.getRootDispersionInMillisDouble();
    System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
            + ", rootdispersion(ms): " + numberFormat.format(disp));

    int refId = message.getReferenceId();
    String refAddr = NtpUtils.getHostAddress(refId);
    String refName = null;
    if (refId != 0) {
        if (refAddr.equals("127.127.1.0")) {
            refName = "LOCAL"; // This is the ref address for the Local Clock
        } else if (stratum >= 2) {
            // If reference id has 127.127 prefix then it uses its own reference clock
            // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
            // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
            if (!refAddr.startsWith("127.127")) {
                try {
                    InetAddress addr = InetAddress.getByName(refAddr);
                    String name = addr.getHostName();
                    if (name != null && !name.equals(refAddr)) {
                        refName = name;
                    }
                } catch (UnknownHostException e) {
                    // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2)
                    // ref not valid host maybe it's a reference clock name?
                    // otherwise just show the ref IP address.
                    refName = NtpUtils.getReferenceClock(message);
                }
            }
        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
            refName = NtpUtils.getReferenceClock(message);
            // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
        }
        // otherwise give up on naming the beast...
    }
    if (refName != null && refName.length() > 1) {
        refAddr += " (" + refName + ")";
    }
    System.out.println(" Reference Identifier:\t" + refAddr);

    TimeStamp refNtpTime = message.getReferenceTimeStamp();
    System.out.println(" Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();
    System.out.println(" Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString());

    long destTime = info.getReturnTime();
    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
    System.out.println(" Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
    System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString());

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
    System.out.println(" Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString());

    info.computeDetails(); // compute offset/delay if not already done
    Long offsetValue = info.getOffset();
    Long delayValue = info.getDelay();
    String delay = (delayValue == null) ? "N/A" : delayValue.toString();
    String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

    System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset in ms
    Promedio = Promedio + offsetValue;
    Cant = Cant + 1;
}

From source file:ntpclock.kamalan.com.utility.NTPClient.java

/**
 * Process <code>TimeInfo</code> object and print its details.
 * @param info <code>TimeInfo</code> object.
 *//*  w w w.j  av  a 2  s  .c  om*/
public static Date processResponse(TimeInfo info) {

    NtpV3Packet message = info.getMessage();
    int stratum = message.getStratum();
    String refType;
    if (stratum <= 0) {
        refType = "(Unspecified or Unavailable)";
    } else if (stratum == 1) {
        refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
    } else {
        refType = "(Secondary Reference; e.g. via NTP or SNTP)";
    }
    // stratum should be 0..15...
    System.out.println(" Stratum: " + stratum + " " + refType);
    int version = message.getVersion();
    int li = message.getLeapIndicator();
    System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision());

    System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");
    int poll = message.getPoll();
    // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
    System.out.println(
            " poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")");
    double disp = message.getRootDispersionInMillisDouble();
    System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
            + ", rootdispersion(ms): " + numberFormat.format(disp));

    int refId = message.getReferenceId();
    String refAddr = NtpUtils.getHostAddress(refId);
    String refName = null;
    if (refId != 0) {
        if (refAddr.equals("127.127.1.0")) {
            refName = "LOCAL"; // This is the ref address for the Local Clock
        } else if (stratum >= 2) {
            // If reference id has 127.127 prefix then it uses its own reference clock
            // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
            // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
            if (!refAddr.startsWith("127.127")) {
                try {
                    InetAddress addr = InetAddress.getByName(refAddr);
                    String name = addr.getHostName();
                    if (name != null && !name.equals(refAddr)) {
                        refName = name;
                    }
                } catch (UnknownHostException e) {
                    // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2)
                    // ref not valid host maybe it's a reference clock name?
                    // otherwise just show the ref IP address.
                    refName = NtpUtils.getReferenceClock(message);
                }
            }
        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
            refName = NtpUtils.getReferenceClock(message);
            // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
        }
        // otherwise give up on naming the beast...
    }
    if (refName != null && refName.length() > 1) {
        refAddr += " (" + refName + ")";
    }
    System.out.println(" Reference Identifier:\t" + refAddr);

    TimeStamp refNtpTime = message.getReferenceTimeStamp();
    System.out.println(" Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();
    System.out.println(" Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString());

    long destTime = info.getReturnTime();
    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
    System.out.println(" Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
    System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString());

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
    System.out.println(" Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString());

    info.computeDetails(); // compute offset/delay if not already done
    Long offsetValue = info.getOffset();
    Long delayValue = info.getDelay();
    String delay = (delayValue == null) ? "N/A" : delayValue.toString();
    String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

    System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset in ms

    // convert date string to java util.date format
    // sample: Wed, Jul 16 2014 05:00:00.070
    Date date = null;
    try {
        //            Log.e("NTPClient", destNtpTime.toDateString());
        date = new SimpleDateFormat("EEE, MMM dd yyyy hh:mm:ss.SSS").parse(destNtpTime.toDateString());
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return date;
}

From source file:org.apache.directory.server.ntp.NtpITest.java

/**
 * Tests to make sure NTP works when enabled in the server.
 *
 * @throws Exception if there are errors
 *//*from w  ww.j  ava2s  .  c om*/
@Test
@Ignore
// Fails with a timeout !!!
public void testNtp() throws Exception {
    InetAddress host = InetAddress.getByName(null);

    NTPUDPClient ntp = new NTPUDPClient();
    ntp.setDefaultTimeout(500000);

    long currentTime = System.currentTimeMillis();
    TimeInfo timeInfo = ntp.getTime(host, port);
    long returnTime = timeInfo.getReturnTime();
    assertTrue(Math.abs(currentTime - returnTime) < 1000);

    timeInfo.computeDetails();

    String offsetMsg = "Expected offset in range (-1000, 1000), but was " + timeInfo.getOffset();
    assertTrue(offsetMsg, -1000 < timeInfo.getOffset() && timeInfo.getOffset() < 1000);
    String delayMsg = "Expected delay in range [0, 1000), but was " + timeInfo.getOffset();
    assertTrue(delayMsg, 0 <= timeInfo.getDelay() && timeInfo.getDelay() < 1000);
}

From source file:org.eclipse.smarthome.binding.ntp.handler.NtpHandler.java

/**
 * Queries the given timeserver <code>hostname</code> and returns the time
 * in milliseconds.//from   w w w. jav a2  s .  c  o  m
 *
 * @param hostname
 *            the timeserver to query
 * @return the time in milliseconds or the current time of the system if an
 *         error occurs.
 */
public long getTime(String hostname) {

    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        timeClient.setDefaultTimeout(NTP_TIMEOUT);
        InetAddress inetAddress = InetAddress.getByName(hostname);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);

        logger.debug("{} Got time update from: {} : {}", getThing().getUID().toString(), hostname,
                SDF.format(new Date(timeInfo.getReturnTime())));
        updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
        return timeInfo.getReturnTime();
    } catch (UnknownHostException uhe) {
        String msg = getThing().getUID().toString() + " the given hostname '" + hostname
                + "' of the timeserver is unknown -> returning current sytem time instead.";
        logger.warn(msg);
        updateStatus(ThingStatus.ONLINE, ThingStatusDetail.COMMUNICATION_ERROR, msg);
    } catch (IOException ioe) {
        String msg = getThing().getUID().toString() + " couldn't establish network connection [host '"
                + hostname + "'] -> returning current sytem time instead.";
        logger.warn(msg);
        updateStatus(ThingStatus.ONLINE, ThingStatusDetail.COMMUNICATION_ERROR, msg);
    }

    return System.currentTimeMillis();
}

From source file:org.jc.zk.util.Utils.java

/**
 * Method in charge of retrieving time from NTP servers.
 * @param servers String array containing ip addresses of NTP servers.
 * @return a long representing current time in milliseconds.
 * @throws Exception If anything goes wrong, an exception is thrown.
 *///from   w  w  w  .  jav  a  2  s .c  om
public static long getNetworkTime(String[] servers) throws Exception {
    for (int i = 0; i < servers.length; ++i) {
        NTPUDPClient timeClient = new NTPUDPClient();
        try {
            InetAddress inetAddress = InetAddress.getByName(servers[i]);
            TimeInfo timeInfo = timeClient.getTime(inetAddress);
            timeInfo.computeDetails();
            long retVal = timeInfo.getReturnTime() + timeInfo.getOffset();

            return retVal;
        } catch (UnknownHostException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    throw new Exception("Impossible to retrieve network time tried these servers: " + Arrays.toString(servers));
}

From source file:org.ntpsync.util.NtpSyncUtils.java

/**
 * Process <code>TimeInfo</code> object and print its details.
 * //from w  ww  .ja va 2s  .  c  om
 * @param info
 *            <code>TimeInfo</code> object.
 */
public static String processResponse(TimeInfo info, Context context) {
    String output = "";

    NtpV3Packet message = info.getMessage();
    int stratum = message.getStratum();
    String refType;
    if (stratum <= 0) {
        refType = context.getString(R.string.detailed_query_unspecified);
    } else if (stratum == 1) {
        refType = context.getString(R.string.detailed_query_primary_reference); // GPS, radio
                                                                                // clock, etc.
    } else {
        refType = context.getString(R.string.detailed_query_secondary_reference);
    }
    // stratum should be 0..15...
    output += "<p><b>" + context.getString(R.string.detailed_query_server) + "</b><br/>"
            + context.getString(R.string.detailed_query_stratum) + " " + stratum + " " + refType;

    int version = message.getVersion();
    int li = message.getLeapIndicator();
    output += "<br/>" + context.getString(R.string.detailed_query_leap) + " " + li + "<br/>"
            + context.getString(R.string.detailed_query_version) + " " + version + "<br/>"
            + context.getString(R.string.detailed_query_precision) + " " + message.getPrecision();

    output += "<br/>" + context.getString(R.string.detailed_query_mode) + " " + message.getModeName() + " ("
            + message.getMode() + ")";
    int poll = message.getPoll();
    // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
    output += "<br/>" + context.getString(R.string.detailed_query_poll) + " "
            + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " "
            + context.getString(R.string.detailed_query_seconds) + " (2 ** " + poll + ")";
    double disp = message.getRootDispersionInMillisDouble();
    output += "<br/>" + context.getString(R.string.detailed_query_rootdelay) + " "
            + numberFormat.format(message.getRootDelayInMillisDouble()) + "<br/>"
            + context.getString(R.string.detailed_query_rootdispersion) + " " + numberFormat.format(disp);

    int refId = message.getReferenceId();
    String refAddr = NtpUtils.getHostAddress(refId);
    String refName = null;
    if (refId != 0) {
        if (refAddr.equals("127.127.1.0")) {
            refName = "LOCAL"; // This is the ref address for the Local Clock
        } else if (stratum >= 2) {
            // If reference id has 127.127 prefix then it uses its own reference clock
            // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
            // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
            if (!refAddr.startsWith("127.127")) {
                try {
                    InetAddress addr = InetAddress.getByName(refAddr);
                    String name = addr.getHostName();
                    if (name != null && !name.equals(refAddr)) {
                        refName = name;
                    }
                } catch (UnknownHostException e) {
                    // some stratum-2 servers sync to ref clock device but fudge stratum level
                    // higher... (e.g. 2)
                    // ref not valid host maybe it's a reference clock name?
                    // otherwise just show the ref IP address.
                    refName = NtpUtils.getReferenceClock(message);
                }
            }
        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
            refName = NtpUtils.getReferenceClock(message);
            // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
        }
        // otherwise give up on naming the beast...
    }
    if (refName != null && refName.length() > 1) {
        refAddr += " (" + refName + ")";
    }
    output += "<p><b>" + context.getString(R.string.detailed_query_reference_identifier) + "</b><br/>" + refAddr
            + "</p>";

    TimeStamp refNtpTime = message.getReferenceTimeStamp();
    output += "<p><b>" + context.getString(R.string.detailed_query_reference_timestamp) + "</b><br/>"
            + refNtpTime.toDateString() + "</p>";

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();
    output += "<p><b>" + context.getString(R.string.detailed_query_originate_timestamp) + "</b><br/>"
            + origNtpTime.toDateString() + "</p>";

    long destTime = info.getReturnTime();
    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
    output += "<p><b>" + context.getString(R.string.detailed_query_receive_timestamp) + "</b><br/>"
            + rcvNtpTime.toDateString() + "</p>";

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
    output += "<p><b>" + context.getString(R.string.detailed_query_transmit_timestamp) + "</b><br/>"
            + xmitNtpTime.toDateString() + "</p>";

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
    output += "<p><b>" + context.getString(R.string.detailed_query_destination_timestamp) + "</b><br/>"
            + destNtpTime.toDateString() + "</p>";

    info.computeDetails(); // compute offset/delay if not already done
    Long offsetValue = info.getOffset();
    Long delayValue = info.getDelay();
    String delay = (delayValue == null) ? "N/A" : delayValue.toString();
    String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

    // offset in ms
    output += "<p><b>" + context.getString(R.string.detailed_query_computed_offset) + "</b><br/>"
            + context.getString(R.string.detailed_query_roundtrip_delay) + " " + delay + "<br/>"
            + context.getString(R.string.detailed_query_clock_offset) + " " + offset + "</p>";

    return output;
}

From source file:org.openhab.binding.ntp.internal.handler.NtpHandler.java

/**
 * Queries the given timeserver <code>hostname</code> and returns the time
 * in milliseconds.//from   w w  w .j a  v a  2  s. c o  m
 *
 * @param hostname the timeserver to query
 * @return the time in milliseconds or the current time of the system if an
 *         error occurs.
 */
public long getTime(String hostname) {
    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        timeClient.setDefaultTimeout(NTP_TIMEOUT);
        InetAddress inetAddress = InetAddress.getByName(hostname);
        TimeInfo timeInfo = timeClient.getTime(inetAddress, port.intValue());
        timeInfo.computeDetails();

        long serverMillis = timeInfo.getReturnTime() + timeInfo.getOffset();
        logger.debug("{} Got time update from host '{}': {}.", getThing().getUID(), hostname,
                SDF.format(new Date(serverMillis)));
        updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
        return serverMillis;
    } catch (UnknownHostException uhe) {
        logger.debug(
                "{} The given hostname '{}' of the timeserver is unknown -> returning current sytem time instead. ({})",
                getThing().getUID(), hostname, uhe.getMessage());
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                "@text/offline.comm-error-unknown-host [\"" + (hostname == null ? "null" : hostname) + "\"]");
    } catch (IOException ioe) {
        logger.debug(
                "{} Couldn't establish network connection to host '{}' -> returning current sytem time instead. ({})",
                getThing().getUID(), hostname, ioe.getMessage());
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                "@text/offline.comm-error-connection [\"" + (hostname == null ? "null" : hostname) + "\"]");
    }

    return System.currentTimeMillis();
}

From source file:org.openhab.binding.ntp.internal.NtpBinding.java

/**
 * Queries the given timeserver <code>hostname</code> and returns the time
 * in milliseconds./*from  w w  w  .ja  v a  2  s .  c  o  m*/
 * 
 * @param hostname the timeserver to query
 * @return the time in milliseconds or the current time of the system if an
 * error occurs.
 */
protected static long getTime(String hostname) {

    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        timeClient.setDefaultTimeout(NTP_TIMEOUT);
        InetAddress inetAddress = InetAddress.getByName(hostname);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);

        return timeInfo.getReturnTime();
    } catch (UnknownHostException uhe) {
        logger.warn(
                "the given hostname '{}' of the timeserver is unknown -> returning current sytem time instead",
                hostname);
    } catch (IOException ioe) {
        logger.warn("couldn't establish network connection [host '{}'] -> returning current sytem time instead",
                hostname);
    }

    return System.currentTimeMillis();
}

From source file:org.sipfoundry.preflight.NTP.java

/**
 * Process <code>TimeInfo</code> object and return details.
 *
 * @param info//from   w  w  w . j a v a  2 s.com
 *            <code>TimeInfo</code> object.
 */
private String processResponse(TimeInfo info) {
    String response;
    NtpV3Packet message = info.getMessage();
    int stratum = message.getStratum();
    String refType;
    if (stratum <= 0) {
        refType = "(Unspecified or Unavailable)";
    } else if (stratum == 1) {
        refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock,
                                                    // etc.
    } else {
        refType = "(Secondary Reference; e.g. via NTP or SNTP)";
    }
    // stratum should be 0..15...
    response = new String("  Stratum: " + stratum + " " + refType + "\n");
    int version = message.getVersion();
    int li = message.getLeapIndicator();
    response += new String(
            "  leap=" + li + ", version=" + version + ", precision=" + message.getPrecision() + "\n");

    response += new String("  mode: " + message.getModeName() + " (" + message.getMode() + ")\n");
    int poll = message.getPoll();
    // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
    response += new String(
            "  poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")\n");
    double disp = message.getRootDispersionInMillisDouble();
    response += new String("  rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
            + ", rootdispersion(ms): " + numberFormat.format(disp) + "\n");

    int refId = message.getReferenceId();
    String refAddr = NtpUtils.getHostAddress(refId);
    String refName = null;
    if (refId != 0) {
        if (refAddr.equals("127.127.1.0")) {
            refName = "LOCAL"; // This is the ref address for the Local
                               // Clock
        } else if (stratum >= 2) {
            // If reference id has 127.127 prefix then it uses its own
            // reference clock
            // defined in the form 127.127.clock-type.unit-num (e.g.
            // 127.127.8.0 mode 5
            // for GENERIC DCF77 AM; see refclock.htm from the NTP software
            // distribution.
            if (!refAddr.startsWith("127.127")) {
                try {
                    InetAddress addr = InetAddress.getByName(refAddr);
                    String name = addr.getHostName();
                    if (name != null && !name.equals(refAddr)) {
                        refName = name;
                    }
                } catch (UnknownHostException e) {
                    // some stratum-2 servers sync to ref clock device but
                    // fudge stratum level higher... (e.g. 2)
                    // ref not valid host maybe it's a reference clock name?
                    // otherwise just show the ref IP address.
                    refName = NtpUtils.getReferenceClock(message);
                }
            }
        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
            refName = NtpUtils.getReferenceClock(message);
            // refname usually have at least 3 characters (e.g. GPS, WWV,
            // LCL, etc.)
        }
        // otherwise give up on naming the beast...
    }
    if (refName != null && refName.length() > 1) {
        refAddr += " (" + refName + ")";
    }
    response += new String("  Reference Identifier:  " + refAddr + "\n");

    TimeStamp refNtpTime = message.getReferenceTimeStamp();
    response += new String("  Reference Timestamp:   " + refNtpTime + "  " + refNtpTime.toDateString() + "\n");

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();
    response += new String(
            "  Originate Timestamp:   " + origNtpTime + "  " + origNtpTime.toDateString() + "\n");

    long destTime = info.getReturnTime();
    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
    response += new String("  Receive Timestamp:     " + rcvNtpTime + "  " + rcvNtpTime.toDateString() + "\n");

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
    response += new String(
            "  Transmit Timestamp:    " + xmitNtpTime + "  " + xmitNtpTime.toDateString() + "\n");

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
    response += new String(
            "  Destination Timestamp: " + destNtpTime + "  " + destNtpTime.toDateString() + "\n");

    info.computeDetails(); // compute offset/delay if not already done
    Long offsetValue = info.getOffset();
    Long delayValue = info.getDelay();
    String delay = (delayValue == null) ? "N/A" : delayValue.toString();
    String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

    response += new String("  Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset + "\n"); // offset
                                                                                                      // in
                                                                                                      // ms

    return response;
}