GestoreCacheControlloTraffico.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.pdd.core.controllo_traffico.policy;

  21. import java.text.SimpleDateFormat;
  22. import java.util.Collections;
  23. import java.util.Date;
  24. import java.util.List;
  25. import java.util.stream.Collectors;

  26. import org.openspcoop2.core.commons.CoreException;
  27. import org.openspcoop2.core.constants.TipoPdD;
  28. import org.openspcoop2.core.controllo_traffico.AttivazionePolicyFiltro;
  29. import org.openspcoop2.core.controllo_traffico.beans.DatiTransazione;
  30. import org.openspcoop2.core.controllo_traffico.beans.IDUnivocoGroupByPolicy;
  31. import org.openspcoop2.core.controllo_traffico.beans.RisultatoStatistico;
  32. import org.openspcoop2.core.controllo_traffico.beans.RisultatoStato;
  33. import org.openspcoop2.core.controllo_traffico.constants.TipoBanda;
  34. import org.openspcoop2.core.controllo_traffico.constants.TipoFinestra;
  35. import org.openspcoop2.core.controllo_traffico.constants.TipoLatenza;
  36. import org.openspcoop2.core.controllo_traffico.constants.TipoPeriodoStatistico;
  37. import org.openspcoop2.core.controllo_traffico.constants.TipoRisorsa;
  38. import org.openspcoop2.core.controllo_traffico.utils.PolicyUtilities;
  39. import org.openspcoop2.core.id.IDServizio;
  40. import org.openspcoop2.core.id.IDSoggetto;
  41. import org.openspcoop2.pdd.core.cache.CacheEntry;
  42. import org.openspcoop2.pdd.core.controllo_traffico.ConfigurazioneGatewayControlloTraffico;
  43. import org.openspcoop2.pdd.core.controllo_traffico.INotify;
  44. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  45. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  46. import org.openspcoop2.protocol.sdk.state.IState;
  47. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  48. import org.openspcoop2.utils.SemaphoreLock;
  49. import org.openspcoop2.utils.UtilsException;
  50. import org.openspcoop2.utils.cache.Cache;
  51. import org.openspcoop2.utils.cache.CacheAlgorithm;
  52. import org.openspcoop2.utils.cache.CacheType;
  53. import org.openspcoop2.utils.date.DateUtils;
  54. import org.slf4j.Logger;

  55. /**    
  56.  * GestoreCacheControlloTraffico
  57.  *
  58.  * @author Poli Andrea (poli@link.it)
  59.  * @author $Author$
  60.  * @version $Rev$, $Date$
  61.  */
  62. public class GestoreCacheControlloTraffico {

  63.     /** Chiave della cache per l'autenticazione Buste  */
  64.     private static final String CONTROLLO_TRAFFICO_CACHE_NAME = "controlloTraffico";
  65.     /** Cache */
  66.     private static Cache cache = null;
  67. //  private static final Boolean semaphoreNumeroRichieste = true;
  68. //  private static final Boolean semaphoreOccupazioneBanda = true;
  69. //  private static final Boolean semaphoreLatenza = true;
  70. //  private static final Boolean semaphoreStato = true;
  71.     private static final org.openspcoop2.utils.Semaphore lockNumeroEsiti = new org.openspcoop2.utils.Semaphore("GestoreCacheControlloTraffico-NumeroEsiti");
  72.     private static final org.openspcoop2.utils.Semaphore lockNumeroRichieste = new org.openspcoop2.utils.Semaphore("GestoreCacheControlloTraffico-NumeroRichieste");
  73.     private static final org.openspcoop2.utils.Semaphore lockOccupazioneBanda = new org.openspcoop2.utils.Semaphore("GestoreCacheControlloTraffico-OccupazioneBanda");
  74.     private static final org.openspcoop2.utils.Semaphore lockLatenza = new org.openspcoop2.utils.Semaphore("GestoreCacheControlloTraffico-Latenza");
  75.     private static final org.openspcoop2.utils.Semaphore lockStato = new org.openspcoop2.utils.Semaphore("GestoreCacheControlloTraffico-Stato");

  76.     /* --------------- Cache --------------------*/
  77.     public static boolean isCacheAbilitata() throws Exception{
  78.         return cache!=null;
  79.     }
  80.     public static void resetCache() throws Exception{
  81.         try{
  82.             if(cache!=null){
  83.                 cache.clear();
  84.             }
  85.         }catch(Exception e){
  86.             throw new Exception("Reset della cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  87.         }
  88.     }
  89.     public static String printStatsCache(String separator) throws Exception{
  90.         try{
  91.             if(cache!=null){
  92.                 try{
  93.                     return cache.printStats(separator);
  94.                 }catch(Exception e){
  95.                     throw new Exception(e.getMessage(),e);
  96.                 }
  97.             }else{
  98.                 throw new Exception("Cache non abilitata");
  99.             }
  100.         }catch(Exception e){
  101.             throw new Exception("Visualizzazione Statistiche riguardante la cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  102.         }
  103.     }
  104.     public static void abilitaCache() throws Exception{
  105.         try{
  106.             if(cache!=null)
  107.                 throw new Exception("Cache gia' abilitata");
  108.             else{
  109.                 _abilitaCache();
  110.             }
  111.         }catch(Exception e){
  112.             throw new Exception("Abilitazione cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  113.         }
  114.     }
  115.     private static synchronized void _abilitaCache() throws Exception{
  116.         try{
  117.             if(cache==null) {
  118.                 cache = new Cache(CacheType.JCS, CONTROLLO_TRAFFICO_CACHE_NAME); // lascio JCS come default abilitato via jmx
  119.                 cache.build();
  120.             }
  121.         }catch(Exception e){
  122.             throw new Exception("Abilitazione cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  123.         }
  124.     }
  125.     public static void abilitaCache(Long dimensioneCache,Boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond, Logger log) throws Exception{
  126.         try{
  127.             if(cache!=null)
  128.                 throw new Exception("Cache gia' abilitata");
  129.             else{
  130.                 int dimensione = -1;
  131.                 if(dimensioneCache!=null){
  132.                     dimensione = dimensioneCache.intValue();
  133.                 }
  134.                 initCache(CacheType.JCS, dimensione, algoritmoCacheLRU, itemIdleTime, itemLifeSecond, log); // lascio JCS come default abilitato via jmx
  135.             }
  136.         }catch(Exception e){
  137.             throw new Exception("Abilitazione cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  138.         }
  139.     }
  140.     public static void disabilitaCache() throws Exception{
  141.         try{
  142.             if(cache==null)
  143.                 throw new Exception("Cache gia' disabilitata");
  144.             else{
  145.                 _disabilitaCache();
  146.             }
  147.         }catch(Exception e){
  148.             throw new Exception("Disabilitazione cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  149.         }
  150.     }
  151.     private static synchronized void _disabilitaCache() throws Exception{
  152.         try{
  153.             if(cache!=null){
  154.                 cache.clear();
  155.                 cache = null;
  156.             }
  157.         }catch(Exception e){
  158.             throw new Exception("Disabilitazione cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  159.         }
  160.     }
  161.     public static String listKeysCache(String separator) throws Exception{
  162.         try{
  163.             if(cache!=null){
  164.                 try{
  165.                     return cache.printKeys(separator);
  166.                 }catch(Exception e){
  167.                     throw new Exception(e.getMessage(),e);
  168.                 }
  169.             }else{
  170.                 throw new Exception("Cache non abilitata");
  171.             }
  172.         }catch(Exception e){
  173.             throw new Exception("Visualizzazione chiavi presenti nella cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  174.         }
  175.     }
  176.    
  177.     public static String getObjectCache(String key) throws Exception{
  178.         try{
  179.             if(cache!=null){
  180.                 try{
  181.                     Object o = cache.get(key);
  182.                     if(o!=null){
  183.                         return o.toString();
  184.                     }else{
  185.                         return "oggetto con chiave ["+key+"] non presente";
  186.                     }
  187.                 }catch(Exception e){
  188.                     throw new Exception(e.getMessage(),e);
  189.                 }
  190.             }else{
  191.                 throw new Exception("Cache non abilitata");
  192.             }
  193.         }catch(Exception e){
  194.             throw new Exception("Visualizzazione oggetto presente nella cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  195.         }
  196.     }
  197.    
  198.     public static void removeObjectCache(String key) throws Exception{
  199.         try{
  200.             if(cache!=null){
  201.                 try{
  202.                     cache.remove(key);
  203.                 }catch(Exception e){
  204.                     throw new Exception(e.getMessage(),e);
  205.                 }
  206.             }else{
  207.                 throw new Exception("Cache non abilitata");
  208.             }
  209.         }catch(Exception e){
  210.             throw new Exception("Rimozione oggetto presente nella cache per i dati sul controllo del traffico non riuscita: "+e.getMessage(),e);
  211.         }
  212.     }
  213.    
  214.    

  215.     public static void initializeCache(CacheType cacheType, Long dimensioneCache,Boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond, Logger log) throws Exception{
  216.         int dimensione = -1;
  217.         if(dimensioneCache!=null){
  218.             dimensione = dimensioneCache.intValue();
  219.         }
  220.         initCache(cacheType, dimensione, algoritmoCacheLRU, itemIdleTime, itemLifeSecond, log);
  221.     }
  222.    
  223.     private static void initCache(CacheType cacheType, Integer dimensioneCache,boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond,Logger alog) throws Exception{
  224.        
  225.         cache = new Cache(cacheType, CONTROLLO_TRAFFICO_CACHE_NAME);
  226.    
  227.         // dimensione
  228.         if(dimensioneCache!=null && dimensioneCache>0){
  229.             try{
  230.                 String msg = "Dimensione della cache (ControlloTraffico) impostata al valore: "+dimensioneCache;
  231.                 alog.info(msg);
  232.                 cache.setCacheSize(dimensioneCache);
  233.             }catch(Exception error){
  234.                 String msg = "Parametro errato per la dimensione della cache (ControlloTraffico): "+error.getMessage();
  235.                 alog.error(msg);
  236.                 throw new Exception(msg,error);
  237.             }
  238.         }
  239.        
  240.         // algoritno
  241.         String msg = "Algoritmo di cache (ControlloTraffico) impostato al valore: LRU";
  242.         if(!algoritmoCacheLRU){
  243.             msg = "Algoritmo di cache (ControlloTraffico) impostato al valore: MRU";
  244.         }
  245.         alog.info(msg);
  246.         if(!algoritmoCacheLRU)
  247.             cache.setCacheAlgoritm(CacheAlgorithm.MRU);
  248.         else
  249.             cache.setCacheAlgoritm(CacheAlgorithm.LRU);
  250.        
  251.        
  252.         // idle time
  253.         if(itemIdleTime!=null && itemIdleTime>0){
  254.             try{
  255.                 msg = "Attributo 'IdleTime' (ControlloTraffico) impostato al valore: "+itemIdleTime;
  256.                 alog.info(msg);
  257.                 cache.setItemIdleTime(itemIdleTime);
  258.             }catch(Exception error){
  259.                 msg = "Parametro errato per l'attributo 'IdleTime' (ControlloTraffico): "+error.getMessage();
  260.                 alog.error(msg);
  261.                 throw new Exception(msg,error);
  262.             }
  263.         }
  264.        
  265.         // LifeSecond
  266.         long longItemLife = -1;
  267.         if(itemLifeSecond!=null && itemLifeSecond>0){
  268.             longItemLife = itemLifeSecond.longValue();
  269.         }
  270.         try{
  271.             msg = "Attributo 'MaxLifeSecond' (ControlloTraffico) impostato al valore: "+longItemLife;
  272.             alog.info(msg);
  273.             cache.setItemLifeTime(longItemLife);
  274.         }catch(Exception error){
  275.             msg = "Parametro errato per l'attributo 'MaxLifeSecond' (ControlloTraffico): "+error.getMessage();
  276.             alog.error(msg);
  277.             throw new Exception(msg,error);
  278.         }
  279.        
  280.         cache.build();
  281.        
  282.     }
  283.    
  284.     @SuppressWarnings("deprecation")
  285.     @Deprecated
  286.     public static void disableSyncronizedGet() throws UtilsException {
  287.         if(cache==null) {
  288.             throw new UtilsException("Cache disabled");
  289.         }
  290.         cache.disableSyncronizedGet();
  291.     }
  292.     @SuppressWarnings("deprecation")
  293.     @Deprecated
  294.     public static boolean isDisableSyncronizedGet() throws UtilsException {
  295.         if(cache==null) {
  296.             throw new UtilsException("Cache disabled");
  297.         }
  298.         return cache.isDisableSyncronizedGet();
  299.     }
  300.    
  301.    
  302.    
  303.     private static GestoreCacheControlloTraffico staticInstance = null;
  304.     public static synchronized void initialize(ConfigurazioneGatewayControlloTraffico configurazioneControlloTraffico) throws CoreException{
  305.         if(staticInstance==null){
  306.             staticInstance = new GestoreCacheControlloTraffico(configurazioneControlloTraffico);
  307.         }
  308.     }
  309.     public static GestoreCacheControlloTraffico getInstance() throws CoreException{
  310.         if(staticInstance==null){
  311.             // spotbugs warning 'SING_SINGLETON_GETTER_NOT_SYNCHRONIZED': l'istanza viene creata allo startup
  312.             synchronized (GestoreCacheControlloTraffico.class) {
  313.                 throw new CoreException("GestoreCacheControlloTraffico non inizializzato");
  314.             }
  315.         }
  316.         return staticInstance;
  317.     }
  318.    
  319.     private DatiStatisticiDAOManager datiStatisticiReader = null;
  320.     private INotify datiNotifierReader = null;
  321.     private Logger log;
  322.     private boolean debug;
  323.     private ConfigurazioneGatewayControlloTraffico configurazioneControlloTraffico;
  324.    
  325.     private GestoreCacheControlloTraffico(ConfigurazioneGatewayControlloTraffico configurazioneControlloTraffico) throws CoreException {
  326.         this.datiStatisticiReader = DatiStatisticiDAOManager.getInstance();
  327.         if(configurazioneControlloTraffico.isNotifierEnabled()){
  328.             this.datiNotifierReader = configurazioneControlloTraffico.getNotifier();
  329.         }
  330.         this.configurazioneControlloTraffico = configurazioneControlloTraffico;
  331.         this.debug = this.configurazioneControlloTraffico.isDebug();
  332.         this.log = OpenSPCoop2Logger.getLoggerOpenSPCoopControlloTraffico(this.debug);
  333.     }
  334.    
  335.    
  336.    
  337.    
  338.     /*********************** NUMERO ESITI ******************************* */
  339.     public RisultatoStatistico readNumeroEsiti(TipoPeriodoStatistico tipoPeriodo, Integer periodLength, Date endDate,
  340.             List<Integer> esiti, IDServizio servizio, IDSoggetto mittente, List<String> ignoreOperations, DatiTransazione datiTransazione, IState state, Integer lifetimeSecond) throws Exception{
  341.                        
  342.         // BuildKey
  343.         SimpleDateFormat dateformat;
  344.         switch(tipoPeriodo) {
  345.         case ORARIO: dateformat = DateUtils.getSimpleDateFormatHour(); break;
  346.         case GIORNALIERO: dateformat = DateUtils.getSimpleDateFormatDay(); break;
  347.         case SETTIMANALE: dateformat = DateUtils.getSimpleDateFormatDay(); break;
  348.         case MENSILE: dateformat = DateUtils.getSimpleDateFormatDay(); break;
  349.         default: dateformat = DateUtils.getSimpleDateFormatDay(); break;
  350.         }
  351.        
  352.        
  353.         StringBuilder bfKey = new StringBuilder(servizio.toString());      
  354.         if (ignoreOperations != null) {
  355.             Collections.sort(ignoreOperations);
  356.             bfKey.append("~" + ignoreOperations);
  357.         }
  358.         bfKey.append(mittente == null ? "" : " " + mittente);
  359.         bfKey.append(esiti == null ? "" : " " + String.join(",", esiti.stream().map(Object::toString).collect(Collectors.toList())));
  360.         bfKey.append(" [").append(dateformat.format(endDate));
  361.         bfKey.append("-").append(periodLength).append(" ").append(tipoPeriodo).append("]");
  362.         String key = bfKey.toString();
  363.        
  364.         // Search key
  365.         RisultatoStatistico risultato = null;
  366.         if(GestoreCacheControlloTraffico.cache!=null){
  367.             risultato = this.readNumeroEsiti(key, tipoPeriodo, periodLength, endDate,
  368.                 esiti, servizio, mittente, ignoreOperations, datiTransazione, state, lifetimeSecond);
  369.         }
  370.         else{
  371.             risultato = this.datiStatisticiReader.readNumeroEsiti(key, tipoPeriodo, periodLength, endDate,
  372.                     esiti, servizio, mittente, ignoreOperations, datiTransazione, state);
  373.         }
  374.         return risultato;
  375.     }
  376.    
  377.     private RisultatoStatistico readNumeroEsiti(String keyCache, TipoPeriodoStatistico tipoPeriodo, Integer periodLength, Date endDate,
  378.             List<Integer> esiti, IDServizio servizio, IDSoggetto mittente, List<String> ignoreOperations, DatiTransazione datiTransazione, IState state, Integer lifetimeSecond) throws Exception{

  379.         RisultatoStatistico obj = null;
  380.         try{

  381.             if(keyCache == null)
  382.                 throw new Exception("KeyCache non definita");

  383.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  384.             if(cache!=null){
  385.                 org.openspcoop2.utils.cache.CacheResponse response =
  386.                     (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  387.                 if(response != null){
  388.                     if(response.getObject()!=null){
  389.                         this.log.debug("Oggetto (tipo:{}) con chiave [{}] valore[{}] in cache.", response.getObject().getClass().getName(), keyCache, response.getObject());
  390.                         @SuppressWarnings("unchecked")
  391.                         CacheEntry<RisultatoStatistico> entry = (CacheEntry<RisultatoStatistico>) response.getObject();
  392.                         if (entry.isValid())
  393.                             return entry.getObject();
  394.                     }else if(response.getException()!=null){
  395.                         this.log.debug("Eccezione (tipo:{}) con chiave [{}]", response.getException().getClass().getName().concat(keyCache), keyCache);
  396.                         throw (Exception) response.getException();
  397.                     }else{
  398.                         this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  399.                     }
  400.                 }
  401.             }
  402.            
  403.             String idTransazione = datiTransazione!=null ? datiTransazione.getIdTransazione() : null;
  404.             SemaphoreLock lock = lockNumeroEsiti.acquire("readNumeroEsitiInCache", idTransazione);
  405.             try {
  406.                
  407.                 // se e' attiva una cache provo ad utilizzarla
  408.                 if(cache!=null){
  409.                     org.openspcoop2.utils.cache.CacheResponse response =
  410.                         (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  411.                     if(response != null){
  412.                         if(response.getObject()!=null){
  413.                             this.log.debug("Oggetto (tipo:{}) con chiave [{}] valore[{}] in cache.", response.getObject().getClass().getName(), keyCache, response.getObject());
  414.                             @SuppressWarnings("unchecked")
  415.                             CacheEntry<RisultatoStatistico> entry = (CacheEntry<RisultatoStatistico>) response.getObject();
  416.                             if (entry.isValid())
  417.                                 return entry.getObject();
  418.                         }else if(response.getException()!=null){
  419.                             this.log.debug("Eccezione (tipo:{}) con chiave [{}] in cache.", response.getException().getClass().getName(), keyCache);
  420.                             throw (Exception) response.getException();
  421.                         }else{
  422.                             this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  423.                         }
  424.                     }
  425.                 }
  426.    
  427.                 // Effettuo le query nella mia gerarchia di registri.
  428.                 this.log.debug("oggetto con chiave [{}] non in cache, effettuo ricerca...", keyCache);
  429.                 try{
  430.                     obj = this.datiStatisticiReader.readNumeroEsiti(keyCache, tipoPeriodo, periodLength, endDate,
  431.                          esiti, servizio, mittente,  ignoreOperations, datiTransazione, state);
  432.                 }catch(Exception e){
  433.                     throw e;
  434.                 }
  435.    
  436.                 // Aggiungo la risposta in cache (se esiste una cache)  
  437.                 // Se ho una eccezione aggiungo in cache solo una not found
  438.                 if( cache!=null ){  
  439.                     if(obj!=null){
  440.                         this.log.debug("Aggiungo oggetto con chiave [{}] valore[{}] in cache", keyCache, obj);
  441.                     }else{
  442.                         throw new Exception("Ricerca ha ritornato un valore null");
  443.                     }
  444.                     try{    
  445.                         org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  446.                         responseCache.setObject(new CacheEntry<RisultatoStatistico>(obj, lifetimeSecond * 1000l));
  447.                        
  448.                         cache.put(keyCache,responseCache);
  449.                     }catch(UtilsException e){
  450.                         this.log.error("Errore durante l'inserimento in cache con chiave [{}] valore[{}]: {}", keyCache, obj, e.getMessage());
  451.                     }
  452.                 }
  453.             }finally {
  454.                 lockNumeroEsiti.release(lock, "readNumeroEsitiInCache", idTransazione);
  455.             }

  456.         }
  457.         catch(Exception e){
  458.             this.log.error(e.getMessage(),e);
  459.             throw new Exception("NumeroEsiti, Algoritmo di Cache fallito: "+e.getMessage(),e);
  460.         }

  461.         return obj;
  462.     }
  463.    
  464.    
  465.     /* ********************** NUMERO RICHIESTE ************************** */
  466.    
  467.     public RisultatoStatistico readNumeroRichieste(TipoRisorsa tipoRisorsa,
  468.             Date leftInterval, Date rightInterval,
  469.             TipoFinestra tipoFinestra, TipoPeriodoStatistico tipoPeriodo,
  470.             DatiTransazione datiTransazione,IDUnivocoGroupByPolicy groupByPolicy, AttivazionePolicyFiltro filtro,
  471.             IState state,
  472.             RequestInfo requestInfo,
  473.             IProtocolFactory<?> protocolFactory) throws Exception{
  474.                        
  475.         // BuildKey
  476.         SimpleDateFormat dateformat = DateUtils.getSimpleDateFormatMs();
  477.        
  478.         TipoPdD tipoPdDTransazioneInCorso = datiTransazione.getTipoPdD();
  479.        
  480.         StringBuilder bfKey = new StringBuilder(tipoRisorsa.getValue()+" ");
  481.         bfKey.append(tipoFinestra.getValue());
  482.         bfKey.append(" ").append(tipoPeriodo.getValue());
  483.         bfKey.append(" ").append(tipoPdDTransazioneInCorso.getTipo());
  484.         bfKey.append(" [").append(dateformat.format(leftInterval)).append("]");
  485.         bfKey.append("-[").append(dateformat.format(rightInterval)).append("]");
  486.         bfKey.append(" GroupBy ");
  487.         bfKey.append(groupByPolicy.toString());
  488.         if(filtro!=null && filtro.isEnabled()) {
  489.             bfKey.append(" Filtro ");
  490.             bfKey.append(PolicyUtilities.toStringFilter(filtro));
  491.         }
  492.         String key = bfKey.toString();
  493.        
  494.         //System.out.println("CERCO OGGETTO CON CHIAVE ["+key+"]");
  495.        
  496.         RisultatoStatistico risultato = null;
  497.         if(GestoreCacheControlloTraffico.cache!=null){
  498.             risultato = this.readNumeroRichiesteInCache(key, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval,
  499.                     datiTransazione, groupByPolicy, filtro,
  500.                     state,
  501.                     requestInfo,
  502.                     protocolFactory);
  503.         }
  504.         else{
  505.             risultato = this.datiStatisticiReader.readNumeroRichieste(key, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval,
  506.                     datiTransazione, groupByPolicy, filtro,
  507.                     state,
  508.                     requestInfo,
  509.                     protocolFactory );
  510.         }
  511.         return risultato;
  512.     }
  513.    
  514.     private RisultatoStatistico readNumeroRichiesteInCache(String keyCache,
  515.             TipoRisorsa tipoRisorsa,TipoFinestra tipoFinestra,TipoPeriodoStatistico tipoPeriodo,
  516.             Date leftInterval, Date rightInterval,
  517.             DatiTransazione datiTransazione,IDUnivocoGroupByPolicy groupByPolicy, AttivazionePolicyFiltro filtro,
  518.             IState state,
  519.             RequestInfo requestInfo,
  520.             IProtocolFactory<?> protocolFactory) throws Exception{

  521.         RisultatoStatistico obj = null;
  522.         try{

  523.             if(keyCache == null)
  524.                 throw new Exception("KeyCache non definita");

  525.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  526.             if(cache!=null){
  527.                 org.openspcoop2.utils.cache.CacheResponse response =
  528.                     (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  529.                 if(response != null){
  530.                     if(response.getObject()!=null){
  531.                         this.log.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] valore["+response.getObject()+"] in cache.");
  532.                         //System.out.println("RITORNO OGGETTO IN CACHE CON CHIAVE ["+keyCache+"]: ["+response.getObject()+"]");
  533.                         return (RisultatoStatistico) response.getObject();
  534.                     }else if(response.getException()!=null){
  535.                         this.log.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] in cache.");
  536.                         throw (Exception) response.getException();
  537.                     }else{
  538.                         this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  539.                     }
  540.                 }
  541.             }
  542.            
  543.             String idTransazione = datiTransazione!=null ? datiTransazione.getIdTransazione() : null;
  544.             //synchronized (semaphoreNumeroRichieste) {
  545.             SemaphoreLock lock = lockNumeroRichieste.acquire("readNumeroRichiesteInCache", idTransazione);
  546.             try {
  547.                
  548.                 // se e' attiva una cache provo ad utilizzarla
  549.                 if(cache!=null){
  550.                     org.openspcoop2.utils.cache.CacheResponse response =
  551.                         (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  552.                     if(response != null){
  553.                         if(response.getObject()!=null){
  554.                             this.log.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] valore["+response.getObject()+"] in cache.");
  555.                             //System.out.println("RITORNO OGGETTO IN CACHE CON CHIAVE ["+keyCache+"]: ["+response.getObject()+"]");
  556.                             return (RisultatoStatistico) response.getObject();
  557.                         }else if(response.getException()!=null){
  558.                             this.log.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] in cache.");
  559.                             throw (Exception) response.getException();
  560.                         }else{
  561.                             this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  562.                         }
  563.                     }
  564.                 }
  565.    
  566.                 // Effettuo le query nella mia gerarchia di registri.
  567.                 this.log.debug("oggetto con chiave ["+keyCache+"] non in cache, effettuo ricerca...");
  568.                 try{
  569.                     obj = this.datiStatisticiReader.readNumeroRichieste(keyCache, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval,
  570.                             datiTransazione, groupByPolicy, filtro,
  571.                             state,
  572.                             requestInfo,
  573.                             protocolFactory);
  574.                 }catch(Exception e){
  575.                     throw e;
  576.                 }
  577.    
  578.                 // Aggiungo la risposta in cache (se esiste una cache)  
  579.                 // Se ho una eccezione aggiungo in cache solo una not found
  580.                 if( cache!=null ){  
  581.                     if(obj!=null){
  582.                         this.log.debug("Aggiungo oggetto con chiave ["+keyCache+"] valore["+obj+"] in cache");
  583.                     }else{
  584.                         throw new Exception("Ricerca ha ritornato un valore null");
  585.                     }
  586.                     try{    
  587.                         org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  588.                         responseCache.setObject((java.io.Serializable)obj);
  589.                         cache.put(keyCache,responseCache);
  590.                     }catch(UtilsException e){
  591.                         this.log.error("Errore durante l'inserimento in cache con chiave ["+keyCache+"] valore["+obj+"]: "+e.getMessage());
  592.                     }
  593.                 }
  594.             }finally {
  595.                 lockNumeroRichieste.release(lock, "readNumeroRichiesteInCache", idTransazione);
  596.             }

  597.         }
  598.         catch(Exception e){
  599.             this.log.error(e.getMessage(),e);
  600.             throw new Exception("NumeroRichieste, Algoritmo di Cache fallito: "+e.getMessage(),e);
  601.         }

  602.         return obj;
  603.     }
  604.    
  605.    
  606.    
  607.    
  608.    
  609.    
  610.     /* ********************** OCCUPAZIONE BANDA ************************** */
  611.    
  612.     public RisultatoStatistico readOccupazioneBanda(TipoRisorsa tipoRisorsa,
  613.             Date leftInterval, Date rightInterval,
  614.             TipoFinestra tipoFinestra, TipoPeriodoStatistico tipoPeriodo,
  615.             TipoBanda tipoBanda,
  616.             DatiTransazione datiTransazione,IDUnivocoGroupByPolicy groupByPolicy, AttivazionePolicyFiltro filtro,
  617.             IState state,
  618.             RequestInfo requestInfo,
  619.             IProtocolFactory<?> protocolFactory) throws Exception{
  620.        
  621.         // BuildKey
  622.         SimpleDateFormat dateformat = DateUtils.getSimpleDateFormatMs();
  623.        
  624.         TipoPdD tipoPdDTransazioneInCorso = datiTransazione.getTipoPdD();
  625.        
  626.         StringBuilder bfKey = new StringBuilder(tipoRisorsa.getValue()+" ");
  627.         bfKey.append(tipoFinestra.getValue());
  628.         bfKey.append(" ").append(tipoPeriodo.getValue());
  629.         bfKey.append(" ").append(tipoBanda.getValue());
  630.         bfKey.append(" ").append(tipoPdDTransazioneInCorso.getTipo());
  631.         bfKey.append(" [").append(dateformat.format(leftInterval)).append("]");
  632.         bfKey.append("-[").append(dateformat.format(rightInterval)).append("]");
  633.         bfKey.append(" GroupBy ");
  634.         bfKey.append(groupByPolicy.toString());
  635.         if(filtro!=null && filtro.isEnabled()) {
  636.             bfKey.append(" Filtro ");
  637.             bfKey.append(PolicyUtilities.toStringFilter(filtro));
  638.         }
  639.         String key = bfKey.toString();
  640.        
  641.         //System.out.println("CERCO OGGETTO CON CHIAVE ["+key+"]");
  642.        
  643.         RisultatoStatistico risultato = null;
  644.         if(GestoreCacheControlloTraffico.cache!=null){
  645.             risultato = this.readOccupazioneBandaInCache(key, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval, tipoBanda,
  646.                     datiTransazione, groupByPolicy, filtro,
  647.                     state,
  648.                     requestInfo,
  649.                     protocolFactory);
  650.         }
  651.         else{
  652.             risultato = this.datiStatisticiReader.readOccupazioneBanda(key, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval, tipoBanda,
  653.                     datiTransazione, groupByPolicy, filtro,
  654.                     state,
  655.                     requestInfo,
  656.                     protocolFactory);
  657.         }
  658.         return risultato;
  659.     }
  660.    
  661.     private RisultatoStatistico readOccupazioneBandaInCache(String keyCache,
  662.             TipoRisorsa tipoRisorsa, TipoFinestra tipoFinestra,TipoPeriodoStatistico tipoPeriodo,
  663.             Date leftInterval, Date rightInterval,
  664.             TipoBanda tipoBanda,
  665.             DatiTransazione datiTransazione,IDUnivocoGroupByPolicy groupByPolicy, AttivazionePolicyFiltro filtro,
  666.             IState state,
  667.             RequestInfo requestInfo,
  668.             IProtocolFactory<?> protocolFactory) throws Exception{

  669.         RisultatoStatistico obj = null;
  670.         try{

  671.             if(keyCache == null)
  672.                 throw new Exception("KeyCache non definita");

  673.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  674.             if(cache!=null){
  675.                 org.openspcoop2.utils.cache.CacheResponse response =
  676.                     (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  677.                 if(response != null){
  678.                     if(response.getObject()!=null){
  679.                         this.log.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] valore["+response.getObject()+"] in cache.");
  680.                         //System.out.println("RITORNO OGGETTO IN CACHE CON CHIAVE ["+keyCache+"]: ["+response.getObject()+"]");
  681.                         return (RisultatoStatistico) response.getObject();
  682.                     }else if(response.getException()!=null){
  683.                         this.log.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] in cache.");
  684.                         throw (Exception) response.getException();
  685.                     }else{
  686.                         this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  687.                     }
  688.                 }
  689.             }
  690.            
  691.             String idTransazione = datiTransazione!=null ? datiTransazione.getIdTransazione() : null;
  692.             //synchronized (semaphoreOccupazioneBanda) {
  693.             SemaphoreLock lock = lockOccupazioneBanda.acquire("readOccupazioneBandaInCache", idTransazione);
  694.             try {
  695.                
  696.                 // se e' attiva una cache provo ad utilizzarla
  697.                 if(cache!=null){
  698.                     org.openspcoop2.utils.cache.CacheResponse response =
  699.                         (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  700.                     if(response != null){
  701.                         if(response.getObject()!=null){
  702.                             this.log.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] valore["+response.getObject()+"] in cache.");
  703.                             //System.out.println("RITORNO OGGETTO IN CACHE CON CHIAVE ["+keyCache+"]: ["+response.getObject()+"]");
  704.                             return (RisultatoStatistico) response.getObject();
  705.                         }else if(response.getException()!=null){
  706.                             this.log.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] in cache.");
  707.                             throw (Exception) response.getException();
  708.                         }else{
  709.                             this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  710.                         }
  711.                     }
  712.                 }
  713.    
  714.                 // Effettuo le query nella mia gerarchia di registri.
  715.                 this.log.debug("oggetto con chiave ["+keyCache+"] non in cache, effettuo ricerca...");
  716.                 try{
  717.                     obj = this.datiStatisticiReader.readOccupazioneBanda(keyCache, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval, tipoBanda,
  718.                             datiTransazione, groupByPolicy, filtro,
  719.                             state,
  720.                             requestInfo,
  721.                             protocolFactory);
  722.                 }catch(Exception e){
  723.                     throw e;
  724.                 }
  725.    
  726.                 // Aggiungo la risposta in cache (se esiste una cache)  
  727.                 // Se ho una eccezione aggiungo in cache solo una not found
  728.                 if( cache!=null ){  
  729.                     if(obj!=null){
  730.                         this.log.debug("Aggiungo oggetto con chiave ["+keyCache+"] valore["+obj+"] in cache");
  731.                     }else{
  732.                         throw new Exception("Ricerca ha ritornato un valore null");
  733.                     }
  734.                     try{    
  735.                         org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  736.                         responseCache.setObject((java.io.Serializable)obj);
  737.                         cache.put(keyCache,responseCache);
  738.                     }catch(UtilsException e){
  739.                         this.log.error("Errore durante l'inserimento in cache con chiave ["+keyCache+"] valore["+obj+"]: "+e.getMessage());
  740.                     }
  741.                 }
  742.                
  743.             }finally {
  744.                 lockOccupazioneBanda.release(lock, "readOccupazioneBandaInCache", idTransazione);
  745.             }

  746.         }
  747.         catch(Exception e){
  748.             this.log.error(e.getMessage(),e);
  749.             throw new Exception("OccupazioneBanda, Algoritmo di Cache fallito: "+e.getMessage(),e);
  750.         }

  751.         return obj;
  752.     }
  753.    
  754.    
  755.    
  756.    
  757.    
  758.    
  759.     /* ********************** LATENZA ************************** */
  760.    
  761.     public RisultatoStatistico readLatenza(TipoRisorsa tipoRisorsa,
  762.             Date leftInterval, Date rightInterval,
  763.             TipoFinestra tipoFinestra, TipoPeriodoStatistico tipoPeriodo,
  764.             TipoLatenza tipoLatenza,
  765.             DatiTransazione datiTransazione,IDUnivocoGroupByPolicy groupByPolicy, AttivazionePolicyFiltro filtro,
  766.             IState state,
  767.             RequestInfo requestInfo,
  768.             IProtocolFactory<?> protocolFactory) throws Exception{
  769.        
  770.         // BuildKey
  771.         SimpleDateFormat dateformat = DateUtils.getSimpleDateFormatMs();
  772.        
  773.         TipoPdD tipoPdDTransazioneInCorso = datiTransazione.getTipoPdD();
  774.        
  775.         StringBuilder bfKey = null;
  776.         bfKey = new StringBuilder(tipoRisorsa.getValue()+" ");
  777.         bfKey.append(tipoFinestra.getValue());
  778.         bfKey.append(" ").append(tipoPeriodo.getValue());
  779.         bfKey.append(" ").append(tipoLatenza.getValue());
  780.         bfKey.append(" ").append(tipoPdDTransazioneInCorso.getTipo());
  781.         bfKey.append(" [").append(dateformat.format(leftInterval)).append("]");
  782.         bfKey.append("-[").append(dateformat.format(rightInterval)).append("]");
  783.         bfKey.append(" GroupBy ");
  784.         bfKey.append(groupByPolicy.toString());
  785.         if(filtro!=null && filtro.isEnabled()) {
  786.             bfKey.append(" Filtro ");
  787.             bfKey.append(PolicyUtilities.toStringFilter(filtro));
  788.         }
  789.         String key = bfKey.toString();
  790.        
  791.         //System.out.println("CERCO OGGETTO CON CHIAVE ["+key+"]");
  792.        
  793.         RisultatoStatistico risultato = null;
  794.         if(GestoreCacheControlloTraffico.cache!=null){
  795.             risultato = this.readLatenzaInCache(key, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval,
  796.                     tipoLatenza, datiTransazione, groupByPolicy, filtro,
  797.                     state,
  798.                     requestInfo,
  799.                     protocolFactory);
  800.         }
  801.         else{
  802.             risultato = this.datiStatisticiReader.readLatenza(key, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval,
  803.                     tipoLatenza, datiTransazione, groupByPolicy, filtro,
  804.                     state,
  805.                     requestInfo,
  806.                     protocolFactory);
  807.         }
  808.         return risultato;
  809.     }
  810.    
  811.     private RisultatoStatistico readLatenzaInCache(String keyCache,
  812.             TipoRisorsa tipoRisorsa,TipoFinestra tipoFinestra,TipoPeriodoStatistico tipoPeriodo,
  813.             Date leftInterval, Date rightInterval,
  814.             TipoLatenza tipoLatenza,
  815.             DatiTransazione datiTransazione,IDUnivocoGroupByPolicy groupByPolicy, AttivazionePolicyFiltro filtro,
  816.             IState state,
  817.             RequestInfo requestInfo,
  818.             IProtocolFactory<?> protocolFactory) throws Exception{

  819.         RisultatoStatistico obj = null;
  820.         try{

  821.             if(keyCache == null)
  822.                 throw new Exception("KeyCache non definita");

  823.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  824.             if(cache!=null){
  825.                 org.openspcoop2.utils.cache.CacheResponse response =
  826.                     (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  827.                 if(response != null){
  828.                     if(response.getObject()!=null){
  829.                         this.log.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] valore["+response.getObject()+"] in cache.");
  830.                         //System.out.println("RITORNO OGGETTO IN CACHE CON CHIAVE ["+keyCache+"]: ["+response.getObject()+"]");
  831.                         return (RisultatoStatistico) response.getObject();
  832.                     }else if(response.getException()!=null){
  833.                         this.log.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] in cache.");
  834.                         throw (Exception) response.getException();
  835.                     }else{
  836.                         this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  837.                     }
  838.                 }
  839.             }
  840.            
  841.             String idTransazione = datiTransazione!=null ? datiTransazione.getIdTransazione() : null;
  842.             //synchronized (semaphoreLatenza) {
  843.             SemaphoreLock lock = lockLatenza.acquire("readLatenzaInCache", idTransazione);
  844.             try {
  845.                
  846.                 // se e' attiva una cache provo ad utilizzarla
  847.                 if(cache!=null){
  848.                     org.openspcoop2.utils.cache.CacheResponse response =
  849.                         (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  850.                     if(response != null){
  851.                         if(response.getObject()!=null){
  852.                             this.log.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] valore["+response.getObject()+"] in cache.");
  853.                             //System.out.println("RITORNO OGGETTO IN CACHE CON CHIAVE ["+keyCache+"]: ["+response.getObject()+"]");
  854.                             return (RisultatoStatistico) response.getObject();
  855.                         }else if(response.getException()!=null){
  856.                             this.log.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] in cache.");
  857.                             throw (Exception) response.getException();
  858.                         }else{
  859.                             this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  860.                         }
  861.                     }
  862.                 }
  863.    
  864.                 // Effettuo le query nella mia gerarchia di registri.
  865.                 this.log.debug("oggetto con chiave ["+keyCache+"] non in cache, effettuo ricerca...");
  866.                 try{
  867.                     obj = this.datiStatisticiReader.readLatenza(keyCache, tipoRisorsa, tipoFinestra, tipoPeriodo, leftInterval, rightInterval,
  868.                             tipoLatenza, datiTransazione, groupByPolicy, filtro,
  869.                             state,
  870.                             requestInfo,
  871.                             protocolFactory);
  872.                 }catch(Exception e){
  873.                     throw e;
  874.                 }
  875.    
  876.                 // Aggiungo la risposta in cache (se esiste una cache)  
  877.                 // Se ho una eccezione aggiungo in cache solo una not found
  878.                 if( cache!=null ){  
  879.                     if(obj!=null){
  880.                         this.log.debug("Aggiungo oggetto con chiave ["+keyCache+"] valore["+obj+"] in cache");
  881.                     }else{
  882.                         throw new Exception("Ricerca ha ritornato un valore null");
  883.                     }
  884.                     try{    
  885.                         org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  886.                         responseCache.setObject((java.io.Serializable)obj);
  887.                         cache.put(keyCache,responseCache);
  888.                     }catch(UtilsException e){
  889.                         this.log.error("Errore durante l'inserimento in cache con chiave ["+keyCache+"] valore["+obj+"]: "+e.getMessage());
  890.                     }
  891.                 }
  892.                
  893.             }finally {
  894.                 lockLatenza.release(lock, "readLatenzaInCache", idTransazione);
  895.             }

  896.         }
  897.         catch(Exception e){
  898.             this.log.error(e.getMessage(),e);
  899.             throw new Exception("Latenza, Algoritmo di Cache fallito: "+e.getMessage(),e);
  900.         }

  901.         return obj;
  902.     }
  903.    
  904.    
  905.    
  906.    
  907.    
  908.    
  909.    
  910.    
  911.    
  912.    
  913.    
  914.    
  915.    
  916.     /* ********************** STATO ************************** */
  917.    
  918.     public RisultatoStato getStato(DatiTransazione datiTransazione, IState state, String nomeAllarme) throws Exception{
  919.        
  920.         // BuildKey
  921.         StringBuilder bfKey = new StringBuilder("Stato ");
  922.         bfKey.append(nomeAllarme);
  923.         String key = bfKey.toString();
  924.        
  925.         //System.out.println("CERCO OGGETTO CON CHIAVE ["+key+"]");
  926.        
  927.         if(GestoreCacheControlloTraffico.cache!=null){
  928.             return this.getStatoInCache(key, datiTransazione, state, nomeAllarme);
  929.         }
  930.         else{
  931.             return this.datiNotifierReader.getStato(this.log, datiTransazione, state, nomeAllarme);
  932.         }
  933.     }
  934.    
  935.     private RisultatoStato getStatoInCache(String keyCache,DatiTransazione datiTransazione, IState state,
  936.             String nomeAllarme) throws Exception{

  937.         RisultatoStato obj = null;
  938.         try{

  939.             if(keyCache == null)
  940.                 throw new Exception("KeyCache non definita");

  941.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  942.             if(cache!=null){
  943.                 org.openspcoop2.utils.cache.CacheResponse response =
  944.                     (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  945.                 if(response != null){
  946.                     if(response.getObject()!=null){
  947.                         this.log.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] valore["+response.getObject()+"] in cache.");
  948.                         //System.out.println("RITORNO OGGETTO IN CACHE CON CHIAVE ["+keyCache+"]: ["+response.getObject()+"]");
  949.                         return (RisultatoStato) response.getObject();
  950.                     }else if(response.getException()!=null){
  951.                         this.log.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] in cache.");
  952.                         throw (Exception) response.getException();
  953.                     }else{
  954.                         this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  955.                     }
  956.                 }
  957.             }
  958.            
  959.             String idTransazione = datiTransazione!=null ? datiTransazione.getIdTransazione() : null;
  960.             //synchronized (semaphoreStato) {
  961.             SemaphoreLock lock = lockStato.acquire("getStatoInCache", idTransazione);
  962.             try {
  963.                
  964.                 // se e' attiva una cache provo ad utilizzarla
  965.                 if(cache!=null){
  966.                     org.openspcoop2.utils.cache.CacheResponse response =
  967.                         (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  968.                     if(response != null){
  969.                         if(response.getObject()!=null){
  970.                             this.log.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] valore["+response.getObject()+"] in cache.");
  971.                             //System.out.println("RITORNO OGGETTO IN CACHE CON CHIAVE ["+keyCache+"]: ["+response.getObject()+"]");
  972.                             return (RisultatoStato) response.getObject();
  973.                         }else if(response.getException()!=null){
  974.                             this.log.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] in cache.");
  975.                             throw (Exception) response.getException();
  976.                         }else{
  977.                             this.log.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  978.                         }
  979.                     }
  980.                 }
  981.    
  982.                 // Effettuo le query nella mia gerarchia di registri.
  983.                 this.log.debug("oggetto con chiave ["+keyCache+"] non in cache, effettuo ricerca...");
  984.                 try{
  985.                     obj = this.datiNotifierReader.getStato(this.log, datiTransazione, state, nomeAllarme);
  986.                 }catch(Exception e){
  987.                     throw e;
  988.                 }
  989.    
  990.                 // Aggiungo la risposta in cache (se esiste una cache)  
  991.                 // Se ho una eccezione aggiungo in cache solo una not found
  992.                 if( cache!=null ){  
  993.                     if(obj!=null){
  994.                         this.log.debug("Aggiungo oggetto con chiave ["+keyCache+"] valore["+obj+"] in cache");
  995.                     }else{
  996.                         throw new Exception("Ricerca ha ritornato un valore null");
  997.                     }
  998.                     try{    
  999.                         org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1000.                         responseCache.setObject((java.io.Serializable)obj);
  1001.                         cache.put(keyCache,responseCache);
  1002.                     }catch(UtilsException e){
  1003.                         this.log.error("Errore durante l'inserimento in cache con chiave ["+keyCache+"] valore["+obj+"]: "+e.getMessage());
  1004.                     }
  1005.                 }
  1006.                
  1007.             }finally {
  1008.                 lockStato.release(lock, "getStatoInCache", idTransazione);
  1009.             }

  1010.         }
  1011.         catch(Exception e){
  1012.             this.log.error(e.getMessage(),e);
  1013.             throw new Exception("Stato, Algoritmo di Cache fallito: "+e.getMessage(),e);
  1014.         }

  1015.         return obj;
  1016.     }
  1017. }