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

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

Introduction

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

Prototype

public void computeDetails() 

Source Link

Document

Compute and validate details of the NTP message packet.

Usage

From source file:experts.net.ip6.ULUA.java

/**
 * Obtain NTP time stamp value//from w ww.j  a v  a2  s.c o  m
 *
 * @param address
 *            NTP server address
 * @return the current time of day in 64-bit NTP format
 * @throws SocketException
 *             If the socket could not be opened which it might be not available any ports.
 * @throws UnknownHostException
 *             If the host could not be found.
 * @throws IOException
 */
public static long obtainNTPTime(String address) throws SocketException, UnknownHostException, IOException {
    NTPUDPClient client = new NTPUDPClient();
    client.setVersion(NtpV3Packet.VERSION_4);

    // throws SocketException
    client.open();
    // throws UnknownHostException from InetAddress.getByName and IOException from client.getTime
    TimeInfo time = client.getTime(InetAddress.getByName(address));
    client.close();

    time.computeDetails();

    return time.getMessage().getTransmitTimeStamp().ntpValue();
}

From source file:be.fedict.trust.service.util.ClockDriftUtil.java

public static TimeInfo executeNTP(ClockDriftConfigEntity clockDriftConfig, final NetworkConfig networkConfig)
        throws IOException {

    LOG.debug("clock drift detection: " + clockDriftConfig.toString());

    final InetAddress ntpServerAddress = InetAddress.getByName(clockDriftConfig.getServer());

    TimeInfo timeInfo;
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(clockDriftConfig.getTimeout());
    client.open();/*  w  ww  . j  a  v a2 s  .c o  m*/
    LOG.debug("NTP server: " + ntpServerAddress);
    timeInfo = client.getTime(ntpServerAddress);
    client.close();
    timeInfo.computeDetails();
    return timeInfo;
}

From source file:de.tud.kitchen.android.NTPTimeReceiver.java

@Override
protected Void doInBackground(InetAddress... params) {
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(10000);/*from w w  w .  ja v  a 2s.c  o  m*/
    try {
        client.open();
    } catch (final SocketException se) {
        se.printStackTrace();
        return null;
    }
    while (!this.isCancelled()) {
        try {
            TimeInfo info = client.getTime(params[0]);
            info.computeDetails();
            Long offsetValue = info.getOffset();
            int receiverTimeDelta = (offsetValue == null) ? 0 : offsetValue.intValue();
            publishProgress(receiverTimeDelta);
        } catch (final IOException ioe) {
            ioe.printStackTrace();
            continue;
        }

        try {
            Thread.sleep(1000 * 60);
        } catch (InterruptedException e) {
            continue;
        }
    }
    client.close();
    return null;
}

From source file:interactivespaces.time.NtpTimeProvider.java

private long computeOffset() throws IOException {
    log.info("Updating time offset from NTP server: " + host.getHostName());
    try {/*from  w  ww . jav  a  2  s  . c om*/
        TimeInfo time = ntpClient.getTime(host);
        time.computeDetails();

        return time.getOffset();
    } catch (IOException e) {
        log.error("Failed to read time from NTP server: " + host.getHostName(), e);
        throw e;
    }
}

From source file:com.blockwithme.time.internal.NTPClockSynchronizer.java

@Override
public long getLocalToUTCTimeOffset() throws Exception {
    final NTPUDPClient client = new NTPUDPClient();
    //      final Calendar cal = Calendar.getInstance(DEFAULT_LOCAL);
    // We want to timeout if a response takes longer than 3 seconds
    client.setDefaultTimeout(TIMEOUT);
    long offsetSum = 0L;
    int offsetCount = 0;
    long bestDelay = Long.MAX_VALUE;
    long bestOffset = Long.MAX_VALUE;
    Throwable lastException = null;
    try {/*w w w  .ja  v  a2s .co  m*/
        client.open();
        for (int i = 0; i < ntpPool.length; i++) {
            try {
                final InetAddress hostAddr = InetAddress.getByName(ntpPool[i]);
                final TimeInfo info = client.getTime(hostAddr);
                info.computeDetails();
                final Long offsetValue = info.getOffset();
                final Long delayValue = info.getDelay();
                if ((delayValue != null) && (offsetValue != null)) {
                    //                      cal.setTimeInMillis(offsetValue
                    //                              + System.currentTimeMillis());
                    //                      final long local2UTC = -(cal.get(Calendar.ZONE_OFFSET) + cal
                    //                              .get(Calendar.DST_OFFSET));
                    if (delayValue <= 100L) {
                        offsetSum += offsetValue;// + local2UTC;
                        offsetCount++;
                    }
                    if (delayValue < bestDelay) {
                        bestDelay = delayValue;
                        bestOffset = offsetValue;// + local2UTC;
                    }
                }
            } catch (final Throwable t) {
                LOG.error("Error reading tiem through NTP", t);
                lastException = t;
            }
        }
    } catch (final Throwable t) {
        LOG.error("Error reading tiem through NTP", t);
        lastException = t;
        // NTPUDPClient can't even open at all!?!
    } finally {
        client.close();
    }
    if (offsetCount > 0) {
        return offsetSum / offsetCount;
    }
    // OK, not good result. Any result at all?
    if (bestDelay != Long.MAX_VALUE) {
        return bestOffset;
    }
    // FAIL!
    throw new Exception("Failed to get NTP time", lastException);
}

From source file:com.jaspersoft.bigquery.connection.BigQueryConnection.java

public String test() throws JRException {
    try {//from   w  w  w.ja v a2  s . c  o m
        if (transport != null && jsonFactory != null && bigquery != null) {
            List datasetRequest = bigquery.datasets().list("publicdata");
            DatasetList datasetList = datasetRequest.execute();
            StringBuilder builder = new StringBuilder();
            builder.append("Available datasets: ");
            if (datasetList != null) {
                java.util.List<Datasets> datasets = datasetList.getDatasets();
                for (Datasets dataset : datasets) {
                    builder.append(dataset.getId());
                    builder.append(",");
                }
            }
            if (builder.charAt(builder.length() - 1) == ',') {
                builder.setCharAt(builder.length() - 1, '.');
            }
            return builder.toString();
        }
    } catch (Throwable e) {
        if (e.getMessage() != null && e.getMessage().toLowerCase().contains("unauthorized")) {
            logger.error(e);
            NTPUDPClient ntpClient = new NTPUDPClient();
            TimeInfo timeInfo = null;
            try {
                timeInfo = ntpClient.getTime(InetAddress.getByName(NTP_SERVER));
            } catch (Throwable e1) {
                e1.printStackTrace();
            } finally {
                ntpClient.close();
            }
            StringBuilder timeMessage = new StringBuilder();
            timeMessage.append("Ensure your system clock is synchronized with an NTP server.\n");
            if (timeInfo != null) {
                timeInfo.computeDetails();
                long offset = (timeInfo.getOffset() != null) ? timeInfo.getOffset() : 0l;
                SimpleDateFormat df = new SimpleDateFormat("EEE yyyy MMM d HH:mm:ss SSS z");
                String localDateString = df.format(new java.util.Date(System.currentTimeMillis()));
                String ntpDateString = df.format(new java.util.Date(System.currentTimeMillis() + offset));
                timeMessage.append("Current offset against \"");
                timeMessage.append(NTP_SERVER);
                timeMessage.append("\" is: ");
                timeMessage.append(offset);
                timeMessage.append(" milliseconds.\n");
                timeMessage.append("Current time on NTP   server: " + ntpDateString + "\n");
                timeMessage.append("Current time on local server: " + localDateString);
            }
            throw new JRException(
                    "Unauthorized exception. Please review your serviceAccountId and privateKeyFilePath.\n"
                            + timeMessage.toString());
        }
        throw new JRException(e);
    }
    throw new JRException("Could not connect to BigQuery");
}

From source file:edu.tcu.gaduo.ihe.iti.ct_transaction.service.NTPClient.java

public Date processResponse(String host) {

    TimeInfo info = null;
    try {/*from www  . j  ava2 s  .  co m*/
        NTPUDPClient client = new NTPUDPClient();
        client.setDefaultTimeout(10000);
        client.open();
        InetAddress hostAddr = InetAddress.getByName(host);
        info = client.getTime(hostAddr);
        client.close();
    } catch (NullPointerException e) {
        logger.info(e.toString());
        return null;
    } catch (IOException e) {
        logger.info(e.toString());
        e.printStackTrace();
        return null;
    }

    message = info.getMessage();
    stratum = message.getStratum(); // 
    if (stratum <= 0)
        refType = "(??)";
    else if (stratum == 1)
        refType = "(??; e.g., GPS)"; // GPS, radio clock,
    else
        refType = "(??; e.g. via NTP or SNTP)";
    // stratum should be 0..15...
    logger.info(" Stratum: " + stratum + " " + refType);

    this.setRefNtpTime(message.getReferenceTimeStamp());

    // Originate Time is time request sent by client (t1)
    this.setOrigNtpTime(message.getOriginateTimeStamp());
    // Receive Time is time request received by server (t2)
    this.setRcvNtpTime(message.getReceiveTimeStamp());
    // Transmit time is time reply sent by server (t3)
    this.setXmitNtpTime(message.getTransmitTimeStamp());
    // Destination time is time reply received by client (t4)
    long destTime = info.getReturnTime();
    this.setDestNtpTime(TimeStamp.getNtpTime(destTime));

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

    Date Date = message.getReferenceTimeStamp().getDate();
    return Date;
}

From source file:amplify.NTPClient.java

/**
 * Process <code>TimeInfo</code> object and print its details.
 *
 * @param info <code>TimeInfo</code> object.
 *///  w ww .  java2 s. c o 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 + ")";

    TimeStamp refNtpTime = message.getReferenceTimeStamp();

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();

    long destTime = info.getReturnTime();
    long localDestTime = System.currentTimeMillis();

    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);

    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();
    clockOffset = offsetValue != null ? offsetValue.longValue() : 0L;

    System.out.println(" Reference Identifier:\t" + refAddr);
    System.out.println(" Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());
    System.out.println(" Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString());
    System.out.println(" Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());
    System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString());
    System.out.println(" Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString());
    System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset in ms
}

From source file:com.amplify.gcm.hack.NTPClient.java

/**
 * Process <code>TimeInfo</code> object and print its details.
 *
 * @param info <code>TimeInfo</code> object.
 *//*from  w ww  . j  a v  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 + ")";

    TimeStamp refNtpTime = message.getReferenceTimeStamp();

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();

    long destTime = info.getReturnTime();
    long localDestTime = System.currentTimeMillis();

    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);

    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();
    clockOffset = offsetValue != null ? offsetValue.longValue() : 0L;

    Log.i(TAG, " Reference Identifier:\t" + refAddr);
    Log.i(TAG, " Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());
    Log.i(TAG, " Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString());
    Log.i(TAG, " Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());
    Log.i(TAG, " Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString());
    Log.i(TAG, " Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString());
    Log.i(TAG, " Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset);
}

From source file:NTP_Example.java

/**
 * Process <code>TimeInfo</code> object and print its details.
 * @param info <code>TimeInfo</code> object.
 *///w  ww. ja v a  2s. c  om
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
}