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

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

Introduction

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

Prototype

public void setDefaultTimeout(int timeout) 

Source Link

Document

Set the default timeout in milliseconds to use when opening a socket.

Usage

From source file:org.eclipse.kura.windows.clock.JavaNtpClockSyncProvider.java

@Override
protected boolean syncClock() throws KuraException {
    boolean ret = false;
    // connect and get the delta
    NTPUDPClient ntpClient = new NTPUDPClient();
    ntpClient.setDefaultTimeout(this.m_ntpTimeout);
    try {/*w  w  w  . j a v  a2 s .  c o m*/
        ntpClient.open();
        try {
            InetAddress ntpHostAddr = InetAddress.getByName(this.m_ntpHost);
            TimeInfo info = ntpClient.getTime(ntpHostAddr, this.m_ntpPort);
            this.m_lastSync = new Date();
            info.computeDetails();

            this.m_listener.onClockUpdate(info.getOffset());
            ret = true;
        } catch (IOException e) {
            s_logger.warn(
                    "Error while synchronizing System Clock with NTP host {}. Please virify network connectivity ...",
                    this.m_ntpHost);
        }
    } catch (Exception e) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    }
    return ret;
}

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

/**
 * Queries the given timeserver <code>hostname</code> and returns the time
 * in milliseconds./* www  .  j  a  v a 2  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.
 */
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.ntpsync.util.NtpSyncUtils.java

/**
 * Queries NTP server to get details/*from   www .j a  va  2  s. c o m*/
 * 
 * @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 w  w . j av 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.handler.NtpHandler.java

/**
 * Queries the given timeserver <code>hostname</code> and returns the time
 * in milliseconds.//from w  w  w  . ja v  a  2s  .c om
 *
 * @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   ww  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.
 */
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;//w  w  w.j  a v a  2s  .  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();/*from  ww  w.  j ava 2s .  c  o  m*/

    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 w  w.  j a  va  2  s  .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);
        }
    }
}

From source file:org.urbancortex.presenter.NTPClient.java

public static TimeInfo main(String[] args) {
    System.out.println(args);/*from  ww  w .j a  va2s.  com*/

    if (args.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);
    }

    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(5000);
    try {
        client.open();
        for (String arg : args) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(arg);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info);

                return info;

            } catch (IOException ioe) {
                ioe.printStackTrace();
                socketTimeout = true;
                //                    csv_logger.stopNTPTask();
                System.out.println("couldn't establish a connection" + ioe);
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
        socketTimeout = true;
        //            csv_logger.stopNTPTask();
        System.out.println("couldn't establish a connection" + e);
    }

    client.close();
    return null;
}