TCPTimeDate.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.TimeTCPClient;
  29. import org.openspcoop2.utils.SemaphoreLock;
  30. import org.openspcoop2.utils.UtilsException;

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

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