UDPTimeDate.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */



  20. package org.openspcoop2.utils.date;

  21. import java.net.InetAddress;
  22. import java.sql.Timestamp;
  23. import java.util.Calendar;
  24. import java.util.Date;
  25. import java.util.GregorianCalendar;
  26. import java.util.Map;
  27. import java.util.concurrent.ConcurrentHashMap;

  28. import org.apache.commons.net.time.TimeUDPClient;
  29. import org.openspcoop2.utils.SemaphoreLock;
  30. import org.openspcoop2.utils.UtilsException;

  31. /**
  32.  * Classe per la produzione di date utilizzando un server TimeUDP
  33.  *
  34.  * @author Poli Andrea (apoli@link.it)
  35.  * @author $Author$
  36.  * @version $Rev$, $Date$
  37.  */
  38. public class UDPTimeDate implements IDate {

  39.     private static InetAddress server = null;
  40.     private static TimeUDPClient udpClient = null;
  41.     private static int defaultTimeout = -1;
  42.     private static Map<String,Date> time = null;
  43.     private static boolean cacheEnabled = true;
  44.     private static int cacheRefresh = 100;
  45.    
  46.     private static org.openspcoop2.utils.Semaphore semaphore = new org.openspcoop2.utils.Semaphore("UDPTimeDate");
  47.    
  48.     private static Date getDateCached() throws Exception{
  49.        
  50.         if(UDPTimeDate.cacheEnabled==false){
  51.             return UDPTimeDate.udpClient.getDate(UDPTimeDate.server);
  52.         }
  53.         else{
  54.             String key = (System.currentTimeMillis() / (UDPTimeDate.cacheRefresh)) + ""; // al massimo vengono eseguite 10 richieste al secondo.
  55.             if(UDPTimeDate.time.containsKey(key)){
  56.                 //System.out.println("NOW ["+key+"] from cache");
  57.                 return UDPTimeDate.time.get(key);
  58.             }else{
  59.                 //synchronized(UDPTimeDate.time){
  60.                 SemaphoreLock lock = semaphore.acquire("getDateCached");
  61.                 try {
  62.                     if(UDPTimeDate.time.containsKey(key)){
  63.                         //System.out.println("NOW ["+key+"] from cache sync");
  64.                         return UDPTimeDate.time.get(key);
  65.                     }else{
  66.                         //System.out.println("NOW ["+key+"] no cache");
  67.                         Date d = UDPTimeDate.udpClient.getDate(UDPTimeDate.server);
  68.                         UDPTimeDate.time.clear();
  69.                         UDPTimeDate.time.put(key, d);
  70.                         return d;
  71.                     }
  72.                 }finally {
  73.                     semaphore.release(lock, "getDateCached");
  74.                 }
  75.             }
  76.         }
  77.     }
  78.    
  79.    
  80.     /**
  81.      * Impostazione delle proprieta' per il DateManager
  82.      */
  83.     @Override
  84.     public void init(java.util.Properties properties) throws UtilsException{
  85.         _init(properties);
  86.     }
  87.    
  88.     private static void _init(java.util.Properties properties) throws UtilsException{
  89.         if(UDPTimeDate.udpClient==null) {
  90.             _initSync(properties);
  91.         }
  92.     }
  93.     private static synchronized void _initSync(java.util.Properties properties) throws UtilsException{
  94.         if(UDPTimeDate.udpClient!=null) {
  95.             return;
  96.         }
  97.         try{
  98.             UDPTimeDate.udpClient = new TimeUDPClient();
  99.            
  100.             // timeout
  101.             String timeoutS = properties.getProperty("time.timeout");
  102.             if(timeoutS!=null){
  103.                 try{
  104.                     UDPTimeDate.defaultTimeout = Integer.parseInt(timeoutS);
  105.                 }catch(Exception e){
  106.                     throw new Exception("org.openspcoop.pdd.date.property.time.timeout value non valido: "+e.getMessage(),e);
  107.                 }
  108.             }
  109.             if(UDPTimeDate.defaultTimeout!=-1)
  110.                 UDPTimeDate.udpClient.setDefaultTimeout(UDPTimeDate.defaultTimeout);
  111.            
  112.             // ipaddress
  113.             String ipaddressS = properties.getProperty("time.server");
  114.             if(ipaddressS==null)
  115.                 throw new Exception("org.openspcoop.pdd.date.property.time.server value non definito");
  116.             if(ipaddressS!=null){
  117.                 try{
  118.                     UDPTimeDate.server = InetAddress.getByName(ipaddressS);
  119.                 }catch(Exception e){
  120.                     throw new Exception("org.openspcoop.pdd.date.property.time.server value non valido: "+e.getMessage(),e);
  121.                 }
  122.             }
  123.    
  124.             // cache
  125.             String cacheS = properties.getProperty("time.cache.enable");
  126.             if(cacheS!=null){
  127.                 try{
  128.                     UDPTimeDate.cacheEnabled = Boolean.parseBoolean(cacheS);
  129.                 }catch(Exception e){
  130.                     throw new Exception("org.openspcoop.pdd.date.property.time.cache.enable non valido: "+e.getMessage(),e);
  131.                 }
  132.             }
  133.            
  134.             // intervallo cache refresh
  135.             String cacheRefreshS = properties.getProperty("time.cache.refresh");
  136.             if(cacheRefreshS!=null){
  137.                 try{
  138.                     int value = Integer.parseInt(cacheRefreshS);
  139.                     if(value>1000)
  140.                         throw new Exception("Valore deve essere minore di 1000");
  141.                     UDPTimeDate.cacheRefresh = 1000 / value;
  142.                 }catch(Exception e){
  143.                     throw new Exception("org.openspcoop.pdd.date.property.time.cache.refresh non valido: "+e.getMessage(),e);
  144.                 }
  145.             }
  146.            
  147.             UDPTimeDate.udpClient.open();
  148.            
  149.             UDPTimeDate.time = new ConcurrentHashMap<String,Date>();
  150.            
  151.         }catch(Exception e){
  152.             UDPTimeDate.udpClient=null;
  153.             throw new UtilsException("Inizializzazione TimeUDP Client (properties) non riuscita: "+e.getMessage(),e);
  154.         }
  155.     }
  156.    
  157.     /**
  158.      * Close il DataManager
  159.      *
  160.      * @throws UtilsException
  161.      */
  162.     @Override
  163.     public void close() throws UtilsException{
  164.         try{
  165.             if(UDPTimeDate.udpClient!=null)
  166.                 UDPTimeDate.udpClient.close();
  167.         }catch(Exception e){
  168.             throw new UtilsException("Chiusura TimeUDP Client non riuscita: "+e.getMessage(),e);
  169.         }
  170.     }
  171.    
  172.     /**
  173.      * Ritorna la data corrente.
  174.      *
  175.      * @return Data corrente
  176.      */
  177.     @Override
  178.     public Date getDate() throws UtilsException{
  179.         try{
  180.             if(UDPTimeDate.udpClient==null)
  181.                 throw new Exception("Inizializzazione non effettuata, invocare metodo init");
  182.            
  183.             //System.out.println("UDP getDate ("+UDPTimeDate.getDateCached()+")");
  184.             return UDPTimeDate.getDateCached();
  185.                        
  186.         }catch(Exception e){
  187.             throw new UtilsException("getDate error: "+e.getMessage(),e);
  188.         }
  189.     }
  190.    
  191.     /**
  192.      * Ritorna la data corrente in millisecondi da Gennaio 1.4970.
  193.      *
  194.      * @return Data corrente
  195.      */
  196.     @Override
  197.     public long getTimeMillis()throws UtilsException {
  198.         try{
  199.             if(UDPTimeDate.udpClient==null)
  200.                 throw new Exception("Inizializzazione non effettuata, invocare metodo init");
  201.            
  202.             //System.out.println("UDP getTime ("+UDPTimeDate.getDateCached().getTime()+")");
  203.             return UDPTimeDate.getDateCached().getTime();
  204.                        
  205.         }catch(Exception e){
  206.             throw new UtilsException("getDate error: "+e.getMessage(),e);
  207.         }
  208.     }
  209.    
  210.     /**
  211.      * Ritorna la data corrente come timestamp SQL.
  212.      *
  213.      * @return Data corrente
  214.      */
  215.     @Override
  216.     public Timestamp getTimestamp() throws UtilsException{
  217.         try{
  218.             if(UDPTimeDate.udpClient==null)
  219.                 throw new Exception("Inizializzazione non effettuata, invocare metodo init");
  220.            
  221.             //System.out.println("UDP getTimestamp ("+new Timestamp(UDPTimeDate.getDateCached().getTime())+")");
  222.             return new Timestamp(UDPTimeDate.getDateCached().getTime());
  223.                        
  224.         }catch(Exception e){
  225.             throw new UtilsException("getDate error: "+e.getMessage(),e);
  226.         }  
  227.     }
  228.    
  229.     /**
  230.      * Ritorna la data corrente come Calendar
  231.      *
  232.      * @return Data corrente
  233.      */
  234.     @Override
  235.     public Calendar getCalendar() throws UtilsException{
  236.         Calendar c = new GregorianCalendar();
  237.         c.setTime(this.getDate());
  238.         return c;
  239.     }
  240. }