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:com.chiorichan.util.WebUtils.java

public static Date getNTPDate() {
    String[] hosts = new String[] { "ntp02.oal.ul.pt", "ntp04.oal.ul.pt", "ntp.xs4all.nl" };

    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 5 seconds
    client.setDefaultTimeout(5000);/*from   w w w.  java2s .  co m*/

    for (String host : hosts) {

        try {
            InetAddress hostAddr = InetAddress.getByName(host);
            // System.out.println( "> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress() );
            TimeInfo info = client.getTime(hostAddr);
            Date date = new Date(info.getReturnTime());
            return date;

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    client.close();

    return null;

}

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

@Override
protected Void doInBackground(InetAddress... params) {
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(10000);//from   www  .  j a  v a2 s.  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:edu.tcu.gaduo.ihe.iti.ct_transaction.service.NTPClient.java

public Date processResponse(String host) {

    TimeInfo info = null;//from   w  ww.  j av a 2s .c om
    try {
        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:com.jaspersoft.bigquery.connection.BigQueryConnection.java

public String test() throws JRException {
    try {// ww  w  .  j  av  a  2s  .  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:com.cscao.apps.ntplib.NTPClient.java

private TimeInfo requestTime(String server, int timeout) {
    TimeInfo responseInfo = null;/*from w  ww  .j a  v a2 s . c  o m*/
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(timeout);
    try {
        client.open();
        try {
            InetAddress hostAddr = InetAddress.getByName(server);
            //                System.out.println("> " + hostAddr.getHostName() + "/"
            //                        + hostAddr.getHostAddress());
            details += "NTP server: " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress();

            responseInfo = client.getTime(hostAddr);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } catch (SocketException e) {
        e.printStackTrace();
    }

    client.close();
    return responseInfo;

}

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 {// ww w  .j a  v  a  2  s  . 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.studio.statistics.UsageManager.java

/**
 * Contact an NTP server to get the current time
 * //w  w w. j a v  a2 s.  c  o  m
 * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.
 * @throws Exception
 *           throw an exception if the time can not be fetched
 */
protected long getCurrentTime() throws Exception {
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
    Date time = new Date(returnTime);
    return time.getTime();
}

From source file:ntp.NTPClient.java

public static void main(String[] args) {
    Properties defaultProps = System.getProperties(); //obtiene las "properties" del sistema
    defaultProps.put("java.net.preferIPv6Addresses", "true");//mapea el valor true en la variable java.net.preferIPv6Addresses
    if (args.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);//from ww  w  .  j a  v a2 s .c o m
    }

    Promedio = 0;
    Cant = 0;
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    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);
            } catch (IOException ioe) {
                System.err.println(ioe.toString());
            }
        }
    } catch (SocketException e) {
        System.err.println(e.toString());
    }

    client.close();
    System.out.println("\n Pomedio " + (Promedio / Cant));
}

From source file:ntpgraphic.LineChart.java

public static void NTPClient(String[] servers, int i) {

    Properties defaultProps = System.getProperties(); //obtiene las "properties" del sistema
    defaultProps.put("java.net.preferIPv6Addresses", "true");//mapea el valor true en la variable java.net.preferIPv6Addresses
    if (servers.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);/*from  w w w . jav a 2  s .  c  o m*/
    }

    Promedio = 0;
    Cant = 0;
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
        client.open();
        for (String arg : servers) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(arg);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info, i);
            } catch (IOException ioe) {
                System.err.println(ioe.toString());
            }
        }
    } catch (SocketException e) {
        System.err.println(e.toString());
    }

    client.close();
    //System.out.println("\n Pomedio "+(Promedio/Cant));
}

From source file:ntpgraphic.PieChart.java

public static void NTPClient(String[] servers) {

    Properties defaultProps = System.getProperties(); //obtiene las "properties" del sistema
    defaultProps.put("java.net.preferIPv6Addresses", "true");//mapea el valor true en la variable java.net.preferIPv6Addresses
    if (servers.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);/*from w ww.j a v  a 2s  .c  o m*/
    }

    Promedio = 0;
    Cant = 0;
    int j = 1;
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
        client.open();
        for (String arg : servers) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(arg);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info, j++);
            } catch (IOException ioe) {
                System.err.println(ioe.toString());
            }
        }
    } catch (SocketException e) {
        System.err.println(e.toString());
    }

    client.close();
    //System.out.println("\n Pomedio "+(Promedio/Cant));
}