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, int port) throws IOException 

Source Link

Document

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

Usage

From source file:com.clustercontrol.port.protocol.ReachAddressNTP.java

/**
 * NTP????????/*from  w  ww.ja va 2 s.c o m*/
 * 
 * @param addressText
 * @return NTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the NTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        NTPUDPClient client = new NTPUDPClient();
        TimeInfo time = null;

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                time = client.getTime(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                if (time != null) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }
                    result = new Date(time.getReturnTime()).toString();
                    retry = false;
                    isReachable = true;
                } else {
                    result = "failed to get time ";
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isOpen()) {
                    client.close();
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(NTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

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  www .  j  a v a2s.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.blue.star.plugins.check_local_time.java

public boolean execute_check() {

    /* Declare variables */
    NTPUDPClient ntpClient = new NTPUDPClient();
    TimeInfo time;//ww w  . j  av  a  2s.c  o m
    InetAddress server;
    offsets = new long[checkCount];

    /* Check for verbosity */
    if (super.verbose > 0)
        verbose = true;

    /* Configure client to meet our requirements */
    ntpClient.setDefaultTimeout(timeout);
    ntpClient.setVersion(ntpVersion);

    try {
        if (verbose) {
            System.out.println("Using NTP Server: " + hostname);
            System.out.println("Using NTP Port: " + port);
            System.out.println("Using NTP Version: " + ntpVersion);
        }

        server = InetAddress.getByName(hostname);
        ntpClient.open();

        if (verbose)
            System.out.println("Beginning total of " + checkCount + " checks.");

        for (int i = 0; i < checkCount; i++) {
            if (verbose)
                System.out.println("Taking time reading number " + i);

            time = ntpClient.getTime(server, port);

            if (time == null) {
                /* State unknown if we can't connect to NTP server, our local time could be fine */
                check_state = common_h.STATE_UNKNOWN;
                check_message = "State Unknown - Unable to connect to NTP Server!";
                return true;
            }
            time.computeDetails();

            offsets[i] = time.getOffset() - time.getDelay();

            /* Small sleep so that we are at least getting some variety in our readings */
            Thread.sleep(200);
        }

        if (verbose)
            System.out.println("Calculating & storing time averages.");
        /* Calculate and store average offset */
        long total = 0;

        for (int i = 0; i < offsets.length; i++)
            total += offsets[i];

        average = total / offsets.length;
    } catch (Exception e) {
        check_state = common_h.STATE_CRITICAL;
        check_message = e.getMessage();
    } finally {
        try {
            ntpClient.close();
        } catch (Exception e) {
        }
    }
    return true;
}

From source file:org.eclipse.kura.linux.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 {/*www  .ja  va 2 s.  c  om*/
        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) {
            ntpClient.close();
            s_logger.warn(
                    "Error while synchronizing System Clock with NTP host {}. Please verify network connectivity ...",
                    this.m_ntpHost);
        }
    } catch (Exception e) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    }
    return ret;
}

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 {//from  w  w w.  j av  a 2s .  com
        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.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 va  2s  . com
 *
 * @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();
}