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:NTP_Example.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);/*from  w  w  w. java2  s  .c  o  m*/
    }

    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) {
                ioe.printStackTrace();
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

    client.close();
}

From source file:de.pawlidi.openaletheia.utils.DateTimeUtils.java

public static long getCurrentTime() {
    try {// w w  w  .  j  av a 2s .  c  o m
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName("time-c.nist.gov");
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        return timeInfo.getReturnTime();
    } catch (IOException e) {
        // TODO: handle exception
    }
    return -1;
}

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;/*  ww  w . j a v a2 s .com*/
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(clockDriftConfig.getTimeout());
    client.open();
    LOG.debug("NTP server: " + ntpServerAddress);
    timeInfo = client.getTime(ntpServerAddress);
    client.close();
    timeInfo.computeDetails();
    return timeInfo;
}

From source file:com.DSC.client.SecureChannel.java

/**
 * Gets the date time offset for the client using a NTP server
 * @throws IOException /*from   ww w .ja  v a 2  s .  c om*/
 */
private static long getTimeOffset() throws IOException {
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(NTP_SERVER);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    return DateTimeUtils.currentTimeMillis() - timeInfo.getReturnTime();
}

From source file:ch.lamacrypt.internal.network.NTP.java

/**
 * Returns the current Unix epoch (in milliseconds), obtained by polling the
 * following NTP server://from www  .  j a v  a 2 s . co  m
 * <ul>
 * <li>0.ch.pool.ntp.org</li>
 * <li>0.is.pool.ntp.org</li>
 *
 * </ul>
 * <p>
 * Waits up to 10 seconds to get a response
 *
 * @return current Unix epoch, in milliseconds
 */
public static long getTime() {
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(10000);
    hosts[0] = "0.ch.pool.ntp.org";
    hosts[1] = "0.is.pool.ntp.org";
    boolean done = false;
    long epoch = 0;
    int i = 0;

    while (!done) {
        try {
            InetAddress hostAddr = InetAddress.getByName(hosts[i]);
            epoch = client.getTime(hostAddr).getReturnTime();
            done = true;
        } catch (IOException ex) {
            ErrorHandler.showError(ex);
        }
        i++;
    }

    client.close();
    return epoch;
}

From source file:com.fuensalida.utils.FechaExternaNTP.java

public static Date getNTPDateROA() {
    String servidor = "minuto.roa.es";
    //Se le da un valor nulo por defecto a la variable

    Date fechaRecibida = null;//from   ww w . ja  va2  s  .  c o m
    //Se crea un objeto de tipo NTPUDPClient Clase de la libreria Commons

    NTPUDPClient cliente = new NTPUDPClient();
    //Tiempo de Espera Antes De Mandar Error.

    cliente.setDefaultTimeout(5000);
    try {
        //Obtenemos la direccion IP por medio de el host previamente Asignado

        InetAddress hostAddr = InetAddress.getByName(servidor);
        //Solicitamos la fecha al servidor

        TimeInfo fecha = cliente.getTime(hostAddr);
        //Recibimos y convertimos la fecha a formato DATE

        fechaRecibida = new Date(fecha.getMessage().getTransmitTimeStamp().getTime());
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
    //Cerramos la comunicacin con el cliente

    cliente.close();
    //Retornamos la fecha ya convertida si no es nula , de ser nula regresa la fecha Local

    return fechaRecibida == null ? new Date() : fechaRecibida;

}

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

/**
 * Obtain NTP time stamp value// 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:com.savoycraft.util.TimeUtil.java

/**
 * Queries a NIST time server to get a difference between its time and the
 * local system time./*w  w w . ja v a 2 s  .co  m*/
 */
public static void calibrate() {
    if (System.currentTimeMillis() < lastTimeRequest + 5000 || calibrated) {
        return;
    }

    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByName(TIME_SERVER);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }
    TimeInfo timeInfo = null;
    try {
        timeInfo = timeClient.getTime(inetAddress);
    } catch (IOException e) {
        System.err.println("SavoyCraft could not contact time.nist.gov.");
        e.printStackTrace();
        return;
    }
    long returnTime = timeInfo.getReturnTime();
    calibration = System.currentTimeMillis() - returnTime;
    System.out.println(calibration);
    // Date time = new Date(returnTime);
    // System.out.println("Time from " + TIME_SERVER + ": " + time);

    lastTimeRequest = System.currentTimeMillis();

    calibrated = true;
}

From source file:flex.helpers.NTPHelper.java

/**
 * Solicitar hora y fecha a servidor NTP.
 * /*from   w ww  .ja  v  a  2  s .c  o  m*/
 * @param ntpServer Direccin ip del servidor NTP
 * @return
 * @throws NTPHelperException 
 */
public static Date getDateTime(String ntpServer) throws NTPHelperException {
    if (ntpServer == null)
        throw new NTPHelperException(NTPHelperException.ERROR_NTP_EMPTY);
    if (ntpServer.isEmpty())
        throw new NTPHelperException(NTPHelperException.ERROR_NTP_EMPTY);

    Date time = null;
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(NTP_TIMEOUT);

    try {
        client.open();
        InetAddress hostAddr = InetAddress.getByName(ntpServer);
        TimeInfo info = client.getTime(hostAddr);
        time = processResponse(info);

    } catch (UnknownHostException ex) {
        throw new NTPHelperException(NTPHelperException.ERROR_NTP_UNKNOWN_HOST, ex.getCause());

    } catch (SocketException ex) {
        throw new NTPHelperException(NTPHelperException.ERROR_NTP_SOCKET, ex.getCause());

    } catch (IOException ex) {
        throw new NTPHelperException(NTPHelperException.ERROR_NTP_READ, ex.getCause());

    } finally {
        client.close();
        System.gc();
    }

    return time;
}

From source file:amplify.NTPClient.java

public static void syncServerTime(String ntpServerAddress) throws IOException {
    NTPUDPClient client = new NTPUDPClient();

    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);//from   w  ww  .j a va  2  s . co  m
    try {
        client.open();
        System.out.println();
        try {
            InetAddress hostAddr = InetAddress.getByName(ntpServerAddress);
            System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
            TimeInfo info = client.getTime(hostAddr);
            processResponse(info);
        } catch (IOException ioe) {
            client.close();
            throw ioe;
        }
    } catch (SocketException e) {
        client.close();
        throw e;
    }

    client.close();
}