TimerGestoreChiaviPDNDLib.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.timers.pdnd;


  21. import java.sql.Connection;
  22. import java.util.Date;

  23. import org.openspcoop2.core.config.driver.DriverConfigurazioneException;
  24. import org.openspcoop2.core.config.driver.db.DriverConfigurazioneDB;
  25. import org.openspcoop2.core.eventi.Evento;
  26. import org.openspcoop2.core.eventi.constants.TipoSeverita;
  27. import org.openspcoop2.core.eventi.utils.SeveritaConverter;
  28. import org.openspcoop2.pdd.config.ConfigurazionePdDReader;
  29. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  30. import org.openspcoop2.pdd.core.CostantiPdD;
  31. import org.openspcoop2.pdd.core.GestoreMessaggi;
  32. import org.openspcoop2.pdd.core.eventi.GestoreEventi;
  33. import org.openspcoop2.pdd.core.keystore.KeystoreException;
  34. import org.openspcoop2.pdd.core.keystore.RemoteStore;
  35. import org.openspcoop2.pdd.core.keystore.RemoteStoreProviderDriverUtils;
  36. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  37. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  38. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  39. import org.openspcoop2.pdd.timers.TimerException;
  40. import org.openspcoop2.pdd.timers.TimerLock;
  41. import org.openspcoop2.pdd.timers.TimerLockNotAvailableException;
  42. import org.openspcoop2.pdd.timers.TimerMonitoraggioRisorseThread;
  43. import org.openspcoop2.pdd.timers.TimerState;
  44. import org.openspcoop2.pdd.timers.TipoLock;
  45. import org.openspcoop2.utils.TipiDatabase;
  46. import org.openspcoop2.utils.Utilities;
  47. import org.openspcoop2.utils.UtilsException;
  48. import org.openspcoop2.utils.certificate.remote.RemoteStoreConfig;
  49. import org.openspcoop2.utils.date.DateManager;
  50. import org.openspcoop2.utils.id.serial.InfoStatistics;
  51. import org.openspcoop2.utils.semaphore.Semaphore;
  52. import org.openspcoop2.utils.semaphore.SemaphoreConfiguration;
  53. import org.openspcoop2.utils.semaphore.SemaphoreMapping;
  54. import org.slf4j.Logger;


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

  63.     private static TimerState state = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  64.     public static TimerState getState() {
  65.         return state;
  66.     }
  67.     public static void setState(TimerState stateParam) {
  68.         state = stateParam;
  69.     }
  70.    
  71.     private OpenSPCoop2Properties op2Properties;
  72.     private String tipoDatabase = null;
  73.    
  74.     private Logger logCore = null;
  75.     private Logger logTimer = null;
  76.     private MsgDiagnostico msgDiag = null;
  77.    
  78.     private void logCoreInfo(String msg) {
  79.         if(this.logCore!=null) {
  80.             this.logCore.info(msg);
  81.         }
  82.     }
  83.     private void logCoreError(String msgErrore, Throwable e) {
  84.         if(this.logCore!=null) {
  85.             this.logCore.error(msgErrore,e);
  86.         }
  87.     }
  88.    
  89.     private void logTimerError(String msgErrore, Throwable e) {
  90.         if(this.logTimer!=null) {
  91.             this.logTimer.error(msgErrore,e);
  92.         }
  93.     }
  94.     private void logTimerError(String msgErrore) {
  95.         if(this.logTimer!=null) {
  96.             this.logTimer.error(msgErrore);
  97.         }
  98.     }
  99.     private void logTimerInfo(String msg) {
  100.         if(this.logTimer!=null) {
  101.             this.logTimer.info(msg);
  102.         }
  103.     }
  104.     private void logTimerInfo(String msg, Exception e) {
  105.         if(this.logTimer!=null) {
  106.             this.logTimer.info(msg, e);
  107.         }
  108.     }
  109.    
  110.     private RemoteStoreConfig remoteStore;
  111.     private String urlCheckEventi;
  112.    
  113.     private String parameterLastEventId;
  114.     private String parameterLimit;
  115.     private int limit;
  116.    
  117.     private int timeoutSeconds = -1;

  118.     /** Timer */
  119.     private TimerLock timerLock = null;

  120.     /** Semaforo */
  121.     private Semaphore semaphore = null;
  122.     private InfoStatistics semaphoreStatistics;
  123.    
  124.     /** Costruttore */
  125.     public TimerGestoreChiaviPDNDLib(Logger logTimer, MsgDiagnostico msgDiag, RemoteStoreConfig remoteStore,
  126.             String urlCheckEventi, int timeoutSeconds) throws TimerException{
  127.        
  128.         this.op2Properties = OpenSPCoop2Properties.getInstance();
  129.         this.tipoDatabase = this.op2Properties.getDatabaseType();
  130.         if(this.tipoDatabase==null){
  131.             throw new TimerException("Tipo Database non definito");
  132.         }
  133.        
  134.         boolean debug = this.op2Properties.isGestoreChiaviPDNDDebug();
  135.        
  136.         this.logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopGestoreChiaviPDND(debug);
  137.         this.logTimer = logTimer;
  138.         this.msgDiag = msgDiag;
  139.        
  140.         this.remoteStore = remoteStore;
  141.         this.urlCheckEventi = urlCheckEventi;
  142.        
  143.         this.timeoutSeconds = timeoutSeconds;
  144.        
  145.         try {
  146.             this.parameterLastEventId = this.op2Properties.getGestoreChiaviPDNDeventsKeysParameterLastEventId();
  147.             this.parameterLimit = this.op2Properties.getGestoreChiaviPDNDeventsKeysParameterLimit();
  148.             this.limit = this.op2Properties.getGestoreChiaviPDNDeventsKeysLimit();
  149.         }catch(Exception e) {
  150.             throw new TimerException(e.getMessage(),e);
  151.         }
  152.        
  153.         this.timerLock = new TimerLock(TipoLock.GESTORE_CHIAVI_PDND);
  154.        
  155.         if(this.op2Properties.isTimerLockByDatabase()) {
  156.             this.semaphoreStatistics = new InfoStatistics();

  157.             SemaphoreConfiguration config = GestoreMessaggi.newSemaphoreConfiguration(this.op2Properties.getGestoreChiaviPDNDTimerLockMaxLife(),
  158.                     this.op2Properties.getGestoreChiaviPDNDTimerLockIdleTime());

  159.             TipiDatabase databaseType = TipiDatabase.toEnumConstant(this.tipoDatabase);
  160.             try {
  161.                 this.semaphore = new Semaphore(this.semaphoreStatistics, SemaphoreMapping.newInstance(this.timerLock.getIdLock()),
  162.                         config, databaseType, this.logTimer);
  163.             }catch(Exception e) {
  164.                 throw new TimerException(e.getMessage(),e);
  165.             }
  166.         }
  167.     }
  168.    
  169.     public void check() throws TimerException {
  170.        
  171.         // Controllo che il sistema non sia andando in shutdown
  172.         if(OpenSPCoop2Startup.contextDestroyed){
  173.             this.logTimerError("["+TimerGestoreChiaviPDND.ID_MODULO+"] Rilevato sistema in shutdown");
  174.             return;
  175.         }

  176.         // Controllo che l'inizializzazione corretta delle risorse sia effettuata
  177.         if(!OpenSPCoop2Startup.initialize){
  178.             this.msgDiag.logFatalError("inizializzazione di OpenSPCoop non effettuata", "Check Inizializzazione");
  179.             String msgErrore = "Riscontrato errore: inizializzazione del Timer o di OpenSPCoop non effettuata";
  180.             this.logTimerError(msgErrore);
  181.             throw new TimerException(msgErrore);
  182.         }

  183.         // Controllo risorse di sistema disponibili
  184.         if( !TimerMonitoraggioRisorseThread.isRisorseDisponibili()){
  185.             this.logTimerError("["+TimerGestoreChiaviPDND.ID_MODULO+"] Risorse di sistema non disponibili: "+TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile().getMessage(),TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile());
  186.             return;
  187.         }
  188.         if( !MsgDiagnostico.gestoreDiagnosticaDisponibile){
  189.             this.logTimerError("["+TimerGestoreChiaviPDND.ID_MODULO+"] Sistema di diagnostica non disponibile: "+MsgDiagnostico.motivoMalfunzionamentoDiagnostici.getMessage(),MsgDiagnostico.motivoMalfunzionamentoDiagnostici);
  190.             return;
  191.         }
  192.        
  193.         boolean enabled = TimerState.ENABLED.equals(TimerGestoreChiaviPDNDLib.state);
  194.         if(!enabled) {
  195.             this.msgDiag.addKeyword(CostantiPdD.KEY_REMOTE_STORE, "-");
  196.             emitDiagnosticLog("disabilitato");
  197.             return;
  198.         }
  199.        
  200.         emitDiagnosticLog("letturaEventi");

  201.         long startControlloTimer = DateManager.getTimeMillis();
  202.            
  203.         DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection = null;
  204.         try{
  205.             Object oConfig = ConfigurazionePdDReader.getDriverConfigurazionePdD();
  206.             if(oConfig instanceof DriverConfigurazioneDB) {
  207.                 driverConfigurazioneDbGestoreConnection = (DriverConfigurazioneDB) oConfig;
  208.             }
  209.             else {
  210.                 throw new TimerException("Gestore utilizzabile solamente con una configurazione su database");
  211.             }
  212.         }
  213.         catch (Exception e) {
  214.             this.msgDiag.logErroreGenerico(e,TimerGestoreChiaviPDND.ID_MODULO);
  215.             this.logTimerError("Riscontrato errore durante la gestione eventi per le chiavi della PDND: "+ e.getMessage(),e);
  216.             return;
  217.         }
  218.        
  219.         try{

  220.             String causa = "Gestione chiavi PDND";
  221.             try {
  222.                
  223.                 acquireLock(driverConfigurazioneDbGestoreConnection, causa);
  224.                
  225.                 process(driverConfigurazioneDbGestoreConnection);
  226.                
  227.             }finally{
  228.                 releaseSafeLock(driverConfigurazioneDbGestoreConnection, causa);
  229.             }
  230.            
  231.             // end
  232.             long endControlloTimer = DateManager.getTimeMillis();
  233.             long diff = (endControlloTimer-startControlloTimer);
  234.             this.logTimerInfo("Gestione eventi per le chiavi della PDND terminata in "+Utilities.convertSystemTimeIntoStringMillisecondi(diff, true));
  235.            
  236.            
  237.         }
  238.         catch(TimerLockNotAvailableException t) {
  239.             // msg diagnostico emesso durante l'emissione dell'eccezione
  240.             this.logTimerInfo(t.getMessage(),t);
  241.         }
  242.         catch (Exception e) {
  243.             this.msgDiag.logErroreGenerico(e,TimerGestoreChiaviPDND.ID_MODULO);
  244.             this.logTimerError("Riscontrato errore durante la gestione eventi per le chiavi della PDND: "+ e.getMessage(),e);
  245.         }
  246.            
  247.     }

  248.     private void acquireLock(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection, String causa) throws DriverConfigurazioneException, TimerException, UtilsException, TimerLockNotAvailableException {
  249.         Connection conConfigurazione = null;
  250.         String method = TimerGestoreChiaviPDND.ID_MODULO+".acquireLock";
  251.         try{

  252.             conConfigurazione = driverConfigurazioneDbGestoreConnection.getConnection(method);
  253.             if(conConfigurazione == null) {
  254.                 throw new TimerException(TimerGestoreChiaviPDND.CONNESSIONE_NON_DISPONIBILE);  
  255.             }
  256.            
  257.             GestoreMessaggi.acquireLock(
  258.                     this.semaphore, conConfigurazione, this.timerLock,
  259.                     this.msgDiag, causa,
  260.                     this.op2Properties.getGestoreChiaviPDNDTimerLockAttesaAttiva(),
  261.                     this.op2Properties.getGestoreChiaviPDNDTimerLockCheckInterval());
  262.         }
  263.         finally{
  264.             try{
  265.                 if(conConfigurazione!=null)
  266.                     driverConfigurazioneDbGestoreConnection.releaseConnection(method, conConfigurazione);
  267.             }catch(Exception eClose){
  268.                 // ignore
  269.             }
  270.         }
  271.     }
  272.     private void releaseSafeLock(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection, String causa)  {
  273.         Connection conConfigurazione = null;
  274.         String method = TimerGestoreChiaviPDND.ID_MODULO+".releaseSafeLock";
  275.         try{

  276.             conConfigurazione = driverConfigurazioneDbGestoreConnection.getConnection(method);
  277.             if(conConfigurazione == null) {
  278.                 throw new TimerException(TimerGestoreChiaviPDND.CONNESSIONE_NON_DISPONIBILE);  
  279.             }
  280.            
  281.             GestoreMessaggi.releaseSafeLock(
  282.                     this.semaphore, conConfigurazione, this.timerLock,
  283.                     this.msgDiag, causa);
  284.            
  285.         }
  286.         catch(Exception e) {
  287.             this.msgDiag.logErroreGenerico(e,TimerGestoreChiaviPDND.ID_MODULO);
  288.         }
  289.         finally{
  290.             try{
  291.                 if(conConfigurazione!=null)
  292.                     driverConfigurazioneDbGestoreConnection.releaseConnection(method, conConfigurazione);
  293.             }catch(Exception eClose){
  294.                 // ignore
  295.             }
  296.         }
  297.     }
  298.    
  299.    
  300.     private long lastEventId = 0;
  301.        
  302.     private void process(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection) throws KeystoreException {
  303.        
  304.         // Recupero id del Remote Store
  305.         boolean created = readRemoteStoreDbImage(driverConfigurazioneDbGestoreConnection);
  306.        
  307.         TimerGestoreChiaviPDNDUtilities pdndUtilities = new TimerGestoreChiaviPDNDUtilities(this.remoteStore, this.urlCheckEventi, this.parameterLastEventId, this.parameterLimit, this.limit);
  308.        
  309.         this.msgDiag.addKeyword(CostantiPdD.KEY_LIMIT, this.limit+"");
  310.        
  311.         boolean updateLasteEventId = false;
  312.        
  313.         if(created || this.remoteStoreDbImage.getLastEvent()==null) {
  314.             // Initialize
  315.             updateLasteEventId = initialize(driverConfigurazioneDbGestoreConnection, pdndUtilities);
  316.         }
  317.         else {
  318.             // Verifico ultima data di aggiornamento
  319.            
  320.             long now = DateManager.getTimeMillis();
  321.             int msTimeout = this.timeoutSeconds * 1000;
  322.             Date check = new Date(now-msTimeout);
  323.             if(check.before(this.remoteStoreDbImage.getDataAggiornamento())) {
  324.                 emitDiagnosticLog("letturaEventi.nonNecessaria");
  325.                 return;
  326.             }
  327.            
  328.             // leggo lastEventId
  329.             long lastEventIdDbImage = Long.parseLong(this.remoteStoreDbImage.getLastEvent());
  330.             this.lastEventId = lastEventIdDbImage;
  331.            
  332.             int letti = 1;
  333.             long prec = 0;
  334.             while(letti > 0) {
  335.                 prec = this.lastEventId;
  336.                 letti = gestione(driverConfigurazioneDbGestoreConnection, pdndUtilities, true);
  337.                 if(this.lastEventId<=prec) {
  338.                     // l'ultima gestione non ha aggiornato lastEventId
  339.                     break;
  340.                 }
  341.             }
  342.            
  343.             if(this.lastEventId>lastEventIdDbImage) {
  344.                 updateLasteEventId = true;
  345.             }

  346.         }
  347.                
  348.         // aggiorno lastEventId sul database
  349.         if(updateLasteEventId) {
  350.             updateRemoteStore(driverConfigurazioneDbGestoreConnection,  this.remoteStoreDbImage.getId(), this.lastEventId+"");
  351.         }
  352.        
  353.     }
  354.     private boolean initialize(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection, TimerGestoreChiaviPDNDUtilities pdndUtilities) {
  355.        
  356.         boolean updateLasteEventId = false;
  357.        
  358.         emitDiagnosticLog("inizializzazione.inCorso");
  359.         try {
  360.             int letti = 1;
  361.             long prec = 0;
  362.             while(letti > 0) {
  363.                 prec = this.lastEventId;
  364.                 letti = gestione(driverConfigurazioneDbGestoreConnection, pdndUtilities, false);
  365.                 if(this.lastEventId<=prec) {
  366.                     // l'ultima gestione non ha aggiornato lastEventId
  367.                     break;
  368.                 }
  369.             }
  370.            
  371.             if(letti==-1) {
  372.                 throw new TimerException("Recupero eventi dalla PDND non riuscito");
  373.             }
  374.                            
  375.             this.msgDiag.addKeyword(CostantiPdD.KEY_OFFSET, this.lastEventId+"");
  376.             emitDiagnosticLog("inizializzazione.effettuata");
  377.            
  378.             updateLasteEventId = true;
  379.            
  380.         }catch(Exception e) {
  381.             this.msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, e.getMessage());
  382.             emitDiagnosticLog("inizializzazione.fallita");
  383.         }
  384.        
  385.         return updateLasteEventId;
  386.     }
  387.    
  388.     private RemoteStore remoteStoreDbImage = null;
  389.     private boolean readRemoteStoreDbImage(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection) throws KeystoreException {
  390.         Connection conConfigurazione = null;
  391.         String method = TimerGestoreChiaviPDND.ID_MODULO+".readRemoteStoreDbImage";
  392.         try{

  393.             conConfigurazione = driverConfigurazioneDbGestoreConnection.getConnection(method);
  394.             if(conConfigurazione == null) {
  395.                 throw new TimerException(TimerGestoreChiaviPDND.CONNESSIONE_NON_DISPONIBILE);  
  396.             }
  397.            
  398.             return readRemoteStoreDbImage(conConfigurazione);
  399.         }
  400.         catch (Exception e) {
  401.             throw new KeystoreException("readRemoteStoreDbImage failed: "+e.getMessage());
  402.         }finally{
  403.             try{
  404.                 if(conConfigurazione!=null)
  405.                     driverConfigurazioneDbGestoreConnection.releaseConnection(method, conConfigurazione);
  406.             }catch(Exception eClose){
  407.                 // ignore
  408.             }
  409.         }
  410.     }
  411.     private boolean readRemoteStoreDbImage(Connection conConfigurazione) throws KeystoreException {
  412.         this.remoteStoreDbImage = RemoteStoreProviderDriverUtils.getRemoteStore(conConfigurazione, this.tipoDatabase, this.remoteStore, false);
  413.         boolean created = false;
  414.         if(this.remoteStoreDbImage==null) {
  415.             // lo creo
  416.             try {
  417.                 RemoteStoreProviderDriverUtils.createRemoteStore(conConfigurazione, this.tipoDatabase, this.remoteStore);
  418.                 created = true;
  419.             }catch(KeystoreException e) {
  420.                 // un errore potrebbe essere dovuto ad un altro thread su un altro nodo che ha creato l'entry
  421.                 // provo a recuperare l'id prima di lanciare l'eccezione
  422.                 this.remoteStoreDbImage = RemoteStoreProviderDriverUtils.getRemoteStore(conConfigurazione, this.tipoDatabase, this.remoteStore, false);
  423.                 if(this.remoteStoreDbImage==null) {
  424.                     throw e;
  425.                 }
  426.             }
  427.            
  428.             if(this.remoteStoreDbImage==null) {
  429.                 this.remoteStoreDbImage = RemoteStoreProviderDriverUtils.getRemoteStore(conConfigurazione, this.tipoDatabase, this.remoteStore, true); // ora dovrebbe esistere
  430.             }
  431.         }
  432.         return created;
  433.     }
  434.    
  435.     private String getEventPrefix(TimerGestoreChiaviPDNDEvent event) {
  436.         return "Evento '"+event.getEventId()+"' ";
  437.     }
  438.    
  439.     private int gestione(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection, TimerGestoreChiaviPDNDUtilities pdndUtilities, boolean gestioneEvento) {
  440.         try {
  441.             long startGenerazione = DateManager.getTimeMillis();
  442.            
  443.             int letti = 0;
  444.            
  445.             this.msgDiag.addKeyword(CostantiPdD.KEY_OFFSET, this.lastEventId+"");
  446.             emitDiagnosticLog("gestioneEventi.inCorso");
  447.            
  448.             TimerGestoreChiaviPDNDEvents events = pdndUtilities.readNextEvents(this.lastEventId);
  449.             if(events==null || events.getEvents()==null || events.getEvents().isEmpty()) {
  450.                 letti = 0;
  451.             }
  452.             else {
  453.                 letti = events.getEvents().size();
  454.             }
  455.             this.msgDiag.addKeyword(CostantiPdD.KEY_NUMERO_EVENTI, letti+"");
  456.             emitDiagnosticLog("gestioneEventi.analisi");
  457.            
  458.             if(letti>0) {
  459.                 for (TimerGestoreChiaviPDNDEvent event : events.getEvents()) {                  
  460.                     if(event.getEventId()>this.lastEventId) {
  461.                         this.lastEventId = event.getEventId();
  462.                         if(gestioneEvento) {
  463.                             gestioneEvento(driverConfigurazioneDbGestoreConnection, event);
  464.                         }
  465.                     }
  466.                     else {
  467.                         emitLog(getEventPrefix(event)+"con un identificativo precedente o uguale all'ultimo evento gestito '"+this.lastEventId+"' (tipo di operazione: '"+event.getObjectType()+"'; tipo di evento: '"+event.getEventType()+"')");
  468.                     }
  469.                 }
  470.             }
  471.            
  472.             long endGenerazione = DateManager.getTimeMillis();
  473.             String tempoImpiegato = Utilities.convertSystemTimeIntoStringMillisecondi((endGenerazione-startGenerazione), true);
  474.             this.msgDiag.addKeyword(CostantiPdD.KEY_TEMPO_GESTIONE, tempoImpiegato);
  475.             emitDiagnosticLog("gestioneEventi.effettuata");
  476.            
  477.             return letti;
  478.            
  479.         }catch(Exception e) {
  480.             this.msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, e.getMessage());
  481.             emitDiagnosticLog("gestioneEventi.fallita");
  482.             return -1;
  483.         }
  484.     }
  485.    
  486.     private void gestioneEvento(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection, TimerGestoreChiaviPDNDEvent event) throws KeystoreException, TimerException {
  487.         if(TimerGestoreChiaviPDNDEvent.OBJECT_TYPE_KEY.equals(event.getObjectType()) &&
  488.             (
  489.                     TimerGestoreChiaviPDNDEvent.EVENT_TYPE_DELETED.equals(event.getEventType())
  490.                     ||
  491.                     TimerGestoreChiaviPDNDEvent.EVENT_TYPE_UPDATED.equals(event.getEventType())
  492.             )
  493.         ) {
  494.            
  495.             this.msgDiag.addKeyword(CostantiPdD.KEY_ID_EVENTO, event.getEventId()+"");
  496.             this.msgDiag.addKeyword(CostantiPdD.KEY_TIPO_EVENTO, event.getEventType());
  497.            
  498.             String kid = null;
  499.             if(event.getObjectId()!=null) {
  500.                 String details = event.getObjectId().toString();
  501.                 this.msgDiag.addKeyword(CostantiPdD.KEY_DETTAGLI_EVENTO, details);
  502.                
  503.                 kid = event.getObjectId().get("kid");
  504.             }
  505.             else {
  506.                 String details = "object id undefined";
  507.                 this.msgDiag.addKeyword(CostantiPdD.KEY_DETTAGLI_EVENTO, details);
  508.             }
  509.                        
  510.             if(kid!=null) {
  511.                 gestioneEvento(driverConfigurazioneDbGestoreConnection, event, kid);
  512.             }
  513.            
  514.             emitDiagnosticLog("gestioneEventi.evento");
  515.         }
  516.         else {
  517.             if(TimerGestoreChiaviPDNDEvent.OBJECT_TYPE_KEY.equals(event.getObjectType())){
  518.                 emitLog(getEventPrefix(event)+"relativo ad una chiave; tipo di evento '"+event.getEventType()+"' ignorato");
  519.             }
  520.             else {
  521.                 emitLog(getEventPrefix(event)+"relativo ad un tipo di operazione '"+event.getObjectType()+"' non gestita; (tipo di evento '"+event.getEventType()+"')");
  522.             }
  523.         }
  524.     }
  525.     private void gestioneEvento(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection, TimerGestoreChiaviPDNDEvent event, String kid) throws KeystoreException, TimerException {
  526.         Connection conConfigurazione = null;
  527.         String method = TimerGestoreChiaviPDND.ID_MODULO+".gestioneEvento_"+kid;
  528.         try{

  529.             conConfigurazione = driverConfigurazioneDbGestoreConnection.getConnection(method);
  530.             if(conConfigurazione == null) {
  531.                 throw new TimerException(TimerGestoreChiaviPDND.CONNESSIONE_NON_DISPONIBILE);  
  532.             }
  533.            
  534.             gestioneEvento(conConfigurazione, event, kid);
  535.         }
  536.         catch (Exception e) {
  537.             throw new KeystoreException("gestioneEvento failed: "+e.getMessage());
  538.         }finally{
  539.             try{
  540.                 if(conConfigurazione!=null)
  541.                     driverConfigurazioneDbGestoreConnection.releaseConnection(method, conConfigurazione);
  542.             }catch(Exception eClose){
  543.                 // ignore
  544.             }
  545.         }
  546.     }
  547.     private void gestioneEvento(Connection conConfigurazione, TimerGestoreChiaviPDNDEvent event, String kid) throws KeystoreException, TimerException {
  548.         Evento evento = null;
  549.         if(TimerGestoreChiaviPDNDEvent.EVENT_TYPE_DELETED.equals(event.getEventType())) {
  550.             int deleted = RemoteStoreProviderDriverUtils.deleteRemoteStoreKey(conConfigurazione, this.tipoDatabase, this.remoteStoreDbImage.getId(), kid);
  551.             if(deleted>0 && this.op2Properties.isGestoreChiaviPDNDEventiDelete()) {
  552.                 // significa che la chiave era stata registrata sulla base dati
  553.                 evento = buildEvento(event.getEventType(), kid, "La chiave è stata eliminata dal repository locale");
  554.             }
  555.         }
  556.         else {
  557.             int updated = RemoteStoreProviderDriverUtils.invalidRemoteStoreKey(conConfigurazione, this.tipoDatabase, this.remoteStoreDbImage.getId(), kid);
  558.             if(updated>0 && this.op2Properties.isGestoreChiaviPDNDEventiUpdate()) {
  559.                 // significa che la chiave era stata registrata sulla base dati
  560.                 evento = buildEvento(event.getEventType(), kid, "La chiave è stata invalidata sul repository locale");
  561.             }
  562.         }
  563.         if(evento!=null) {
  564.             try {
  565.                 GestoreEventi.getInstance().log(evento);
  566.             }catch(Exception e) {
  567.                 String msgError = "Registrazione evento per kid '"+kid+"' (eventType:"+event.getEventType()+") non riuscita: "+e.getMessage();
  568.                 this.logCoreError(msgError,e);
  569.                 this.logTimerError(msgError,e);
  570.             }
  571.         }
  572.     }
  573.    
  574.     private void updateRemoteStore(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection, long idStore, String lastEventId) throws KeystoreException {
  575.         Connection conConfigurazione = null;
  576.         String method = TimerGestoreChiaviPDND.ID_MODULO+".updateRemoteStore_"+idStore+"_"+lastEventId;
  577.         try{

  578.             conConfigurazione = driverConfigurazioneDbGestoreConnection.getConnection(method);
  579.             if(conConfigurazione == null) {
  580.                 throw new TimerException(TimerGestoreChiaviPDND.CONNESSIONE_NON_DISPONIBILE);  
  581.             }
  582.            
  583.             RemoteStoreProviderDriverUtils.updateRemoteStore(conConfigurazione, this.tipoDatabase, this.remoteStoreDbImage.getId(), this.lastEventId+"");
  584.         }
  585.         catch (Exception e) {
  586.             throw new KeystoreException("updateRemoteStore failed: "+e.getMessage());
  587.         }finally{
  588.             try{
  589.                 if(conConfigurazione!=null)
  590.                     driverConfigurazioneDbGestoreConnection.releaseConnection(method, conConfigurazione);
  591.             }catch(Exception eClose){
  592.                 // ignore
  593.             }
  594.         }
  595.     }
  596.    
  597.     private void emitDiagnosticLog(String code) {
  598.         this.msgDiag.logPersonalizzato(code);
  599.         String msg = this.msgDiag.getMessaggio_replaceKeywords(code);
  600.         emitLog(msg);
  601.     }
  602.     private void emitLog(String msg) {
  603.         this.logCoreInfo(msg);
  604.         this.logTimerInfo(msg);
  605.     }
  606.    
  607.     public static Evento buildEvento(String eventType, String objectDetail, String descrizione) throws TimerException{
  608.         Evento evento = new Evento();
  609.         evento.setTipo("GestioneChiaviPDND");
  610.         if(TimerGestoreChiaviPDNDEvent.EVENT_TYPE_ADDED.equals(eventType)) {
  611.             evento.setCodice(TIPO_EVENTO_ADD);
  612.         }
  613.         else if(TimerGestoreChiaviPDNDEvent.EVENT_TYPE_UPDATED.equals(eventType)) {
  614.             evento.setCodice(TIPO_EVENTO_UPDATED);
  615.         }
  616.         else if(TimerGestoreChiaviPDNDEvent.EVENT_TYPE_DELETED.equals(eventType)) {
  617.             evento.setCodice(TIPO_EVENTO_DELETED);
  618.         }
  619.         else {
  620.             evento.setCodice(eventType);
  621.         }
  622.         if(objectDetail!=null){
  623.             evento.setIdConfigurazione(objectDetail);
  624.         }      
  625.         evento.setDescrizione(descrizione);
  626.         evento.setOraRegistrazione(DateManager.getDate());
  627.         try {
  628.             evento.setSeverita(SeveritaConverter.toIntValue(TipoSeverita.INFO));
  629.         }catch(Exception e) {
  630.             throw new TimerException(e.getMessage(),e);
  631.         }
  632.         evento.setClusterId(OpenSPCoop2Properties.getInstance().getClusterId(false));
  633.         return evento;
  634.     }
  635.    
  636.     private static final String TIPO_EVENTO_ADD = "Add";
  637.     private static final String TIPO_EVENTO_DELETED = "Delete";
  638.     private static final String TIPO_EVENTO_UPDATED = "Update";
  639. }