TimerGestoreBusteNonRiscontrateImpl.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;

  21. import java.util.Date;

  22. import javax.ejb.CreateException;
  23. import javax.ejb.EJBException;
  24. import javax.ejb.SessionBean;
  25. import javax.ejb.SessionContext;
  26. import javax.ejb.TimedObject;
  27. import javax.ejb.Timer;
  28. import javax.ejb.TimerService;

  29. import org.slf4j.Logger;
  30. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  31. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  32. import org.openspcoop2.pdd.core.CostantiPdD;
  33. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  34. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  35. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  36. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  37. import org.openspcoop2.protocol.registry.RegistroServiziManager;
  38. import org.openspcoop2.utils.Semaphore;
  39. import org.openspcoop2.utils.SemaphoreLock;
  40. import org.openspcoop2.utils.Utilities;
  41. import org.openspcoop2.utils.date.DateManager;

  42. /**
  43.  * Implementazione dell'interfaccia {@link TimerGestoreBusteNonRiscontrate} del Gestore
  44.  * dei threads di servizio di OpenSPCoop.
  45.  *
  46.  *  
  47.  * @author Poli Andrea (apoli@link.it)
  48.  * @author Marcello Spadafora (ma.spadafora@finsiel.it)
  49.  * @author $Author$
  50.  * @version $Rev$, $Date$
  51.  */

  52. public class TimerGestoreBusteNonRiscontrateImpl implements SessionBean, TimedObject {

  53.      /**
  54.      * serialVersionUID
  55.      */
  56.     private static final long serialVersionUID = 1L;
  57.    
  58.     /* ******** F I E L D S P R I V A T I ******** */

  59.     /** Contesto */
  60.     private SessionContext sessionContext;
  61.     /** Timer associato a questo EJB */
  62.     private Timer timer;
  63.     /**
  64.      * Timeout dopo il quale un riscontro non ancora 'ringraziato' provoca la
  65.      * rispedizione della busta
  66.      */
  67.     private long timeout = 10;
  68.     /** Properties Reader */
  69.     private OpenSPCoop2Properties propertiesReader;
  70.     /** ConfigurazionePdDReader */
  71.     private ConfigurazionePdDManager configurazionePdDReader;
  72.     /** RegistroServiziReader */
  73.     private RegistroServiziManager registroServiziReader;
  74.     /** MsgDiagnostico */
  75.     private MsgDiagnostico msgDiag;
  76.     /** Logger */
  77.     private Logger logTimer;

  78.     /** Indicazione se l'istanza in questione e' autoDeployata da JBoss o creata da OpenSPCoop */
  79.     private boolean deployFromOpenSPCoop = false;
  80.     /** Indicazione se la gestione e' attualmente in esecuzione */
  81.     private boolean gestioneAttiva = false;
  82.     /** Indicazione se deve essere effettuato il log delle query */
  83.     private boolean logQuery = false;
  84.     /** Numero di messaggi prelevati sulla singola query */
  85.     private int limit = CostantiPdD.LIMIT_MESSAGGI_GESTORI;






  86.     /* ********  M E T O D I   ******** */

  87.     /**
  88.      * Viene chiamato in causa per istanziare il properties reader al primo
  89.      * utilizzo del thread che implementa l'EJBean definito in questa classe.
  90.      *
  91.      *
  92.      */
  93.     public void ejbCreate() throws CreateException {


  94.         // Aspetto inizializzazione di OpenSPCoop (aspetto mezzo minuto e poi segnalo errore)
  95.         int attesa = 90;
  96.         int secondi = 0;
  97.         while( (OpenSPCoop2Startup.initialize==false) && (secondi<attesa) ){
  98.             Utilities.sleep(1000);
  99.             secondi++;
  100.         }
  101.         if(secondi>= 90){
  102.             throw new CreateException("Riscontrata inizializzazione OpenSPCoop non effettuata");
  103.         }  

  104.         this.logTimer = OpenSPCoop2Logger.getLoggerOpenSPCoopTimers();
  105.        
  106.         try {
  107.             this.msgDiag = MsgDiagnostico.newInstance(TimerGestoreBusteNonRiscontrate.ID_MODULO);
  108.             this.msgDiag.setPrefixMsgPersonalizzati(MsgDiagnosticiProperties.MSG_DIAG_TIMER_GESTORE_RISCONTRI_RICEVUTE);
  109.             this.msgDiag.addKeyword(CostantiPdD.KEY_TIMER_GESTORE_RISCONTRI_RICEVUTE, TimerGestoreBusteNonRiscontrate.ID_MODULO);
  110.         } catch (Exception e) {
  111.             String msgErrore = "Riscontrato Errore durante l'inizializzazione del MsgDiagnostico: "+e.getMessage();
  112.             this.logTimer.error(msgErrore,e);
  113.             throw new CreateException(msgErrore);
  114.         }

  115.         try{
  116.             this.configurazionePdDReader = ConfigurazionePdDManager.getInstance();
  117.         }catch (Exception e) {
  118.             this.msgDiag.logErroreGenerico(e,"InizializzazioneReaderConfigurazione");
  119.             String msgErrore = "Riscontrato errore durante l'inizializzazione del Reader della Configurazione: "+e.getMessage();
  120.             this.logTimer.error(msgErrore,e);
  121.             throw new CreateException(msgErrore);
  122.         }
  123.         if( this.configurazionePdDReader.getTimeoutRiscontro() < 1  )   {
  124.             String msgErrore = "Riscontrato errore durante la lettura del timeout per le buste non riscontrate (<=0 ??)";
  125.             this.msgDiag.logErroreGenerico(msgErrore,"getTimeoutRiscontro()");
  126.             this.logTimer.error(msgErrore);
  127.             throw new CreateException(msgErrore);  
  128.         }

  129.         try{
  130.             this.registroServiziReader = RegistroServiziManager.getInstance();
  131.         }catch (Exception e) {
  132.             this.msgDiag.logErroreGenerico(e,"InizializzazioneReaderRegistroServizi");
  133.             String msgErrore = "Riscontrato Errore durante l'inizializzazione del Reader del registro dei Servizi: "+e.getMessage();
  134.             this.logTimer.error(msgErrore,e);
  135.             throw new CreateException(msgErrore);
  136.         }
  137.        
  138.         try {
  139.             this.timeout = this.configurazionePdDReader.getTimeoutRiscontro();
  140.             String minuti = "minuti";
  141.             if(this.timeout == 1)
  142.                 minuti = "minuto";
  143.             this.msgDiag.addKeyword(CostantiPdD.KEY_TIMEOUT, this.timeout+" "+minuti);
  144.             this.propertiesReader = OpenSPCoop2Properties.getInstance();
  145.         } catch (Exception e) {
  146.             this.msgDiag.logErroreGenerico(e,"InizializzazioneTimer");
  147.             String msgErrore = "Riscontrato errore durante la lettura dellea configurazione per il Thread GestoreBusteNonRiscontrate: "+e.getMessage();
  148.             this.logTimer.error(msgErrore,e);
  149.             throw new CreateException(msgErrore);
  150.         }
  151.        
  152.         this.logQuery = this.propertiesReader.isTimerGestoreRiscontriRicevuteAbilitatoLog();
  153.         this.limit = this.propertiesReader.getTimerGestoreRiscontriRicevuteLimit();
  154.         if(this.limit<=0){
  155.             this.limit = CostantiPdD.LIMIT_MESSAGGI_GESTORI;
  156.         }
  157.         this.msgDiag.addKeyword(CostantiPdD.KEY_LIMIT, this.limit+"");


  158.     }

  159.     /**
  160.      * Metodo necessario per l'implementazione dell'interfaccia
  161.      * <code>SessionBean</code>.
  162.      *
  163.      *
  164.      */
  165.     @Override
  166.     public void ejbRemove() throws EJBException {
  167.     }

  168.     /**
  169.      * Metodo necessario per l'implementazione dell'interfaccia
  170.      * <code>SessionBean</code>.
  171.      *
  172.      *
  173.      */
  174.     @Override
  175.     public void ejbActivate() throws EJBException {
  176.     }

  177.     /**
  178.      * Metodo necessario per l'implementazione dell'interfaccia
  179.      * <code>SessionBean</code>.
  180.      *
  181.      *
  182.      */
  183.     @Override
  184.     public void ejbPassivate() throws EJBException {
  185.     }

  186.     private static Semaphore SEMAPHORE = new Semaphore(TimerGestoreBusteNonRiscontrate.ID_MODULO);
  187.     private static Boolean LOCK = false;
  188.    
  189.     /**
  190.      * Metodo necessario per l'implementazione dell'interfaccia
  191.      * <code>TimedObject</code>.
  192.      *
  193.      *
  194.      */
  195.     @Override
  196.     public void ejbTimeout(Timer timer) throws EJBException {

  197.         // Nelle nuove versioni, jboss avviava automaticamente un EJB Timer registrato. Questo comportamento, insieme
  198.         // al codice che avviava manualmente il timer in versione thread provocava un doppio avvio.
  199.         if(this.propertiesReader.isServerJ2EE()==false){
  200.             //System.out.println("Riscontri STOPPED");
  201.             stop(timer);
  202.             return;
  203.         }
  204.        
  205.        
  206.         // Solo il thread avviato da OpenSPCoop deve essere eseguito
  207.         if( (this.deployFromOpenSPCoop == false)){
  208.             if(this.propertiesReader.isTimerAutoStart_StopTimer()){
  209.                 stop(timer);
  210.                 return;
  211.             }else{
  212.                 // Viene sempre richiamato ejbCreate() e quindi la variabile deployFromOpenSPCoop รจ sempre null.
  213.                 // La single instance viene gestiti quindi con un lock
  214.                 SemaphoreLock lock = SEMAPHORE.acquireThrowRuntime("ejbTimeout");
  215.                 try {
  216.                     if(LOCK){
  217.                         this.msgDiag.logPersonalizzato("precedenteEsecuzioneInCorso.stopTimer");
  218.                         this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("precedenteEsecuzioneInCorso.stopTimer"));
  219.                         stop(timer);
  220.                         return;
  221.                     }
  222.                     else{
  223.                         LOCK = true;
  224.                        
  225.                         /**
  226.                          * Aggiungo una sleep di 5 secondi per far provocare il LOCK sopra presente, per le altre istanze di timer
  227.                          * in modo da avere solamente una istanza in esecuzione
  228.                          */
  229.                         for (int i = 0; i < 10; i++) {
  230.                             Utilities.sleep(500);
  231.                         }
  232.                     }
  233.                 }finally {
  234.                     SEMAPHORE.release(lock, "ejbTimeout");
  235.                 }
  236.             }
  237.         }

  238.         try{
  239.                    
  240.             // Controllo se OpenSPCoop desidera avviare il Timer
  241.             if(this.propertiesReader.isTimerGestoreRiscontriRicevuteAbilitato()==false){
  242.                 this.msgDiag.logPersonalizzato("disabilitato");
  243.                 this.logTimer.warn(this.msgDiag.getMessaggio_replaceKeywords("disabilitato"));
  244.                 stop(timer);
  245.                 return;
  246.             }
  247.            
  248.             // Controllo che l'inizializzazione corretta delle risorse sia effettuata
  249.             if(timer == null){
  250.                 String msgErrore = "inizializzazione del Timer non effettuata";
  251.                 this.msgDiag.logFatalError(msgErrore, "Check inizializzazione");
  252.                 this.logTimer.error(msgErrore);
  253.                 stop(timer);
  254.                 return;
  255.             }
  256.             if(OpenSPCoop2Startup.initialize==false){
  257.                 String msgErrore = "inizializzazione di OpenSPCoop non effettuata";
  258.                 this.msgDiag.logFatalError(msgErrore, "Check inizializzazione");
  259.                 this.logTimer.error(msgErrore);
  260.                 stop(timer);
  261.                 return;
  262.             }
  263.    
  264.             if(this.gestioneAttiva){
  265.                 this.msgDiag.logPersonalizzato("precedenteEsecuzioneInCorso");
  266.                 this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("precedenteEsecuzioneInCorso"));
  267.                 return;
  268.             }
  269.            
  270.             try{
  271.                 // Prendo la gestione
  272.                 this.gestioneAttiva = true;
  273.                 TimerGestoreBusteNonRiscontrateLib gestoreMessaggiLib =
  274.                     new TimerGestoreBusteNonRiscontrateLib(this.msgDiag,this.logTimer,this.propertiesReader,this.logQuery,this.limit,
  275.                             this.timeout,this.configurazionePdDReader,this.registroServiziReader);
  276.                
  277.                 gestoreMessaggiLib.check();
  278.                
  279.             }catch(Exception e){
  280.                 this.msgDiag.logErroreGenerico(e,"GestoreRepositoryBusteTimerEJB");
  281.                 this.logTimer.error("Errore generale: "+e.getMessage(),e);
  282.             }finally{
  283.                 // Rilascio la gestione
  284.                 this.gestioneAttiva = false;
  285.             }          
  286.            
  287.         }finally{
  288.             SemaphoreLock lock = SEMAPHORE.acquireThrowRuntime("ejbTimeoutCheck2");
  289.             try {
  290.                 LOCK = false;
  291.             }finally {
  292.                 SEMAPHORE.release(lock, "ejbTimeoutCheck2");
  293.             }
  294.         }
  295.        
  296.     }

  297.     /**
  298.      * Imposta il Contesto del Session Bean. Metodo necessario per
  299.      * l'implementazione dell'interfaccia <code>SessionBean</code>.
  300.      *
  301.      * @param aContext
  302.      *            Contesto del Session Bean.
  303.      *
  304.      */
  305.     @Override
  306.     public void setSessionContext(SessionContext aContext) throws EJBException {
  307.         this.sessionContext = aContext;
  308.     }

  309.     /**
  310.      * Inizializza il Timer di gestione
  311.      *
  312.      *
  313.      */
  314.     public boolean start() throws EJBException {
  315.         if( this.timer != null ){

  316.             this.msgDiag.logPersonalizzato("timerGiaAvviato");
  317.             this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("timerGiaAvviato"));
  318.             return false;

  319.         } else {

  320.             if(this.propertiesReader.isTimerGestoreRiscontriRicevuteAbilitato()){
  321.            
  322.                 this.deployFromOpenSPCoop = true;  
  323.                 this.msgDiag.logPersonalizzato("avvioInCorso");
  324.                 this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("avvioInCorso"));
  325.                 Utilities.sleep(1000); // tempo necessario per un corretto avvio in JBoss 4.0.3...
  326.                 Date now = DateManager.getDate();
  327.                 long timeout = 60 * 1000 * this.timeout;
  328.                 try {
  329.                     // creo il timer
  330.                     TimerService ts = this.sessionContext.getTimerService();
  331.                     this.timer = ts.createTimer(now, timeout, TimerGestoreBusteNonRiscontrate.ID_MODULO);
  332.                     this.msgDiag.logPersonalizzato("avvioEffettuato");
  333.                     this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("avvioEffettuato"));
  334.                 } catch (Exception e) {
  335.                     stop();
  336.                     this.msgDiag.logFatalError(e, "Creazione timer EJB gestore delle buste non riscontrate");
  337.                     this.logTimer.error("Errore durante la creazione del timer: "+e.getMessage(),e);
  338.                 }
  339.                 return this.timer != null;
  340.                
  341.             }else{
  342.                
  343.                 this.msgDiag.logPersonalizzato("disabilitato");
  344.                 this.logTimer.warn(this.msgDiag.getMessaggio_replaceKeywords("disabilitato"));
  345.                 return false;
  346.                
  347.             }
  348.         }
  349.     }

  350.     /**
  351.      * Restituisce lo stato del timer di gestione
  352.      *
  353.      *
  354.      */
  355.     public boolean isStarted() throws EJBException {
  356.         return this.timer != null;
  357.     }

  358.     /**
  359.      * Annulla il timer di gestione
  360.      *
  361.      *
  362.      */
  363.     public void stop(Timer atimer) throws EJBException {
  364.         if (atimer != null) {
  365.             atimer.cancel();
  366.         }
  367.     }

  368.     /**
  369.      * Annulla il timer di gestione interno
  370.      *
  371.      *
  372.      */
  373.     public void stop() throws EJBException {
  374.         if (this.timer != null) {
  375.             this.timer.cancel();
  376.             this.timer = null;
  377.         }
  378.     }

  379. }