SHARE
TWEET

Untitled

a guest Aug 22nd, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package mx.hash.ejemplontp;
  7.  
  8. import java.io.IOException;
  9. import java.net.InetAddress;
  10. import java.util.Date;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13.  
  14. import org.apache.commons.net.ntp.NTPUDPClient;
  15. import org.apache.commons.net.ntp.TimeInfo;
  16.  
  17. public class NTPService {
  18.  
  19.     static private final Logger LOGGER = Logger.getLogger("mx.hash.ejemplontp.NTPService");
  20.  
  21.     public Date getNTPDate() {
  22.         String[] hosts = new String[]{"cronos.cenam.mx", "2.mx.pool.ntp.org"};
  23.  
  24.         Date fechaRecibida;
  25.         NTPUDPClient cliente = new NTPUDPClient();
  26.         cliente.setDefaultTimeout(5000);
  27.         for (String host : hosts) {
  28.             try {
  29.                 LOGGER.log(Level.INFO, "Obteniendo fecha desde: {0}", host);
  30.                 InetAddress hostAddr = InetAddress.getByName(host);
  31.                 TimeInfo fecha = cliente.getTime(hostAddr);
  32.                 fechaRecibida = new Date(fecha.getMessage().getTransmitTimeStamp().getTime());
  33.                 return fechaRecibida;
  34.                
  35.             } catch (IOException e) {
  36.                 LOGGER.log(Level.SEVERE, "NO SE PUDO CONECTAR AL SERVIDOR {0}", host);
  37.                 LOGGER.log(Level.SEVERE, e.getMessage(), e);
  38.             }
  39.         }
  40.        
  41.         LOGGER.log(Level.WARNING, "No se pudo conectar con servidor, regresando hora local");
  42.         cliente.close();
  43.         return new Date();
  44.     }
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top