Example usage for org.apache.commons.net.ntp NTPUDPClient getTime

List of usage examples for org.apache.commons.net.ntp NTPUDPClient getTime

Introduction

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

Prototype

public TimeInfo getTime(InetAddress host) throws IOException 

Source Link

Document

Retrieves the time information from the specified server on the default NTP port and returns it.

Usage

From source file:org.apache.common.net.examples.ntp.NTPClient.java

public static final void main(String[] args) {
    if (args.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);//www  .  j a  v a 2  s. c om
    }

    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
        client.open();
        for (int i = 0; i < args.length; i++) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(args[i]);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

    client.close();
}

From source file:org.apache.rya.accumulo.mr.merge.util.TimeUtils.java

/**
 * Queries the specified NTP Server for the time.
 * Do not query time server more than once every 4 seconds.
 * @param timeServerHost the time server host name.
 * @return the NTP server {@link Date} or {@code null}.
 * @throws IOException/* ww w.j ava 2 s.com*/
 */
public static Date getNtpServerDate(final String timeServerHost) throws IOException {
    try {
        TimeInfo timeInfo = null;
        final NTPUDPClient timeClient = new NTPUDPClient();
        timeClient.setDefaultTimeout(NTP_SERVER_TIMEOUT_MS);
        final InetAddress inetAddress = InetAddress.getByName(timeServerHost);
        if (inetAddress != null) {
            timeInfo = timeClient.getTime(inetAddress);
            if (timeInfo != null) {
                // TODO: which time to use?
                final long serverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
                //long serverTime = timeInfo.getReturnTime();
                final Date ntpDate = new Date(serverTime);
                return ntpDate;
            }
        }
    } catch (final IOException e) {
        throw new IOException("Unable to get NTP server time.", e);
    }
    return null;
}

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 www.  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);

        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   ww  w . j a  v  a2s.  c  o m
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

/**
 * Queries NTP server to get details/*www.j a  v  a 2 s  .  c  om*/
 * 
 * @param ntpServerHostname
 */
public static TimeInfo detailedQuery(String ntpServerHostname) throws IOException, SocketException {
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);

    TimeInfo info = null;
    try {
        client.open();

        InetAddress hostAddr = InetAddress.getByName(ntpServerHostname);
        Log.d(Constants.TAG, "> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
        info = client.getTime(hostAddr);
    } finally {
        client.close();
    }

    return info;
}

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

/**
 * Queries NTP server using UDP to get offset
 * //  w  ww  .j  a v a2  s.c om
 * @param ntpServerHostname
 * @return offset
 * @throws IOException
 *             , SocketException
 */
public static long query(String ntpServerHostname) throws IOException, SocketException {
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);

    TimeInfo info = null;
    try {
        client.open();

        InetAddress hostAddr = InetAddress.getByName(ntpServerHostname);
        Log.d(Constants.TAG,
                "Trying to get time from " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());

        info = client.getTime(hostAddr);
    } finally {
        client.close();
    }

    // compute offset/delay if not already done
    info.computeDetails();

    return info.getOffset();
}

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

/**
 * Queries the given timeserver <code>hostname</code> and returns the time
 * in milliseconds.// w  w w .j  a va2 s .c  om
 * 
 * @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

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;//from ww w . j  a va 2  s. c o  m

    if (networkResources.ntpServers == null) {
        journalService.println("No NTP servers provided, skipping test.");
        results = NTP_SERVERS_MISSING;
    } else {
        journalService.println("Starting NTP servers test.");
        NTPUDPClient client = new NTPUDPClient();
        client.setDefaultTimeout(timeout * 1000);
        try {
            client.open(bindPort, bindAddress);

            for (InetAddress ntpServer : networkResources.ntpServers) {
                journalService.println("NTP test for server: " + ntpServer.getCanonicalHostName());
                try {
                    TimeInfo info = client.getTime(ntpServer);
                    journalService.println(new String(processResponse(info)));
                } catch (IOException e) {
                    client.close();
                    if (e.getClass() == java.net.SocketTimeoutException.class) {
                        journalService.println("  NTP request timed out.");
                        results = NTP_SERVER_FAILURE;
                    } else {
                        journalService.println("  NTP request error: " + e.getMessage());
                        results = NTP_TEST_FAILURE;
                    }
                }
            }
        } catch (SocketException e) {
            journalService.println("Unable to create NTP client: " + e.getMessage());
            results = NTP_TEST_FAILURE;
        }
    }

    journalService.println("");
    return results;
}

From source file:org.smallmind.nutsnbolts.ntp.NTPTime.java

public final long getOffset(int timeoutMillis) throws IOException {

    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(timeoutMillis);

    client.open();/*w  w  w  .j  a v a2 s.  c  om*/

    try {

        TimeInfo timeInfo;

        timeInfo = client.getTime(InetAddress.getByName(hostNames[RANDOM.nextInt(hostNames.length)]));
        timeInfo.computeDetails();

        return timeInfo.getOffset();
    } finally {
        client.close();
    }
}

From source file:org.tranche.time.TimeUtil.java

/**
 * //  w  ww.j  a va  2s  .  c o m
 * @param address
 * @return
 * @throws java.net.UnknownHostException
 * @throws java.io.IOException
 */
public static final long getOffset(String address) throws UnknownHostException, IOException {
    NTPUDPClient ntpClient = new NTPUDPClient();
    try {
        InetAddress inet = InetAddress.getByName(address);
        DebugUtil.debugOut(TimeUtil.class, "Updating offset from " + inet.getHostAddress() + ".");
        int timeout = ConfigureTranche.getInt(ConfigureTranche.CATEGORY_NETWORK_TIME_SERVERS,
                ConfigureTranche.PROP_TIME_UPDATE_TIMEOUT);
        if (timeout > 0) {
            ntpClient.setDefaultTimeout(timeout);
        }
        TimeInfo time = ntpClient.getTime(inet);
        time.computeDetails();
        DebugUtil.debugOut(TimeUtil.class, "Returned Offset: " + time.getOffset());
        DebugUtil.debugOut(TimeUtil.class, "Network Delay: " + time.getDelay());
        return time.getOffset();
    } finally {
        try {
            ntpClient.close();
        } catch (Exception e) {
            DebugUtil.debugErr(TimeUtil.class, e);
        }
    }
}