List of usage examples for org.apache.commons.net.ntp NTPUDPClient close
public void close()
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);/* w ww . jav a 2s. co 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: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;/*from w ww . j a v a 2 s . c om*/ 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:experts.net.ip6.ULUA.java
/** * Obtain NTP time stamp value/*from w w w . j a v a 2 s .c om*/ * * @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:ch.lamacrypt.internal.network.NTP.java
/** * Returns the current Unix epoch (in milliseconds), obtained by polling the * following NTP server:/*w w w. j a va 2 s . com*/ * <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: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 www . j a v a2s .c o 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(); }
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 w w w. j a v a 2 s . co 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:flex.helpers.NTPHelper.java
/** * Solicitar hora y fecha a servidor NTP. * /* w w w. j av a 2s .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: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. j ava 2s . c om 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:edu.tcu.gaduo.ihe.iti.ct_transaction.service.NTPClient.java
public Date processResponse(String host) { TimeInfo info = null;/*from www . j a v a 2 s.c o m*/ 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 {/* w w w. ja va 2 s . 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"); }