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

  21. import java.io.ByteArrayOutputStream;
  22. import java.security.SecureRandom;
  23. import java.sql.Connection;
  24. import java.sql.PreparedStatement;
  25. import java.sql.ResultSet;
  26. import java.sql.SQLException;
  27. import java.sql.Timestamp;
  28. import java.util.ArrayList;
  29. import java.util.Date;
  30. import java.util.HashMap;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.concurrent.ConcurrentHashMap;
  34. import java.util.concurrent.TimeUnit;

  35. import org.openspcoop2.core.commons.DBUtils;
  36. import org.openspcoop2.core.config.constants.CostantiConfigurazione;
  37. import org.openspcoop2.core.config.driver.DriverConfigurazioneException;
  38. import org.openspcoop2.core.constants.CostantiDB;
  39. import org.openspcoop2.core.id.IDSoggetto;
  40. import org.openspcoop2.message.OpenSPCoop2Message;
  41. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  42. import org.openspcoop2.message.OpenSPCoop2MessageParseResult;
  43. import org.openspcoop2.message.constants.MessageRole;
  44. import org.openspcoop2.message.constants.MessageType;
  45. import org.openspcoop2.message.utils.MessageUtilities;
  46. import org.openspcoop2.pdd.config.ClassNameProperties;
  47. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  48. import org.openspcoop2.pdd.core.state.IOpenSPCoopState;
  49. import org.openspcoop2.pdd.core.state.OpenSPCoopStateful;
  50. import org.openspcoop2.pdd.core.state.OpenSPCoopStateless;
  51. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  52. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  53. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  54. import org.openspcoop2.pdd.mdb.ConsegnaContenutiApplicativi;
  55. import org.openspcoop2.pdd.mdb.Imbustamento;
  56. import org.openspcoop2.pdd.mdb.ImbustamentoRisposte;
  57. import org.openspcoop2.pdd.mdb.InoltroBuste;
  58. import org.openspcoop2.pdd.mdb.InoltroRisposte;
  59. import org.openspcoop2.pdd.mdb.Sbustamento;
  60. import org.openspcoop2.pdd.mdb.SbustamentoRisposte;
  61. import org.openspcoop2.pdd.services.core.RicezioneBuste;
  62. import org.openspcoop2.pdd.services.core.RicezioneContenutiApplicativi;
  63. import org.openspcoop2.pdd.services.skeleton.IdentificativoIM;
  64. import org.openspcoop2.pdd.services.skeleton.MessaggioIM;
  65. import org.openspcoop2.pdd.timers.TimerConsegnaContenutiApplicativiThread;
  66. import org.openspcoop2.pdd.timers.TimerGestoreMessaggi;
  67. import org.openspcoop2.pdd.timers.TimerLock;
  68. import org.openspcoop2.pdd.timers.TimerLockNotAvailableException;
  69. import org.openspcoop2.pdd.timers.TipoLock;
  70. import org.openspcoop2.protocol.engine.Configurazione;
  71. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  72. import org.openspcoop2.protocol.engine.constants.Costanti;
  73. import org.openspcoop2.protocol.engine.driver.ProfiloDiCollaborazione;
  74. import org.openspcoop2.protocol.engine.driver.RepositoryBuste;
  75. import org.openspcoop2.protocol.engine.driver.Riscontri;
  76. import org.openspcoop2.protocol.engine.driver.RollbackRepositoryBuste;
  77. import org.openspcoop2.protocol.engine.driver.repository.IGestoreRepository;
  78. import org.openspcoop2.protocol.sdk.Busta;
  79. import org.openspcoop2.protocol.sdk.Context;
  80. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  81. import org.openspcoop2.protocol.sdk.ProtocolException;
  82. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  83. import org.openspcoop2.protocol.sdk.state.StateMessage;
  84. import org.openspcoop2.protocol.sdk.state.StatefulMessage;
  85. import org.openspcoop2.utils.LoggerWrapperFactory;
  86. import org.openspcoop2.utils.MapKey;
  87. import org.openspcoop2.utils.SortedMap;
  88. import org.openspcoop2.utils.TipiDatabase;
  89. import org.openspcoop2.utils.Utilities;
  90. import org.openspcoop2.utils.UtilsException;
  91. import org.openspcoop2.utils.cache.Cache;
  92. import org.openspcoop2.utils.cache.CacheAlgorithm;
  93. import org.openspcoop2.utils.cache.CacheType;
  94. import org.openspcoop2.utils.date.DateManager;
  95. import org.openspcoop2.utils.date.DateUtils;
  96. import org.openspcoop2.utils.date.DaylightSavingUtils;
  97. import org.openspcoop2.utils.date.TimeTransitionType;
  98. import org.openspcoop2.utils.id.serial.InfoStatistics;
  99. import org.openspcoop2.utils.io.Base64Utilities;
  100. import org.openspcoop2.utils.jdbc.IJDBCAdapter;
  101. import org.openspcoop2.utils.jdbc.JDBCAdapterFactory;
  102. import org.openspcoop2.utils.jdbc.JDBCUtilities;
  103. import org.openspcoop2.utils.resources.Loader;
  104. import org.openspcoop2.utils.semaphore.Semaphore;
  105. import org.openspcoop2.utils.semaphore.SemaphoreConfiguration;
  106. import org.openspcoop2.utils.semaphore.SemaphoreLogEventGenerator;
  107. import org.openspcoop2.utils.semaphore.SemaphoreMapping;
  108. import org.openspcoop2.utils.sql.ISQLQueryObject;
  109. import org.openspcoop2.utils.sql.SQLObjectFactory;
  110. import org.openspcoop2.utils.threads.RunnableLogger;
  111. import org.openspcoop2.utils.transport.TransportRequestContext;
  112. import org.slf4j.Logger;


  113. /**
  114.  * Classe utilizzata per la gestione dei messaggi in OpenSPCoop
  115.  *
  116.  * @author Poli Andrea (apoli@link.it)
  117.  * @author Tronci Fabio (tronci@link.it)
  118.  * @author $Author$
  119.  * @version $Rev$, $Date$
  120.  */


  121. public class GestoreMessaggi  {

  122.     /** Logger utilizzato per debug. */
  123.     private Logger log = null;

  124.     private IOpenSPCoopState openspcoopstate=null;
  125.     public IOpenSPCoopState getOpenspcoopstate() {
  126.         return this.openspcoopstate;
  127.     }
  128.     private boolean isRichiesta=false;
  129.     private boolean readyForDrop = false; // usato solo nello stateless, indica se il messaggio puo' essere cancellato dal db
  130.     private boolean portaDiTipoStateless = false;
  131.     /** Indicazione se siamo in modalita di routing stateless */
  132.     private boolean routingStateless;
  133.     private boolean oneWayVersione11 = false;




  134.     /* ********  F I E L D S    S T A T I C    P U B L I C  ******** */
  135.     /** Tabella che mantiene i messaggi da consegnare ai servizi applicativi*/
  136.     public static final String MESSAGGI  = "MESSAGGI";
  137.     /* Colonne dei Messaggi */
  138.     public static final String MESSAGGI_COLUMN_ID_MESSAGGIO  = "ID_MESSAGGIO";
  139.     public static final String MESSAGGI_COLUMN_TIPO_MESSAGGIO  = "TIPO";
  140.     public static final String MESSAGGI_COLUMN_RIFERIMENTO_MSG  = "RIFERIMENTO_MSG";
  141.     public static final String MESSAGGI_COLUMN_ORA_REGISTRAZIONE  = "ORA_REGISTRAZIONE";
  142.     public static final String MESSAGGI_COLUMN_PROPRIETARIO  = "PROPRIETARIO";
  143.     public static final String MESSAGGI_COLUMN_PROTOCOLLO  = "PROTOCOLLO";
  144.     public static final String MESSAGGI_COLUMN_ID_TRANSAZIONE  = "id_transazione";
  145.     public static final String MESSAGGI_COLUMN_CORRELAZIONE_APPLICATIVA_RICHIESTA  = "CORRELAZIONE_APPLICATIVA";
  146.     public static final String MESSAGGI_COLUMN_CORRELAZIONE_APPLICATIVA_RISPOSTA  = "CORRELAZIONE_RISPOSTA";

  147.     /** Tabella che mantiene i servizi applicativi che devono ancora ricevere un dato messaggio */
  148.     public static final String MSG_SERVIZI_APPLICATIVI  = "MSG_SERVIZI_APPLICATIVI";
  149.     /* Colonne dei Messaggi Servizi Applicativi */
  150.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_ID_MESSAGGIO  = "ID_MESSAGGIO";
  151.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_TIPO  = "TIPO";
  152.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_SERVIZIO_APPLICATIVO  = "SERVIZIO_APPLICATIVO";
  153.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_ORA_REGISTRAZIONE  = "ORA_REGISTRAZIONE";
  154.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_INTEGRATION_MANAGER  = "INTEGRATION_MANAGER";
  155.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_LOCK_CONSEGNA  = "LOCK_CONSEGNA";
  156.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_ATTESA_ESITO  = "ATTESA_ESITO";
  157.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_ERRORE_PROCESSAMENTO_COMPACT  = "ERRORE_PROCESSAMENTO_COMPACT";
  158.     public static final String MSG_SERVIZI_APPLICATIVI_COLUMN_TIPO_CONSEGNA  = "TIPO_CONSEGNA";

  159.     /** Tabella che definisce il contenuto di un messaggio */
  160.     public static final String DEFINIZIONE_MESSAGGI = "DEFINIZIONE_MESSAGGI";
  161.     /* Colonne della tabella contenente i bytes dei messaggi */
  162.     public static final String DEFINIZIONE_MESSAGGI_COLUMN_ID_MESSAGGIO = "ID_MESSAGGIO";
  163.     public static final String DEFINIZIONE_MESSAGGI_COLUMN_TIPO_MESSAGGIO = "TIPO";
  164.     public static final String DEFINIZIONE_MESSAGGI_COLUMN_ORA_REGISTRAZIONE  = "ORA_REGISTRAZIONE";

  165.     /** Tipo di consegna verso un servizio applicativo: tramite Connettore*/
  166.     public static final String CONSEGNA_TRAMITE_CONNETTORE  = "Connettore";
  167.     /** Tipo di consegna verso un servizio applicativo: tramite ConnectionReply*/
  168.     public static final String CONSEGNA_TRAMITE_CONNECTION_REPLY  = "ConnectionReply";
  169.     /** Tipo di consegna verso un servizio applicativo: solo tramite IntegrationManager*/
  170.     public static final String CONSEGNA_TRAMITE_INTEGRATION_MANAGER  = "IntegrationManager";

  171.    
  172.     private static java.util.Random _rnd = null;
  173.     private static synchronized void initRandom() {
  174.         if(_rnd==null) {
  175.             _rnd = new SecureRandom();
  176.         }
  177.     }
  178.     public static java.util.Random getRandom() {
  179.         if(_rnd==null) {
  180.             initRandom();
  181.         }
  182.         return _rnd;
  183.     }
  184.    
  185.    

  186.     /** MessaggioDiagnostico */
  187.     private MsgDiagnostico msgDiag;
  188.     /** Identificativo del Messaggio */
  189.     private String idBusta;




  190.     /** Indica la directory dove effettuare salvataggi */
  191.     private String workDir;
  192.     /** Indicazione se il messaggio sara' salvato nella INBOX dei messaggi, o nella OUTBOX */
  193.     private String tipo;
  194.     /** Properties reader */
  195.     private OpenSPCoop2Properties propertiesReader;


  196.     /** Chiave della cache per i Gestore Messaggi  */
  197.     private static final String GESTORE_MESSAGGI_CACHE_NAME = "gestoreMessaggi";
  198.     /** GestoreMessaggi Cache */
  199.     private static Cache cacheMappingGestoreMessaggi = null;

  200.     private static String cluster_id = null;

  201.     private PdDContext pddContext = null;
  202. //  public PdDContext getPddContext() { Non scommentare, c'è piu' in basso il metodo che legge dallo stato
  203. //      return this.pddContext;
  204. //  }
  205.     private IProtocolFactory<?> protocolFactory = null;
  206.     public IProtocolFactory<?> getProtocolFactory() {
  207.         return this.protocolFactory;
  208.     }
  209.    
  210.     /** ID Transazione */
  211.     private String idTransazione;

  212.     /* --------------- Cache --------------------*/
  213.     public static void resetCache() throws GestoreMessaggiException{
  214.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  215.             try{
  216.                 GestoreMessaggi.cacheMappingGestoreMessaggi.clear();
  217.             }catch(Exception e){
  218.                 throw new GestoreMessaggiException(e.getMessage(),e);
  219.             }
  220.         }
  221.     }
  222.     public static String printStatsCache(String separator) throws GestoreMessaggiException{
  223.         try{
  224.             if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  225.                 return GestoreMessaggi.cacheMappingGestoreMessaggi.printStats(separator);
  226.             }
  227.             else{
  228.                 throw new Exception("Cache non abilitata");
  229.             }
  230.         }catch(Exception e){
  231.             throw new GestoreMessaggiException("Visualizzazione Statistiche riguardante la cache dei messaggi gestiti non riuscita: "+e.getMessage(),e);
  232.         }
  233.     }
  234.     public static void abilitaCache() throws GestoreMessaggiException{
  235.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null)
  236.             throw new GestoreMessaggiException("Cache gia' abilitata");
  237.         else{
  238.             _abilitaCache();
  239.         }
  240.     }
  241.     private static synchronized void _abilitaCache() throws GestoreMessaggiException{
  242.         if(GestoreMessaggi.cacheMappingGestoreMessaggi==null) {
  243.             try{
  244.                 GestoreMessaggi.cacheMappingGestoreMessaggi = new Cache(CacheType.JCS, GestoreMessaggi.GESTORE_MESSAGGI_CACHE_NAME); // lascio JCS come default abilitato via jmx
  245.                 GestoreMessaggi.cacheMappingGestoreMessaggi.build();
  246.             }catch(Exception e){
  247.                 throw new GestoreMessaggiException(e.getMessage(),e);
  248.             }
  249.         }
  250.     }
  251.     public static void abilitaCache(long dimensioneCache,boolean algoritmoCacheLRU,long itemIdleTime,long itemLifeSecond) throws GestoreMessaggiException{
  252.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null)
  253.             throw new GestoreMessaggiException("Cache gia' abilitata");
  254.         else{
  255.             try{
  256.                 String algoritmoCache = null;
  257.                 if(algoritmoCacheLRU)
  258.                     algoritmoCache = CostantiConfigurazione.CACHE_LRU.toString() ;
  259.                 else
  260.                     algoritmoCache = CostantiConfigurazione.CACHE_MRU.toString();
  261.                 GestoreMessaggi.initCacheGestoreMessaggi(CacheType.JCS, (int)dimensioneCache,algoritmoCache,itemIdleTime,itemLifeSecond,null,null); // lascio JCS come default abilitato via jmx
  262.             }catch(Exception e){
  263.                 throw new GestoreMessaggiException(e.getMessage(),e);
  264.             }
  265.         }
  266.     }
  267.     public static void disabilitaCache() throws GestoreMessaggiException{
  268.         if(GestoreMessaggi.cacheMappingGestoreMessaggi==null)
  269.             throw new GestoreMessaggiException("Cache gia' disabilitata");
  270.         else{
  271.             _disabilitaCache();
  272.         }
  273.     }
  274.     private static synchronized void _disabilitaCache() throws GestoreMessaggiException{
  275.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null) {
  276.             try{
  277.                 GestoreMessaggi.cacheMappingGestoreMessaggi.clear();
  278.                 GestoreMessaggi.cacheMappingGestoreMessaggi = null;
  279.             }catch(Exception e){
  280.                 throw new GestoreMessaggiException(e.getMessage(),e);
  281.             }
  282.         }
  283.     }
  284.     public static boolean isCacheAbilitata(){
  285.         return GestoreMessaggi.cacheMappingGestoreMessaggi != null;
  286.     }
  287.     public static String listKeysCache(String separator) throws GestoreMessaggiException{
  288.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  289.             try{
  290.                 return GestoreMessaggi.cacheMappingGestoreMessaggi.printKeys(separator);
  291.             }catch(Exception e){
  292.                 throw new GestoreMessaggiException(e.getMessage(),e);
  293.             }
  294.         }else{
  295.             throw new GestoreMessaggiException("Cache non abilitata");
  296.         }
  297.     }
  298.     public static String getObjectCache(String key) throws GestoreMessaggiException{
  299.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  300.             try{
  301.                 Object o = GestoreMessaggi.cacheMappingGestoreMessaggi.get(key);
  302.                 if(o!=null){
  303.                     return o.toString();
  304.                 }else{
  305.                     return "oggetto con chiave ["+key+"] non presente";
  306.                 }
  307.             }catch(Exception e){
  308.                 throw new GestoreMessaggiException(e.getMessage(),e);
  309.             }
  310.         }else{
  311.             throw new GestoreMessaggiException("Cache non abilitata");
  312.         }
  313.     }
  314.     public static void removeObjectCache(String key) throws GestoreMessaggiException{
  315.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  316.             try{
  317.                 GestoreMessaggi.cacheMappingGestoreMessaggi.remove(key);
  318.             }catch(Exception e){
  319.                 throw new GestoreMessaggiException(e.getMessage(),e);
  320.             }
  321.         }else{
  322.             throw new GestoreMessaggiException("Cache non abilitata");
  323.         }
  324.     }



  325.     /** Inizializzazione della Cache, se abilitata */
  326.     public static void initialize() throws Exception{
  327.         OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  328.         if(properties.isAbilitataCacheGestoreMessaggi()){
  329.             Logger log = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  330.             Logger logConsole = OpenSPCoop2Logger.getLoggerOpenSPCoopConsole();
  331.             int dimensioneCache = properties.getDimensioneCacheGestoreMessaggi();
  332.             String algoritmoCache = properties.getAlgoritmoCacheGestoreMessaggi();
  333.             long itemIdleTime = properties.getItemIdleTimeCacheGestoreMessaggi();
  334.             long itemLifeSecond = properties.getItemLifeSecondCacheGestoreMessaggi();
  335.             CacheType cacheType = properties.getCacheTypeMessage();
  336.             GestoreMessaggi.initCacheGestoreMessaggi(cacheType, dimensioneCache,algoritmoCache,itemIdleTime,itemLifeSecond,log,logConsole);
  337.         }
  338.     }

  339.     public static void initCacheGestoreMessaggi(CacheType cacheType, int dimensioneCache,String algoritmoCache,long itemIdleTime,long itemLifeSecond,Logger log,Logger logConsole) throws Exception{

  340.         if(log!=null)
  341.             log.info("Inizializzazione cache gestoreMessaggi");
  342.         if(logConsole!=null)
  343.             logConsole.info("Inizializzazione cache gestoreMessaggi");

  344.         GestoreMessaggi.cacheMappingGestoreMessaggi = new Cache(cacheType, GestoreMessaggi.GESTORE_MESSAGGI_CACHE_NAME);

  345.         String msg = null;
  346.         if( (dimensioneCache>0) ||
  347.                 (algoritmoCache != null) ){

  348.             if( dimensioneCache>0 ){
  349.                 try{
  350.                     msg = "Dimensione della cache (Gestore Messaggi) impostata al valore: "+dimensioneCache;
  351.                     if(log!=null)
  352.                         log.info(msg);
  353.                     if(logConsole!=null)
  354.                         logConsole.info(msg);
  355.                     GestoreMessaggi.cacheMappingGestoreMessaggi.setCacheSize(dimensioneCache);
  356.                 }catch(Exception error){
  357.                     throw new DriverConfigurazioneException("Parametro errato per la dimensione della cache (Gestore Messaggi): "+error.getMessage());
  358.                 }
  359.             }
  360.             if(algoritmoCache != null ){
  361.                 msg = "Algoritmo di cache (Gestore Messaggi) impostato al valore: "+algoritmoCache;
  362.                 if(log!=null)
  363.                     log.info(msg);
  364.                 if(logConsole!=null)
  365.                     logConsole.info(msg);
  366.                 if(CostantiConfigurazione.CACHE_MRU.toString().equalsIgnoreCase(algoritmoCache))
  367.                     GestoreMessaggi.cacheMappingGestoreMessaggi.setCacheAlgoritm(CacheAlgorithm.MRU);
  368.                 else
  369.                     GestoreMessaggi.cacheMappingGestoreMessaggi.setCacheAlgoritm(CacheAlgorithm.LRU);
  370.             }

  371.         }

  372.         if( itemIdleTime > 0  ){
  373.             try{
  374.                 msg = "Attributo 'IdleTime' (Gestore Messaggi) impostato al valore: "+itemIdleTime;
  375.                 if(log!=null)
  376.                     log.info(msg);
  377.                 if(logConsole!=null)
  378.                     logConsole.info(msg);
  379.                 GestoreMessaggi.cacheMappingGestoreMessaggi.setItemIdleTime(itemIdleTime);
  380.             }catch(Exception error){
  381.                 throw new DriverConfigurazioneException("Parametro errato per l'attributo 'IdleTime' (Gestore Messaggi): "+error.getMessage());
  382.             }
  383.         }

  384.         try{
  385.             msg = "Attributo 'MaxLifeSecond' (Gestore Messaggi) impostato al valore: "+itemLifeSecond;
  386.             if(log!=null)
  387.                 log.info(msg);
  388.             if(logConsole!=null)
  389.                 logConsole.info(msg);
  390.             GestoreMessaggi.cacheMappingGestoreMessaggi.setItemLifeTime(itemLifeSecond);
  391.         }catch(Exception error){
  392.             throw new DriverConfigurazioneException("Parametro errato per l'attributo 'MaxLifeSecond' (Gestore Messaggi): "+error.getMessage());
  393.         }

  394.         GestoreMessaggi.cacheMappingGestoreMessaggi.build();
  395.     }
  396.    
  397.    
  398.     @SuppressWarnings("deprecation")
  399.     @Deprecated
  400.     public static void disableSyncronizedGet() throws UtilsException {
  401.         if(GestoreMessaggi.cacheMappingGestoreMessaggi==null) {
  402.             throw new UtilsException("Cache disabled");
  403.         }
  404.         GestoreMessaggi.cacheMappingGestoreMessaggi.disableSyncronizedGet();
  405.     }
  406.     @SuppressWarnings("deprecation")
  407.     @Deprecated
  408.     public static boolean isDisableSyncronizedGet() throws UtilsException {
  409.         if(GestoreMessaggi.cacheMappingGestoreMessaggi==null) {
  410.             throw new UtilsException("Cache disabled");
  411.         }
  412.         return GestoreMessaggi.cacheMappingGestoreMessaggi.isDisableSyncronizedGet();
  413.     }
  414.    



  415.     /** Elementi in cache
  416.      * @throws UtilsException */
  417.     public static String cacheToString() throws UtilsException{
  418.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  419.             StringBuilder bf = new StringBuilder();
  420.             bf.append("Cache GestoreMessaggi: "+GestoreMessaggi.cacheMappingGestoreMessaggi.printStats(" "));
  421.             return bf.toString();
  422.         }else
  423.             return "Cache non abilitata";
  424.     }

  425.     /** Registrazione Mapping rifMsg-id */
  426.     public static void addIntoCache_MappingRifMsgToId(MsgDiagnostico msgDiag, String tipoMessaggio,String riferimentoMessaggio, String idBusta) throws UtilsException{
  427.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  428.             String key = "mappingRifMsgToId_"+tipoMessaggio+"_"+riferimentoMessaggio;
  429.             GestoreMessaggi.cacheMappingGestoreMessaggi.put(key, idBusta);
  430.             /* PUT SAFE COSTOSO
  431.             try{
  432.                 GestoreMessaggi.cacheMappingGestoreMessaggi.putSafe(key, idBusta);
  433.             }catch(ObjectExistsException ex){
  434.                 //String oldValue = (String) GestoreMessaggi.cacheMappingGestoreMessaggi.get(key);
  435.                 //msgDiag.highDebug("RiferimentoMessaggio ["+tipoMessaggio+"]/["+riferimentoMessaggio+"] gia registrato, con il valore "+oldValue + " (nuovo valore:"+idBusta+")");
  436.                 msgDiag.highDebug("RiferimentoMessaggio ["+tipoMessaggio+"]/["+riferimentoMessaggio+"] gia registrato (nuovo valore:"+idBusta+")");
  437.                 GestoreMessaggi.cacheMappingGestoreMessaggi.remove(key);
  438.                 GestoreMessaggi.cacheMappingGestoreMessaggi.put(key, idBusta);
  439.             }
  440.              */
  441.             //System.out.println("AGGIORNO CACHE RIFERIMENTO RIF["+tipoMessaggio+"_"+riferimentoMessaggio+"] ID["+idBusta+"]");
  442.         }
  443.     }
  444.     /** Get RiferimentoMessaggio */
  445.     public static String getFromCache_idFromRifMsgMapping(String tipoMessaggio,String riferimentoMessaggio){
  446.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  447.             Object obj = GestoreMessaggi.cacheMappingGestoreMessaggi.get("mappingRifMsgToId_"+tipoMessaggio+"_"+riferimentoMessaggio);
  448.             // System.out.println("GET FROM CACHE RIFERIMENTO RIF["+tipoMessaggio+"_"+riferimentoMessaggio+"] ID TROVATO: ["+obj+"]");
  449.             if(obj!=null)
  450.                 return (String) obj;
  451.             else
  452.                 return null;
  453.         }else
  454.             return null;
  455.     }
  456.     /** delete exists */
  457.     public static void deleteFromCache_idFromRifMsgMapping(String tipoMessaggio,String riferimentoMessaggio){
  458.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  459.             String key = "mappingRifMsgToId_"+tipoMessaggio+"_"+riferimentoMessaggio;
  460.             try{
  461.                 GestoreMessaggi.cacheMappingGestoreMessaggi.remove(key);
  462.                 //System.out.println("DELETE FROM CACHE RIF MSG KEY["+key+"]");
  463.             }catch(Exception e){
  464.                 //System.out.println("DELETE FROM CACHE RIF MSG KEY["+key+"] ERROR:"+e.getMessage());
  465.             }
  466.         }
  467.     }

  468.     /** Registrazione proprietario */
  469.     public static void addIntoCache_Proprietario(MsgDiagnostico msgDiag, String tipoMessaggio,String idBusta, String proprietario) throws UtilsException{
  470.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){

  471.             String prop = proprietario;
  472.             if(prop.startsWith(RicezioneContenutiApplicativi.ID_MODULO)){
  473.                 prop = RicezioneContenutiApplicativi.ID_MODULO;
  474.             }else if(prop.startsWith(RicezioneBuste.ID_MODULO)){
  475.                 prop = RicezioneBuste.ID_MODULO;
  476.             }

  477.             String key = "proprietario_to"+prop+"_("+tipoMessaggio+"_"+idBusta+")";
  478.             GestoreMessaggi.cacheMappingGestoreMessaggi.put(key, proprietario);
  479.             /* PUT SAFE COSTOSO
  480.             try{
  481.                 GestoreMessaggi.cacheMappingGestoreMessaggi.putSafe(key, proprietario);
  482.             }catch(ObjectExistsException ex){
  483.                 //String oldValue = (String) GestoreMessaggi.cacheMappingGestoreMessaggi.get(key);
  484.                 //msgDiag.highDebug("Proprietario ["+tipoMessaggio+"]/["+idBusta+"] gia registrato, con il valore "+oldValue + " (nuovo valore:"+proprietario+")");
  485.                 msgDiag.highDebug("Proprietario ["+tipoMessaggio+"]/["+idBusta+"] gia registrato, (nuovo valore:"+proprietario+")");
  486.                 GestoreMessaggi.cacheMappingGestoreMessaggi.remove(key);
  487.                 GestoreMessaggi.cacheMappingGestoreMessaggi.put(key, proprietario);
  488.             }
  489.              */
  490.             //System.out.println("AGGIORNO CACHE PROPRIETARIO KEY["+key+"] ID["+proprietario+"]");
  491.         }
  492.     }
  493.     /** Get proprietario */
  494.     public static String getFromCache_Proprietario(String idModulo,String tipoMessaggio,String idBusta){
  495.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){

  496.             String prop = idModulo;
  497.             if(prop.startsWith(RicezioneContenutiApplicativi.ID_MODULO)){
  498.                 prop = RicezioneContenutiApplicativi.ID_MODULO;
  499.             }else if(prop.startsWith(RicezioneBuste.ID_MODULO)){
  500.                 prop = RicezioneBuste.ID_MODULO;
  501.             }

  502.             String key = "proprietario_to"+prop+"_("+tipoMessaggio+"_"+idBusta+")";
  503.             Object obj = GestoreMessaggi.cacheMappingGestoreMessaggi.get(key);
  504.             //System.out.println("GET FROM CACHE PROPRIETARIO KEY["+key+"] ID TROVATO: ["+obj+"]");
  505.             if(obj!=null)
  506.                 return (String) obj;
  507.             else
  508.                 return null;
  509.         }else
  510.             return null;
  511.     }
  512.     /** delete proprietario */
  513.     public static void deleteFromCache_Proprietario(String modulo,String tipoMessaggio,String idBusta){
  514.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  515.             String key = "proprietario_to"+modulo+"_("+tipoMessaggio+"_"+idBusta+")";
  516.             try{
  517.                 GestoreMessaggi.cacheMappingGestoreMessaggi.remove(key);
  518.                 //System.out.println("DELETE FROM CACHE Proprietario KEY["+key+"]");
  519.             }catch(Exception e){
  520.                 //System.out.println("DELETE FROM CACHE Proprietario KEY["+key+"] ERROR:"+e.getMessage());
  521.             }
  522.         }
  523.     }
  524.     /** Registrazione messaggio */
  525.     public static void addIntoCache_existsMessage(MsgDiagnostico msgDiag,String tipoMessaggio,String idBusta) throws UtilsException{
  526.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  527.             String key = "existsMessage_"+tipoMessaggio+"_"+idBusta;
  528.             GestoreMessaggi.cacheMappingGestoreMessaggi.put(key, true);
  529.             /* PUT SAFE COSTOSO
  530.             try{
  531.                 GestoreMessaggi.cacheMappingGestoreMessaggi.putSafe(key, true);
  532.             }catch(ObjectExistsException ex){
  533.                 msgDiag.highDebug("Messaggio (existsMessage) ["+tipoMessaggio+"]/["+idBusta+"] gia registrato");
  534.                 GestoreMessaggi.cacheMappingGestoreMessaggi.remove(key);
  535.                 GestoreMessaggi.cacheMappingGestoreMessaggi.put(key, true);
  536.             }*/
  537.             //System.out.println("AGGIORNO CACHE EXISTS MESSAGGIO ID["+tipoMessaggio+"_"+idBusta+"]");
  538.         }
  539.     }
  540.     /** exists messaggio */
  541.     public static boolean getFromCache_existsMessage(String tipoMessaggio,String idBusta){
  542.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  543.             Object obj = GestoreMessaggi.cacheMappingGestoreMessaggi.get("existsMessage_"+tipoMessaggio+"_"+idBusta);
  544.             //System.out.println("GET FROM CACHE EXISTS MESSAGGIO["+tipoMessaggio+"_"+idBusta+"] ID TROVATO: ["+obj+"]");
  545.             if(obj!=null)
  546.                 return (Boolean) obj;
  547.             else
  548.                 return false;
  549.         }else
  550.             return false;
  551.     }
  552.     /** delete exists */
  553.     public static void deleteFromCache_existsMessage(String tipoMessaggio,String idBusta){
  554.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  555.             String key = "existsMessage_"+tipoMessaggio+"_"+idBusta;
  556.             try{
  557.                 GestoreMessaggi.cacheMappingGestoreMessaggi.remove(key);
  558.                 //System.out.println("DELETE FROM CACHE EXISTS MESSAGE KEY["+key+"]");
  559.             }catch(Exception e){
  560.                 //System.out.println("DELETE FROM CACHE EXISTS MESSAGE KEY["+key+"] ERROR: "+e.getMessage());
  561.             }
  562.         }
  563.     }



  564.     /** Tabella Hash contenente il mapping tra tipo-id e proprietario */
  565.     private Map<String,String> tableProprietariMessaggiGestiti;

  566.     /**
  567.      * Aggiunge il proprietario di un idGestito.
  568.      *
  569.      * @param tipo
  570.      * @param idBusta
  571.      * @param proprietario
  572.      */
  573.     private void addProprietarioIntoTable(String tipo,String idBusta,String proprietario){
  574.         this.tableProprietariMessaggiGestiti.put(tipo+"@"+idBusta, proprietario);
  575.     }
  576.     /*
  577.     private String getProprietarioFromTable(String tipo,String idBusta){
  578.         return this.tableProprietariMessaggiGestiti.get(tipo+"@"+idBusta);
  579.     }
  580.      */
  581.     public void addProprietariMsgGestitiFromTable(Map<String,String> t)throws UtilsException{
  582.         this.tableProprietariMessaggiGestiti.putAll(t);
  583.     }
  584.     public Map<String, String> getTableProprietariMessaggiGestiti() {
  585.         return this.tableProprietariMessaggiGestiti;
  586.     }
  587.     public void addProprietariIntoCache_readFromTable(String modulo,String descrizione,String idBustaRichiestaCorrelata,boolean router){

  588.         if (this.openspcoopstate instanceof OpenSPCoopStateless) return; // NOP

  589.         for (String key : this.tableProprietariMessaggiGestiti.keySet()) {
  590.             String idTipo [] = key.split("@");
  591.             String value = this.tableProprietariMessaggiGestiti.get(key);
  592.             try{
  593.                 //System.out.println("Aggiornamento proprietario ["+descrizione+"] (Modulo:"+modulo+") per ["+idTipo[0]+"/"+idTipo[1]+"] a ["+value+"] ...");
  594.                 this.msgDiag.highDebug("Aggiornamento proprietario ["+descrizione+"] (Modulo:"+modulo+") per ["+idTipo[0]+"/"+idTipo[1]+"] a ["+value+"] ...");
  595.                 GestoreMessaggi.addIntoCache_Proprietario(this.msgDiag,idTipo[0],idTipo[1],value);
  596.                 this.msgDiag.highDebug("Aggiornamento proprietario ["+descrizione+"] (Modulo:"+modulo+") per ["+idTipo[0]+"/"+idTipo[1]+"] a ["+value+"] effettuata");

  597.                 if(TimerGestoreMessaggi.ID_MODULO.equals(value)){
  598.                     //  System.out.println("Gestione eliminazione messaggio");
  599.                     this.puliziaCache(modulo, this.idBusta, this.tipo, idBustaRichiestaCorrelata, router);
  600.                 }else{
  601.                     //System.out.println("Pulizia vecchi proprietari");
  602.                     this.puliziaCacheAltriProprietari(modulo, this.idBusta, this.tipo);
  603.                 }

  604.             }catch(Exception e){
  605.                 //System.out.println("Aggiornamento proprietario ["+descrizione+"] (Modulo:"+modulo+") per ["+idTipo[0]+"/"+idTipo[1]+"] a ["+value+"] ERROR");
  606.                 this.msgDiag.logErroreGenerico(e,"GestoreMessaggi.addIntoCache_Proprietario(Descr:"+descrizione+",Modulo:"+modulo+",Per:"+idTipo[0]+"/"+idTipo[1]+",Value:"+value+"");
  607.                 this.log.error("Aggiornamento proprietario ["+descrizione+"] (Modulo:"+modulo+") per ["+idTipo[0]+"/"+idTipo[1]+"] a ["+value+"] non riuscita",e);
  608.             }
  609.         }
  610.     }
  611.     public void puliziaCacheAltriProprietari(String moduloVecchio,String idBusta,String tipo){
  612.         //System.out.println("OLD");
  613.         if(moduloVecchio.indexOf(RicezioneContenutiApplicativi.ID_MODULO)>=0){
  614.             GestoreMessaggi.deleteFromCache_Proprietario(RicezioneContenutiApplicativi.ID_MODULO,tipo, idBusta);
  615.         }
  616.         else if(moduloVecchio.indexOf(Imbustamento.ID_MODULO)>=0){
  617.             GestoreMessaggi.deleteFromCache_Proprietario(Imbustamento.ID_MODULO,tipo, idBusta);
  618.         }
  619.         else if(moduloVecchio.indexOf(InoltroBuste.ID_MODULO)>=0){
  620.             GestoreMessaggi.deleteFromCache_Proprietario(InoltroBuste.ID_MODULO,tipo, idBusta);
  621.         }
  622.         else if(moduloVecchio.indexOf(SbustamentoRisposte.ID_MODULO)>=0){
  623.             GestoreMessaggi.deleteFromCache_Proprietario(SbustamentoRisposte.ID_MODULO,tipo, idBusta);
  624.         }
  625.         else if(moduloVecchio.indexOf(RicezioneBuste.ID_MODULO)>=0){
  626.             GestoreMessaggi.deleteFromCache_Proprietario(RicezioneBuste.ID_MODULO,tipo, idBusta);
  627.         }
  628.         else if(moduloVecchio.indexOf(Sbustamento.ID_MODULO)>=0){
  629.             GestoreMessaggi.deleteFromCache_Proprietario(Sbustamento.ID_MODULO,tipo, idBusta);
  630.         }
  631.         else if(moduloVecchio.indexOf(ConsegnaContenutiApplicativi.ID_MODULO)>=0){
  632.             GestoreMessaggi.deleteFromCache_Proprietario(ConsegnaContenutiApplicativi.ID_MODULO,tipo, idBusta);
  633.         }
  634.         else if(moduloVecchio.indexOf(InoltroRisposte.ID_MODULO)>=0){
  635.             GestoreMessaggi.deleteFromCache_Proprietario(InoltroRisposte.ID_MODULO,tipo, idBusta);
  636.         }
  637.         else if(moduloVecchio.indexOf(ImbustamentoRisposte.ID_MODULO)>=0){
  638.             GestoreMessaggi.deleteFromCache_Proprietario(ImbustamentoRisposte.ID_MODULO,tipo, idBusta);
  639.         }
  640.     }
  641.     public void puliziaCache(String modulo,String idBusta,String tipo,String idBustaRichiesta,boolean router){
  642.         try{
  643.             //System.out.println("delete existsMessage....");
  644.             // Pulizia esistenza Messaggio
  645.             GestoreMessaggi.deleteFromCache_existsMessage(tipo, idBusta);

  646.             // Pulizia riferimentoMessaggio
  647.             if(idBustaRichiesta!=null){
  648.                 //System.out.println("delete riferimentoMsg....");
  649.                 GestoreMessaggi.deleteFromCache_idFromRifMsgMapping(tipo, idBustaRichiesta);
  650.             }

  651.             // Pulizia proprietari
  652.             if(router){
  653.                 if(idBustaRichiesta==null){
  654.                     // delete Richiesta
  655.                     //System.out.println("router richiesta....");
  656.                     GestoreMessaggi.deleteFromCache_Proprietario(InoltroBuste.ID_MODULO,tipo, idBusta);
  657.                 }else{
  658.                     // delete Risposta
  659.                     //System.out.println("router risposta....");
  660.                     GestoreMessaggi.deleteFromCache_Proprietario(RicezioneBuste.ID_MODULO,tipo, idBusta);
  661.                 }
  662.             }else{

  663.                 if(idBustaRichiesta==null){
  664.                     if(Costanti.OUTBOX.equals(tipo)){
  665.                         // portaDelegata richiesta
  666.                         //System.out.println("pd richiesta....");
  667.                         GestoreMessaggi.deleteFromCache_Proprietario(Imbustamento.ID_MODULO,tipo, idBusta);
  668.                         GestoreMessaggi.deleteFromCache_Proprietario(InoltroBuste.ID_MODULO,tipo, idBusta);
  669.                     }else{
  670.                         // portaApplicativa richiesta
  671.                         //System.out.println("pa richiesta....");
  672.                         GestoreMessaggi.deleteFromCache_Proprietario(Sbustamento.ID_MODULO,tipo, idBusta);
  673.                         GestoreMessaggi.deleteFromCache_Proprietario(ConsegnaContenutiApplicativi.ID_MODULO,tipo, idBusta);
  674.                     }
  675.                 }else{
  676.                     if(Costanti.INBOX.equals(tipo)){
  677.                         // portaDelegata risposta
  678.                         //System.out.println("pd risposta....");
  679.                         GestoreMessaggi.deleteFromCache_Proprietario(SbustamentoRisposte.ID_MODULO,tipo, idBusta);
  680.                         GestoreMessaggi.deleteFromCache_Proprietario(RicezioneContenutiApplicativi.ID_MODULO,tipo, idBusta);
  681.                     }else{
  682.                         // portaApplicativa risposta
  683.                         //System.out.println("pa risposta....");
  684.                         GestoreMessaggi.deleteFromCache_Proprietario(ImbustamentoRisposte.ID_MODULO,tipo, idBusta);
  685.                         // nota: solo una delle due delete sara' effettiva, poiche' il msg di sblocco dato a RicezioneBuste e il msg reale dato a InoltroRisposte hanno id diverso
  686.                         GestoreMessaggi.deleteFromCache_Proprietario(RicezioneBuste.ID_MODULO,tipo, idBusta);
  687.                         GestoreMessaggi.deleteFromCache_Proprietario(InoltroRisposte.ID_MODULO,tipo, idBusta);
  688.                     }
  689.                 }
  690.             }
  691.             //System.out.println("fine");

  692.         }catch(Exception e){
  693.             this.msgDiag.logErroreGenerico(e,"GestoreMessaggi.puliziaCache(Modulo:"+modulo+",Per:"+idBusta+"/"+tipo+",Router:"+router+"");
  694.             this.log.error("Pulizia della cache non riuscita (Modulo:"+modulo+") per ["+idBusta+"/"+tipo+"] router["+router+"]",e);
  695.         }
  696.     }




  697.     /** Tabella Hash contenente l'informazione sull'esistenza di un messaggio */
  698.     private Map<String,Boolean> tableMessaggiGestiti;

  699.     /**
  700.      * Regitra l'id di un msg gestito
  701.      *
  702.      * @param tipo
  703.      * @param idBusta
  704.      */
  705.     private void addMessaggioIntoTable(String tipo,String idBusta){
  706.         this.tableMessaggiGestiti.put(tipo+"@"+idBusta,true);
  707.     }
  708.     /*
  709.     public boolean getMessaggioFromTable(String tipo,String idBusta){
  710.         Object v = this.tableMessaggiGestiti.get(tipo+"@"+idBusta);
  711.         if(v!=null)
  712.             return (Boolean )v;
  713.         else
  714.             return false;

  715.     }
  716.      */
  717.     public void addMsgGestitiFromTable(Map<String,Boolean> t)throws UtilsException{
  718.         this.tableMessaggiGestiti.putAll(t);
  719.     }
  720.     public Map<String, Boolean> getTableMessaggiGestiti() {
  721.         return this.tableMessaggiGestiti;
  722.     }
  723.     public void addMessaggiIntoCache_readFromTable(String modulo,String descrizione){

  724.         if (this.openspcoopstate instanceof OpenSPCoopStateless) return; //NOP

  725.         for (String key : this.tableMessaggiGestiti.keySet()) {
  726.             String idTipo [] = key.split("@");
  727.             Boolean value = this.tableMessaggiGestiti.get(key);
  728.             try{
  729.                 this.msgDiag.highDebug("Aggiornamento existsMessage ["+descrizione+"] (Modulo:"+modulo+") per ["+idTipo[0]+"/"+idTipo[1]+"] a ["+value+"] ...");
  730.                 GestoreMessaggi.addIntoCache_existsMessage(this.msgDiag,idTipo[0],idTipo[1]);
  731.                 this.msgDiag.highDebug("Aggiornamento existsMessage ["+descrizione+"] (Modulo:"+modulo+") per ["+idTipo[0]+"/"+idTipo[1]+"] a ["+value+"] effettuata");
  732.             }catch(Exception e){
  733.                 this.msgDiag.logErroreGenerico(e,"GestoreMessaggi.addIntoCache_existsMessage(Descr:"+descrizione+",Modulo:"+modulo+",Per:"+idTipo[0]+"/"+idTipo[1]+",Value:"+value+"");
  734.                 this.log.error("Aggiornamento existsMessage ["+descrizione+"] (Modulo:"+modulo+") per ["+idTipo[0]+"/"+idTipo[1]+"] a ["+value+"] non riuscita",e);
  735.             }
  736.         }
  737.     }



  738.     /* ********  S T A T I C  JDBC ADAPTER  ******** */

  739.     /** adapterJDBC di OpenSPCoop di OpenSPCoop */
  740.     private static IJDBCAdapter adapter=null;
  741.     private static boolean adapterInitialized = false;
  742.     private static synchronized void initAdapter(Logger log,OpenSPCoop2Properties propertiesReader){
  743.         if(GestoreMessaggi.adapterInitialized==false){
  744.             if(propertiesReader.isRepositoryOnFS() == false){
  745.                 try{
  746.                     String jdbcAdapter = propertiesReader.getRepositoryJDBCAdapter();
  747.                     if(propertiesReader.getDatabaseType()!=null && TipiDatabase.DEFAULT.equals(jdbcAdapter)){
  748.                         //System.out.println("PASSO DA FACTORY GESTORE MESSAGGI");
  749.                         GestoreMessaggi.adapter = JDBCAdapterFactory.createJDBCAdapter(propertiesReader.getDatabaseType());
  750.                     }
  751.                     else{
  752.                         ClassNameProperties classNameProperties = ClassNameProperties.getInstance();
  753.                         //      Ricerco connettore
  754.                         String adapterClass = classNameProperties.getJDBCAdapter(jdbcAdapter);
  755.                         if(adapterClass == null){
  756.                             log.error("Inizializzione GestoreMessaggi non riuscita: AdapterClass non registrata ["+propertiesReader.getRepositoryJDBCAdapter()+"]");
  757.                         }
  758.                         Loader loader = Loader.getInstance();
  759.                         GestoreMessaggi.adapter = (IJDBCAdapter) loader.newInstance(adapterClass);
  760.                     }
  761.                 }catch(Exception e){
  762.                     log.error("Inizializzione GestoreMessaggi non riuscita: AdapterClass non trovata ["+propertiesReader.getRepositoryJDBCAdapter()+"]:"+e.getMessage(),e);
  763.                 }
  764.             }
  765.             GestoreMessaggi.adapterInitialized = true;
  766.         }
  767.     }



  768.     /* ********  S T A T I C  PDDCONTEXT SERIALIZER  ******** */

  769.     /** PdDContextSerializer */
  770.     private static IPdDContextSerializer pddContextSerializer = null;
  771.     private static boolean pddContextSerializerInitialized = false;
  772.     private static synchronized void initPddContextSerializer(Logger log,OpenSPCoop2Properties propertiesReader){
  773.         if(GestoreMessaggi.pddContextSerializerInitialized==false){
  774.             String pddContextSerializerClass = propertiesReader.getPddContextSerializer();
  775.             if(pddContextSerializerClass!=null && !CostantiConfigurazione.NONE.equals(pddContextSerializerClass)){
  776.                 try{
  777.                     Loader loader = Loader.getInstance();
  778.                     GestoreMessaggi.pddContextSerializer = (IPdDContextSerializer) loader.newInstance(pddContextSerializerClass);
  779.                 }catch(Exception e){
  780.                     log.error("Inizializzione GestoreMessaggi non riuscita: IPdDContextSerializer non trovata ["+pddContextSerializerClass+"]:"+e.getMessage(),e);
  781.                 }
  782.             }
  783.             GestoreMessaggi.pddContextSerializerInitialized = true;
  784.         }
  785.     }



  786.     /* ********  C O S T R U T T O R E  ******** */

  787.     /**
  788.      * Costruttore.
  789.      *
  790.      * @param openspcoopstate Oggetto che rappresenta lo stato di una busta
  791.      *
  792.      */
  793.     public GestoreMessaggi(IOpenSPCoopState openspcoopstate, boolean isRichiesta,MsgDiagnostico msgDiag,PdDContext pddContext){
  794.         this(openspcoopstate, isRichiesta, null,null,OpenSPCoop2Logger.getLoggerOpenSPCoopCore(),msgDiag,pddContext);
  795.     }
  796.     /**
  797.      * Costruttore.
  798.      *
  799.      * @param openspcoopstate Oggetto che rappresenta lo stato di una busta
  800.      *
  801.      */
  802.     public GestoreMessaggi(IOpenSPCoopState openspcoopstate, boolean isRichiesta,Logger alog,MsgDiagnostico msgDiag,PdDContext pddContext){
  803.         this(openspcoopstate, isRichiesta,null,null,alog,msgDiag,pddContext);
  804.     }

  805.     /**
  806.      * Costruttore.
  807.      * @param openspcoopstate Oggetto che rappresenta lo stato di una busta
  808.      * @param idBusta Identificativo del Messaggio
  809.      * @param tipo Indicazione se il messaggio sara' salvato nella INBOX dei messaggi, o nella OUTBOX
  810.      *
  811.      */
  812.     public GestoreMessaggi(IOpenSPCoopState openspcoopstate, boolean isRichiesta,String idBusta, String tipo,MsgDiagnostico msgDiag,PdDContext pddContext){
  813.         this(openspcoopstate, isRichiesta, idBusta,tipo,Configurazione.getLibraryLog(),msgDiag,pddContext);
  814.     }
  815.     /**
  816.      * Costruttore.
  817.      *
  818.      * @param openspcoopstate Oggetto che rappresenta lo stato di una busta
  819.      * @param idBusta Identificativo del Messaggio
  820.      * @param tipo Indicazione se il messaggio sara' salvato nella INBOX dei messaggi, o nella OUTBOX
  821.      *
  822.      */
  823.     public GestoreMessaggi(IOpenSPCoopState openspcoopstate, boolean isRichiesta, String idBusta, String tipo,Logger alog,MsgDiagnostico msgDiag,PdDContext pddContext){
  824.         this.openspcoopstate = openspcoopstate;
  825.         this.isRichiesta = isRichiesta;
  826.         //state = (isRichiesta) ? openspcoopstate.getStatoRichiesta() : openspcoopstate.getStatoRisposta();
  827.         // new  HashMap<String,PreparedStatement>(); in stateful ?? inizializzo ?
  828.         this.tableProprietariMessaggiGestiti = new  ConcurrentHashMap<String,String>();
  829.         this.tableMessaggiGestiti = new ConcurrentHashMap<String, Boolean>();
  830.         this.idBusta = idBusta;
  831.         this.tipo = tipo;
  832.         this.propertiesReader = OpenSPCoop2Properties.getInstance();
  833.         this.msgDiag = msgDiag;
  834.         if(alog!=null){
  835.             this.log = alog;
  836.         }else{
  837.             this.log = LoggerWrapperFactory.getLogger(GestoreMessaggi.class);
  838.         }

  839.         if(this.propertiesReader.isRepositoryOnFS() == false){
  840.             if(GestoreMessaggi.adapterInitialized==false){
  841.                 GestoreMessaggi.initAdapter(this.log,this.propertiesReader);
  842.             }
  843.         }else{
  844.             this.workDir = this.propertiesReader.getRepositoryDirectory();
  845.         }

  846.         if(GestoreMessaggi.pddContextSerializerInitialized==false){
  847.             GestoreMessaggi.initPddContextSerializer(this.log,this.propertiesReader);
  848.         }

  849.         GestoreMessaggi.cluster_id = this.propertiesReader.getClusterId(false);

  850.         this.pddContext = pddContext;
  851.         try{
  852.             if(this.pddContext!=null) {
  853.                 this.idTransazione = (String) this.pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  854.                 this.protocolFactory = ProtocolFactoryManager.getInstance().getProtocolFactoryByName((String) this.pddContext.getObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME));
  855.             }
  856.         }catch(Exception e){
  857.             this.log.error("Inizializzione GestoreMessaggi non riuscita [ProtocoFactoryManager.getInstance]:"+e.getMessage(),e);
  858.         }

  859.     }












  860.     /* ********  U T I L I T Y  ******** */

  861.     /**
  862.      * Imposta lo stateMessage
  863.      *
  864.      * @param openspcoopstate oggetto che rappresenta lo stato della busta
  865.      *
  866.      */
  867.     public void updateOpenSPCoopState(IOpenSPCoopState openspcoopstate){
  868.         this.openspcoopstate = openspcoopstate;
  869.     }




  870.     /**
  871.      * Restituisce il nome della colonna associata al nodo con identificativo <var>nomeNodo</var>.
  872.      *
  873.      * @param idNodo Identificatore del nodo.
  874.      *
  875.      */
  876.     private String getColonnaSQL(String idNodo) throws SQLException{
  877.         if(idNodo.startsWith(RicezioneContenutiApplicativi.ID_MODULO))
  878.             return "MOD_RICEZ_CONT_APPLICATIVI";
  879.         else if(ConsegnaContenutiApplicativi.ID_MODULO.equals(idNodo))
  880.             return "MOD_CONSEGNA_CONT_APPLICATIVI";
  881.         else if(idNodo.startsWith(RicezioneBuste.ID_MODULO))
  882.             return "MOD_RICEZ_BUSTE";
  883.         else if(InoltroBuste.ID_MODULO.equals(idNodo))
  884.             return "MOD_INOLTRO_BUSTE";
  885.         else if(InoltroRisposte.ID_MODULO.equals(idNodo))
  886.             return "MOD_INOLTRO_RISPOSTE";
  887.         else if(Imbustamento.ID_MODULO.equals(idNodo))
  888.             return "MOD_IMBUSTAMENTO";
  889.         else if(ImbustamentoRisposte.ID_MODULO.equals(idNodo))
  890.             return "MOD_IMBUSTAMENTO_RISPOSTE";
  891.         else if(Sbustamento.ID_MODULO.equals(idNodo))
  892.             return "MOD_SBUSTAMENTO";
  893.         else if(SbustamentoRisposte.ID_MODULO.equals(idNodo))
  894.             return "MOD_SBUSTAMENTO_RISPOSTE";
  895.         else
  896.             throw new SQLException("Traduzione IDModulo->ColonnaSQL per modulo ["+idNodo+"] non possibile");
  897.     }





















  898.     /* ********  C R E A Z I O N E  ******** */
  899.     /**
  900.      * Crea lo stato di un messaggio gestito da OpenSPCoop, salvandolo anche su fileSystem/DB.
  901.      *
  902.      * @param message Messaggio.
  903.      *
  904.      */
  905.     public void registraMessaggio(OpenSPCoop2Message message,String correlazioneApplicativaRichiesta) throws GestoreMessaggiException{
  906.         registraMessaggio(message,null, false,correlazioneApplicativaRichiesta,null);
  907.     }
  908.     public void registraMessaggio(OpenSPCoop2Message message,String correlazioneApplicativaRichiesta,String correlazioneApplicativaRisposta) throws GestoreMessaggiException{
  909.         registraMessaggio(message,null, false,correlazioneApplicativaRichiesta,correlazioneApplicativaRisposta);
  910.     }

  911.     public void registraMessaggio(OpenSPCoop2Message message,Date oraRegistrazione,String correlazioneApplicativaRichiesta) throws GestoreMessaggiException{
  912.         registraMessaggio(message,oraRegistrazione, false,correlazioneApplicativaRichiesta,null);
  913.     }
  914.     public void registraMessaggio(OpenSPCoop2Message message,Date oraRegistrazione,String correlazioneApplicativaRichiesta,String correlazioneApplicativaRisposta) throws GestoreMessaggiException{
  915.         registraMessaggio(message,oraRegistrazione, false,correlazioneApplicativaRichiesta,correlazioneApplicativaRisposta);
  916.     }

  917.     /**
  918.      * Crea lo stato di un messaggio gestito da OpenSPCoop, salvandolo anche su fileSystem/DB.
  919.      *
  920.      * @param message Messaggio.
  921.      *
  922.      */
  923.     public void registraMessaggio(OpenSPCoop2Message message, Date oraRegistrazione, boolean salvaNelloStateless,
  924.             String correlazioneApplicativaRichiesta) throws GestoreMessaggiException {
  925.         registraMessaggio(message,oraRegistrazione,salvaNelloStateless,correlazioneApplicativaRichiesta,null);
  926.     }
  927.     public void registraMessaggio(OpenSPCoop2Message message, Date oraRegistrazione, boolean salvaNelloStateless,
  928.             String correlazioneApplicativaRichiesta,String correlazioneApplicativaRisposta) throws GestoreMessaggiException {

  929.         // OraRegistrazione
  930.         java.sql.Timestamp oraRegistrazioneT = null;
  931.         if (oraRegistrazione == null) {
  932.             oraRegistrazioneT = DateManager.getTimestamp();
  933.         } else {
  934.             oraRegistrazioneT = new java.sql.Timestamp(oraRegistrazione.getTime());
  935.         }

  936.         // Gestione stateless
  937.         boolean gestisciInfoGenericheDB = true;
  938.         if( this.openspcoopstate instanceof OpenSPCoopStateless ){

  939.             if (this.isRichiesta)
  940.                 ((OpenSPCoopStateless)this.openspcoopstate).getTempiAttraversamentoPDD().setRicezioneMsgIngresso(oraRegistrazioneT);
  941.             else
  942.                 ((OpenSPCoopStateless)this.openspcoopstate).getTempiAttraversamentoPDD().setRicezioneMsgRisposta(oraRegistrazioneT);

  943.             ((OpenSPCoopStateless)this.openspcoopstate).setIDCorrelazioneApplicativa(correlazioneApplicativaRichiesta);
  944.             ((OpenSPCoopStateless)this.openspcoopstate).setIDCorrelazioneApplicativaRisposta(correlazioneApplicativaRisposta);
  945.             ((OpenSPCoopStateless)this.openspcoopstate).setPddContext(this.pddContext);

  946.             if(!this.isRichiesta){
  947.                 ((OpenSPCoopStateless)this.openspcoopstate).setRispostaMsg(message);
  948.                 return;
  949.             }else{
  950.                 if( (this.oneWayVersione11==false) || this.routingStateless){
  951.                     gestisciInfoGenericheDB = false;
  952.                 }
  953.             }
  954.         }

  955.         // stato
  956.         StateMessage stato = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta()) : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  957.         // Gestione info DB
  958.         if(gestisciInfoGenericheDB){


  959.             Connection connectionDB = stato.getConnectionDB();  

  960.             /* ----- Registrazione in contesto OpenSPCoop ------- */
  961.             PreparedStatement pstmt = null;
  962.             try {

  963.                 // PdDContext
  964.                 StringBuilder fieldNamesPdDContext = new StringBuilder();
  965.                 StringBuilder fieldValuesPdDContext = new StringBuilder();
  966.                 Map<String, String> contextSerializerParameters = null;
  967.                 List<Object> objectSerializer = new ArrayList<>();
  968.                 if(GestoreMessaggi.pddContextSerializer!=null){
  969.                     contextSerializerParameters = GestoreMessaggi.pddContextSerializer.getGestoreMessaggiKeywords();
  970.                     if(contextSerializerParameters!=null && contextSerializerParameters.size()>0){
  971.                         for (String keyword : contextSerializerParameters.keySet()) {

  972.                             MapKey<String> mapKey = org.openspcoop2.utils.Map.newMapKey(keyword);
  973.                             Object o = this.pddContext.getObject(mapKey);
  974.                             if(o==null){
  975.                                 continue; // un oggetto puo' essere opzionale in un context
  976.                             }

  977.                             fieldNamesPdDContext.append(" , ");
  978.                             fieldValuesPdDContext.append(" , ");
  979.                             fieldNamesPdDContext.append(contextSerializerParameters.get(keyword));
  980.                             fieldValuesPdDContext.append("?");

  981.                             if( !(o instanceof String) && !(o instanceof Long) && !(o instanceof Timestamp)){
  982.                                 throw new Exception("Oggetto con chiave ["+keyword+"] e' di tipo ["+o.getClass().getName()+"], e' possibile serializzare solo i tipi java.lang.String/java.lang.Long/java.sql.Timestamp");
  983.                             }
  984.                             objectSerializer.add(o);
  985.                         }
  986.                     }
  987.                 }


  988.                 StringBuilder query = new StringBuilder();
  989.                 query.append("INSERT INTO ");

  990.                 query.append(GestoreMessaggi.MESSAGGI);
  991.                 query.append("(ID_MESSAGGIO,TIPO,ORA_REGISTRAZIONE,RISPEDIZIONE, REDELIVERY_DELAY, CLUSTER_ID, CORRELAZIONE_APPLICATIVA, CORRELAZIONE_RISPOSTA, PROTOCOLLO, id_transazione"+fieldNamesPdDContext.toString()
  992.                         +") VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?"+fieldValuesPdDContext.toString()+")");
  993.                 //this.log.debug("[registraMessaggio] Aggiorno MSG["+this.tipo+"/"+this.idBusta+"] ORA_REGISTRAZIONE["+oraRegistrazioneT.toString()+"] e RISPEDIZIONE["+oraRegistrazioneT.toString()+"]");


  994.                 pstmt = connectionDB.prepareStatement(query.toString());
  995.                 int index = 1;
  996.                 pstmt.setString(index++, this.idBusta);
  997.                 pstmt.setString(index++, this.tipo);
  998.                 pstmt.setTimestamp(index++, oraRegistrazioneT);
  999.                 pstmt.setTimestamp(index++, oraRegistrazioneT);
  1000.                 pstmt.setTimestamp(index++, oraRegistrazioneT);
  1001.                 pstmt.setString(index++, GestoreMessaggi.cluster_id);
  1002.                 pstmt.setString(index++, correlazioneApplicativaRichiesta);
  1003.                 pstmt.setString(index++, correlazioneApplicativaRisposta);
  1004.                 pstmt.setString(index++, this.protocolFactory.getProtocol());
  1005.                 pstmt.setString(index++, this.idTransazione);
  1006.                 for (int i = 0; i < objectSerializer.size(); i++) {
  1007.                     Object o = objectSerializer.get(i);
  1008.                     if(o instanceof String){
  1009.                         pstmt.setString(index++, o.toString());
  1010.                     } else if(o instanceof Long){
  1011.                         pstmt.setLong(index++, (Long)o);
  1012.                     } else if(o instanceof Timestamp){
  1013.                         pstmt.setTimestamp(index++, (Timestamp)o);
  1014.                     }
  1015.                 }

  1016.                 // Add PreparedStatement:
  1017.                 stato.getPreparedStatement().put("INSERT (MSG_OP_STEP1) registraMessaggioOpenSPCoop " + this.tipo + "/" + this.idBusta, pstmt);

  1018.                 // Add Messaggio into table
  1019.                 this.addMessaggioIntoTable(this.tipo, this.idBusta);

  1020.             } catch (Exception e) {
  1021.                 String errorMsg = "GESTORE_MESSAGGI, Errore di registrazione " + this.tipo + "/" + this.idBusta + ": " + e.getMessage();
  1022.                 this.log.error(errorMsg, e);
  1023.                 try {
  1024.                     if (pstmt != null) {
  1025.                         pstmt.close();
  1026.                     }
  1027.                 } catch (Exception er) {
  1028.                 }
  1029.                 throw new GestoreMessaggiException(errorMsg, e);
  1030.             }
  1031.         }

  1032.         //  Salvo contenuto messaggio
  1033.         if (message != null) {

  1034.             SavedMessage msgSoap = null;
  1035.             try {
  1036.                 msgSoap = new SavedMessage(this.idBusta, this.openspcoopstate, this.tipo, this.workDir, GestoreMessaggi.adapter, this.log);
  1037.                 boolean consume = true;
  1038.                 msgSoap.save(message, this.isRichiesta, salvaNelloStateless, consume, oraRegistrazioneT);
  1039.             } catch (Exception e) {
  1040.                 String errorMsg = "GESTORE_MESSAGGI, Errore di registrazione (SoapMessage) " + this.tipo + "/" + this.idBusta + ": " + e.getMessage();
  1041.                 if (msgSoap != null) {
  1042.                     stato.closePreparedStatement(); // Chiude le PreparedStatement aperte(e non eseguite) per il salvataggio del Msg
  1043.                 }
  1044.                 this.log.error(errorMsg, e);
  1045.                 throw new GestoreMessaggiException(errorMsg, e);
  1046.             }
  1047.         }
  1048.     }

  1049.     public java.sql.Timestamp registraInformazioniMessaggio_statelessEngine(Date oraRegistrazione,String proprietarioMessaggio,
  1050.             String correlazioneApplicativaRichiesta) throws GestoreMessaggiException {
  1051.         return this.registraInformazioniMessaggio_statelessEngine(oraRegistrazione, proprietarioMessaggio, null,correlazioneApplicativaRichiesta,null);
  1052.     }
  1053.     public java.sql.Timestamp registraInformazioniMessaggio_statelessEngine(Date oraRegistrazione,String proprietarioMessaggio,String riferimentoMessaggio,
  1054.             String correlazioneApplicativaRichiesta,String correlazioneApplicativaRisposta) throws GestoreMessaggiException {

  1055.         // OraRegistrazione
  1056.         java.sql.Timestamp oraRegistrazioneT = null;
  1057.         if (oraRegistrazione == null) {
  1058.             oraRegistrazioneT = DateManager.getTimestamp();
  1059.         } else {
  1060.             oraRegistrazioneT = new java.sql.Timestamp(oraRegistrazione.getTime());
  1061.         }

  1062.         // stato
  1063.         StateMessage stato = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta()) : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  1064.         // Gestione info DB
  1065.         Connection connectionDB = stato.getConnectionDB();  

  1066.         /* ----- Registrazione in contesto OpenSPCoop ------- */
  1067.         PreparedStatement pstmt = null;
  1068.         try {

  1069.             // PdDContext
  1070.             StringBuilder fieldNamesPdDContext = new StringBuilder();
  1071.             StringBuilder fieldValuesPdDContext = new StringBuilder();
  1072.             Map<String, String> contextSerializerParameters = null;
  1073.             List<Object> objectSerializer = new ArrayList<>();
  1074.             if(GestoreMessaggi.pddContextSerializer!=null){
  1075.                 contextSerializerParameters = GestoreMessaggi.pddContextSerializer.getGestoreMessaggiKeywords();
  1076.                 if(contextSerializerParameters!=null && contextSerializerParameters.size()>0){
  1077.                     for (String keyword : contextSerializerParameters.keySet()) {

  1078.                         MapKey<String> mapKey = org.openspcoop2.utils.Map.newMapKey(keyword);
  1079.                         Object o = this.pddContext.getObject(mapKey);
  1080.                         if(o==null){
  1081.                             continue; // un oggetto puo' essere opzionale in un context
  1082.                         }

  1083.                         fieldNamesPdDContext.append(" , ");
  1084.                         fieldValuesPdDContext.append(" , ");
  1085.                         fieldNamesPdDContext.append(contextSerializerParameters.get(keyword));
  1086.                         fieldValuesPdDContext.append("?");

  1087.                         if( !(o instanceof String) && !(o instanceof Long) && !(o instanceof Timestamp)){
  1088.                             throw new Exception("Oggetto con chiave ["+keyword+"] e' di tipo ["+o.getClass().getName()+"], e' possibile serializzare solo i tipi java.lang.String/java.lang.Long/java.sql.Timestamp");
  1089.                         }
  1090.                         objectSerializer.add(o);
  1091.                     }
  1092.                 }
  1093.             }


  1094.             StringBuilder query = new StringBuilder();
  1095.             query.append("INSERT INTO ");

  1096.             query.append(GestoreMessaggi.MESSAGGI);
  1097.             query.append("(ID_MESSAGGIO,TIPO,ORA_REGISTRAZIONE,RISPEDIZIONE, REDELIVERY_DELAY, CLUSTER_ID, PROPRIETARIO, CORRELAZIONE_APPLICATIVA, CORRELAZIONE_RISPOSTA, PROTOCOLLO, id_transazione ");
  1098.             if(riferimentoMessaggio!=null)
  1099.                 query.append(", RIFERIMENTO_MSG");
  1100.             query.append(fieldNamesPdDContext.toString());
  1101.             query.append(") VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ");
  1102.             if(riferimentoMessaggio!=null)
  1103.                 query.append(", ?");
  1104.             query.append(fieldValuesPdDContext);
  1105.             query.append(" )");

  1106.             //this.log.debug("[registraMessaggio] Aggiorno MSG["+this.tipo+"/"+this.idBusta+"] ORA_REGISTRAZIONE["+oraRegistrazioneT.toString()+"] e RISPEDIZIONE["+oraRegistrazioneT.toString()+"]");


  1107.             pstmt = connectionDB.prepareStatement(query.toString());
  1108.             int index = 1;
  1109.             pstmt.setString(index++, this.idBusta);
  1110.             pstmt.setString(index++, this.tipo);
  1111.             pstmt.setTimestamp(index++, oraRegistrazioneT);
  1112.             pstmt.setTimestamp(index++, oraRegistrazioneT);
  1113.             pstmt.setTimestamp(index++, oraRegistrazioneT);
  1114.             pstmt.setString(index++, GestoreMessaggi.cluster_id);
  1115.             pstmt.setString(index++, proprietarioMessaggio);
  1116.             pstmt.setString(index++, correlazioneApplicativaRichiesta);
  1117.             pstmt.setString(index++, correlazioneApplicativaRisposta);
  1118.             pstmt.setString(index++, this.protocolFactory.getProtocol());
  1119.             pstmt.setString(index++, this.idTransazione);
  1120.             if(riferimentoMessaggio!=null){
  1121.                 pstmt.setString(index++,riferimentoMessaggio);
  1122.             }
  1123.             for (int i = 0; i < objectSerializer.size(); i++) {
  1124.                 Object o = objectSerializer.get(i);
  1125.                 if(o instanceof String){
  1126.                     pstmt.setString(index++, o.toString());
  1127.                 } else if(o instanceof Long){
  1128.                     pstmt.setLong(index++, (Long)o);
  1129.                 } else if(o instanceof Timestamp){
  1130.                     pstmt.setTimestamp(index++, (Timestamp)o);
  1131.                 }
  1132.             }

  1133.             // Add PreparedStatement:
  1134.             stato.getPreparedStatement().put("INSERT (MSG_OP_STEP1) registraMessaggioOpenSPCoop(stateless engine) " + this.tipo + "/" + this.idBusta, pstmt);

  1135.             // Add Messaggio into table
  1136.             this.addMessaggioIntoTable(this.tipo, this.idBusta);

  1137.         } catch (Exception e) {
  1138.             String errorMsg = "GESTORE_MESSAGGI, Errore di registrazione (stateless engine) " + this.tipo + "/" + this.idBusta + ": " + e.getMessage();
  1139.             this.log.error(errorMsg, e);
  1140.             try {
  1141.                 if (pstmt != null) {
  1142.                     pstmt.close();
  1143.                 }
  1144.             } catch (Exception er) {
  1145.             }
  1146.             throw new GestoreMessaggiException(errorMsg, e);
  1147.         }

  1148.         return oraRegistrazioneT;
  1149.     }

  1150.     public void registraMessaggio_statelessEngine(OpenSPCoop2Message message, boolean consumeMessage, java.sql.Timestamp oraRegistrazioneT) throws GestoreMessaggiException {
  1151.         // Salvo contenuto messaggio
  1152.         if (message != null) {

  1153.             // stato
  1154.             StateMessage stato = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta()) : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;


  1155.             SavedMessage msgSoap = null;
  1156.             try {
  1157.                 msgSoap = new SavedMessage(this.idBusta, this.openspcoopstate, this.tipo, this.workDir, GestoreMessaggi.adapter, this.log);
  1158.                 msgSoap.save(message, this.isRichiesta, false, consumeMessage, oraRegistrazioneT);
  1159.             } catch (Exception e) {
  1160.                 String errorMsg = "GESTORE_MESSAGGI, Errore di registrazione (SoapMessage) " + this.tipo + "/" + this.idBusta + ": " + e.getMessage();
  1161.                 if (msgSoap != null) {
  1162.                     stato.closePreparedStatement(); // Chiude le PreparedStatement aperte(e non eseguite) per il salvataggio del Msg
  1163.                 }
  1164.                 this.log.error(errorMsg, e);
  1165.                 throw new GestoreMessaggiException(errorMsg, e);
  1166.             }
  1167.         }
  1168.     }
  1169.    
  1170.     public void registraRisposta_statelessEngine(String identificativo, OpenSPCoop2Message message, boolean consumeMessage) throws GestoreMessaggiException {
  1171.         // Salvo contenuto messaggio
  1172.         if (message != null) {

  1173.             String id = identificativo!=null ? identificativo : this.idBusta;
  1174.            
  1175.             // stato
  1176.             StateMessage stato = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta()) : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;


  1177.             SavedMessage msgSoap = null;
  1178.             try {
  1179.                 msgSoap = new SavedMessage(id, this.openspcoopstate, this.tipo, this.workDir, GestoreMessaggi.adapter, this.log);
  1180.                 msgSoap.updateResponse(message, consumeMessage);
  1181.             } catch (Exception e) {
  1182.                 String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento (SoapMessage) " + this.tipo + "/" + id + ": " + e.getMessage();
  1183.                 if (msgSoap != null) {
  1184.                     stato.closePreparedStatement(); // Chiude le PreparedStatement aperte(e non eseguite) per il salvataggio del Msg
  1185.                 }
  1186.                 this.log.error(errorMsg, e);
  1187.                 throw new GestoreMessaggiException(errorMsg, e);
  1188.             }
  1189.         }
  1190.     }
  1191.    
  1192.     public void registraTransactionContext_statelessEngine(String identificativo, Context context) throws GestoreMessaggiException {
  1193.         // Salvo contenuto messaggio
  1194.         if (context != null) {

  1195.             String id = identificativo!=null ? identificativo : this.idBusta;
  1196.            
  1197.             // stato
  1198.             StateMessage stato = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta()) : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;


  1199.             SavedMessage msgSoap = null;
  1200.             try {
  1201.                 msgSoap = new SavedMessage(id, this.openspcoopstate, this.tipo, this.workDir, GestoreMessaggi.adapter, this.log);
  1202.                 msgSoap.updateTransactionContext(context);
  1203.             } catch (Exception e) {
  1204.                 String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento (TransactionContext) " + this.tipo + "/" + id + ": " + e.getMessage();
  1205.                 if (msgSoap != null) {
  1206.                     stato.closePreparedStatement(); // Chiude le PreparedStatement aperte(e non eseguite) per il salvataggio del Msg
  1207.                 }
  1208.                 this.log.error(errorMsg, e);
  1209.                 throw new GestoreMessaggiException(errorMsg, e);
  1210.             }
  1211.         }
  1212.     }

  1213.     /**
  1214.      * Registra un destinatario (servizio applicativo) il quale dovra' ricevere un messaggio gestito da OpenSPCoop.
  1215.      *
  1216.      * @param serv Servizio Applicativo da registrare come destinatario del messaggio
  1217.      * @param sbustamentoSOAP Indicazione se al servizio applicativo deve essere ritornato un messaggio sbustato
  1218.      * @param integrationManager Indiciazione se il servizio applicativo e' autorizzato a ricevere il contenuto anche attraverso il servizio integrationManager
  1219.      * @param tipoConsegna Assume il valore 'Connettore' se la consegna avviente tramite un connettore, 'ConnectionReply' se viene ritornato tramite connectionReply, 'IntegrationManager' se e' solo ottenibile tramite IntegrationManager
  1220.      *
  1221.      */
  1222.     public void registraDestinatarioMessaggio(String serv,
  1223.             boolean sbustamentoSOAP,boolean sbustamentoInfoProtocol,
  1224.             boolean integrationManager,String tipoConsegna,Timestamp oraRegistrazioneMessaggio,
  1225.             String nomePorta, boolean attesaEsito, boolean impostaPerConsegnaTimerContenutiApplicativi,
  1226.             String coda, String priorita, boolean schedulingNonAttivo)throws GestoreMessaggiException{
  1227.         if(this.openspcoopstate instanceof OpenSPCoopStateful || this.oneWayVersione11) {
  1228.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  1229.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  1230.             Connection connectionDB = stateMSG.getConnectionDB();
  1231.             PreparedStatement pstmt = null;
  1232.             try{    

  1233.                 // Costruzione Query
  1234.                 StringBuilder query = new StringBuilder();
  1235.                 query.append("INSERT INTO ");
  1236.                 query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  1237.                 String columnCoda = "";
  1238.                 String valueCoda = "";
  1239.                 String columnPriorita = "";
  1240.                 String valuePriorita = "";
  1241.                 String columnErroreProcessamento = "";
  1242.                 String valueErroreProcessamento = "";
  1243.                 String columnLockConsegna = "";
  1244.                 String valueLockConsegna = "";
  1245.                 if(coda!=null) {
  1246.                     columnCoda=",CODA";
  1247.                     valueCoda=", ?";
  1248.                 }
  1249.                 if(priorita!=null) {
  1250.                     columnPriorita=",PRIORITA";
  1251.                     valuePriorita=", ?";
  1252.                 }
  1253.                 if(impostaPerConsegnaTimerContenutiApplicativi) {
  1254.                     columnErroreProcessamento = ",ERRORE_PROCESSAMENTO,ERRORE_PROCESSAMENTO_COMPACT";
  1255.                     valueErroreProcessamento = ", ? , ?";
  1256.                 }
  1257.                 if(schedulingNonAttivo) {
  1258.                     columnLockConsegna=",LOCK_CONSEGNA";
  1259.                     valueLockConsegna=", ?";
  1260.                 }
  1261.                 query.append("(ID_MESSAGGIO,SERVIZIO_APPLICATIVO,SBUSTAMENTO_SOAP,SBUSTAMENTO_INFO_PROTOCOL,INTEGRATION_MANAGER,TIPO_CONSEGNA,ORA_REGISTRAZIONE,RISPEDIZIONE,NOME_PORTA,ATTESA_ESITO"+
  1262.                             columnCoda+
  1263.                             columnPriorita+
  1264.                             columnErroreProcessamento+
  1265.                             columnLockConsegna+
  1266.                         ") VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?"+
  1267.                             valueCoda+
  1268.                             valuePriorita+
  1269.                             valueErroreProcessamento+
  1270.                             valueLockConsegna+
  1271.                             ")");

  1272.                 pstmt = connectionDB.prepareStatement(query.toString());
  1273.                 int index = 1;
  1274.                 pstmt.setString(index++,this.idBusta);
  1275.                 pstmt.setString(index++,serv);
  1276.                 if(sbustamentoSOAP)
  1277.                     pstmt.setInt(index++,CostantiDB.TRUE);
  1278.                 else
  1279.                     pstmt.setInt(index++,CostantiDB.FALSE);
  1280.                 if(sbustamentoInfoProtocol)
  1281.                     pstmt.setInt(index++,CostantiDB.TRUE);
  1282.                 else
  1283.                     pstmt.setInt(index++,CostantiDB.FALSE);
  1284.                 if(integrationManager)
  1285.                     pstmt.setInt(index++,CostantiDB.TRUE);
  1286.                 else
  1287.                     pstmt.setInt(index++,CostantiDB.FALSE);
  1288.                 pstmt.setString(index++,tipoConsegna);

  1289.                 pstmt.setTimestamp(index++,oraRegistrazioneMessaggio);

  1290.                 pstmt.setTimestamp(index++,oraRegistrazioneMessaggio); // rispedizione, verra aggiornata
  1291.                
  1292.                 pstmt.setString(index++,nomePorta);
  1293.                
  1294.                 if(attesaEsito)
  1295.                     pstmt.setInt(index++,CostantiDB.TRUE);
  1296.                 else
  1297.                     pstmt.setInt(index++,CostantiDB.FALSE);
  1298.                
  1299.                 if(coda!=null) {
  1300.                     pstmt.setString(index++, coda);
  1301.                 }
  1302.                 if(priorita!=null) {
  1303.                     pstmt.setString(index++, priorita);
  1304.                 }
  1305.                
  1306.                 if(impostaPerConsegnaTimerContenutiApplicativi) {
  1307.                     pstmt.setString(index++, TimerConsegnaContenutiApplicativiThread.ID_MODULO);
  1308.                     pstmt.setString(index++, TimerConsegnaContenutiApplicativiThread.ID_MODULO);
  1309.                 }
  1310.                
  1311.                 if(schedulingNonAttivo) {
  1312.                     pstmt.setTimestamp(index++, TimerConsegnaContenutiApplicativiThread.LOCK_CONSEGNA_FUTURA);
  1313.                 }

  1314.                 //this.log.debug("[registraDestinatarioMessaggio] Aggiorno MSG["+this.tipo+"/"+this.idBusta+"] RISPEDIZIONE["+oraRegistrazioneMessaggio.toString()+"]");

  1315.                 // Add PreparedStatement
  1316.                 stateMSG.getPreparedStatement().put("INSERT (MSG_OP_STEP2) registraDestinatarioMessaggioOpenSPCoop["+serv+"]["+this.idBusta+"]",pstmt);

  1317.             } catch(Exception e) {
  1318.                 String errorMsg = "GESTORE_MESSAGGI, Errore di registrazione destinatario Messaggio "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  1319.                 try{
  1320.                     if(pstmt != null)
  1321.                         pstmt.close();
  1322.                 } catch(Exception er) {
  1323.                     // close
  1324.                 }
  1325.                 this.log.error(errorMsg,e);
  1326.                 throw new GestoreMessaggiException(errorMsg,e);
  1327.             }
  1328.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless && !this.oneWayVersione11){
  1329.             //NOP
  1330.         }else{
  1331.             throw new GestoreMessaggiException("Metodo invocato con IState non valido"); //CAMBIARE FIRMA PER TRATTARE ECCEZIONE?
  1332.         }
  1333.     }








  1334.     /* ********  A G G I O R N A M E N T I  ******** */



  1335.     /**
  1336.      * Aggiorna lo stato di un messaggio gestito da OpenSPCoop, configurando il nodo dell'infrastruttura autorizzato a processarlo.
  1337.      *
  1338.      * @param nodoOpenSPCoop  Nodo OpenSPCoop autorizzato a processare il messaggio
  1339.      *
  1340.      */
  1341.     public void aggiornaProprietarioMessaggio(String nodoOpenSPCoop)throws GestoreMessaggiException{
  1342.         this.aggiornaProprietarioMessaggio_engine(nodoOpenSPCoop, false, false);
  1343.     }

  1344.     /**
  1345.      * Aggiorna lo stato di un messaggio gestito da OpenSPCoop, configurando il nodo dell'infrastruttura autorizzato a processarlo.
  1346.      *
  1347.      * @param nodoOpenSPCoop  Nodo OpenSPCoop autorizzato a processare il messaggio
  1348.      *
  1349.      */
  1350.     public void aggiornaProprietarioMessaggio(String nodoOpenSPCoop,boolean searchForRiferimentoMsg)throws GestoreMessaggiException{
  1351.         this.aggiornaProprietarioMessaggio_engine(nodoOpenSPCoop, searchForRiferimentoMsg,false);
  1352.     }


  1353.     /**
  1354.      * Aggiorna lo stato di un messaggio gestito da OpenSPCoop, configurando il nodo dell'infrastruttura autorizzato a processarlo.
  1355.      *
  1356.      * @param nodoOpenSPCoop  Nodo OpenSPCoop autorizzato a processare il messaggio
  1357.      *
  1358.      */
  1359.     private boolean deleted = false;
  1360.     private void aggiornaProprietarioMessaggio_engine(String nodoOpenSPCoop,boolean searchForRiferimentoMsg,boolean executePreparedStatement)throws GestoreMessaggiException{

  1361.         if(this.deleted){
  1362.             return; // gia' marcato per eliminazione
  1363.         }

  1364.         boolean stateful = this.openspcoopstate instanceof OpenSPCoopStateful;

  1365.         if(!stateful){
  1366.             if (this.isRichiesta) ((OpenSPCoopStateless)this.openspcoopstate).setDestinatarioRequestMsgLib(nodoOpenSPCoop);
  1367.             else ((OpenSPCoopStateless)this.openspcoopstate).setDestinatarioResponseMsgLib(nodoOpenSPCoop);
  1368.         }

  1369.         if( stateful || this.readyForDrop || this.oneWayVersione11) {
  1370.             StateMessage stateMsg = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  1371.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  1372.             Connection connectionDB = stateMsg.getConnectionDB();

  1373.             PreparedStatement pstmt = null;
  1374.             try{    

  1375.                 // Costruzione Query
  1376.                 StringBuilder query = new StringBuilder();
  1377.                 query.append("UPDATE ");
  1378.                 query.append(GestoreMessaggi.MESSAGGI);
  1379.                 query.append(" SET PROPRIETARIO=? WHERE ");
  1380.                 // Se devo aggiornare per riferimento, devo invertire il tipo del messaggio, e devo cercare i messaggi che possiedono l'id come riferimento
  1381.                 String tipoMessaggio = null;
  1382.                 if(searchForRiferimentoMsg){
  1383.                     if(Costanti.OUTBOX.equals(this.tipo)){
  1384.                         tipoMessaggio = Costanti.INBOX;
  1385.                     }else{
  1386.                         tipoMessaggio = Costanti.OUTBOX;
  1387.                     }
  1388.                     query.append(" RIFERIMENTO_MSG=? AND TIPO=? ");
  1389.                 }else{
  1390.                     tipoMessaggio = this.tipo;
  1391.                     query.append(" ID_MESSAGGIO=? AND TIPO=? ");
  1392.                 }
  1393.                 pstmt = connectionDB.prepareStatement(query.toString());
  1394.                 pstmt.setString(1,nodoOpenSPCoop);
  1395.                 pstmt.setString(2,this.idBusta);
  1396.                 pstmt.setString(3,tipoMessaggio);

  1397.                 // Add PreparedStatement
  1398.                 if(executePreparedStatement){
  1399.                     pstmt.executeUpdate();
  1400.                     pstmt.close();
  1401.                 }
  1402.                 else{
  1403.                     //System.out.println("UPDATE ["+query.toString()+"] 1["+nodoOpenSPCoop+"] 2["+this.idBusta+"] 3["+tipoMessaggio+"]");
  1404.                     stateMsg.getPreparedStatement().put("UPDATE aggiornaProprietarioMessaggioOpenSPCoop "+this.tipo+"/"+this.idBusta,pstmt);
  1405.                 }

  1406.                 // Add Proprietario into table
  1407.                 this.addProprietarioIntoTable(this.tipo, this.idBusta, nodoOpenSPCoop);

  1408.             } catch(Exception e) {
  1409.                 String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento proprietario Messaggio "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  1410.                 try{
  1411.                     if(pstmt != null)
  1412.                         pstmt.close();
  1413.                 } catch(Exception er) {
  1414.                     // close
  1415.                 }
  1416.                 this.log.error(errorMsg,e);
  1417.                 throw new GestoreMessaggiException(errorMsg,e);
  1418.             }
  1419.         }

  1420.         if(TimerGestoreMessaggi.ID_MODULO.equals(nodoOpenSPCoop)){
  1421.             this.deleted = true;
  1422.         }
  1423.     }

  1424.     /**
  1425.      * Aggiorna lo stato di un messaggio gestito da OpenSPCoop, configurando l'ID del campo riferimento messaggio di una busta gestita
  1426.      *
  1427.      * @param riferimentoMessaggio Riferimento Messaggio di una busta gestita
  1428.      *
  1429.      */
  1430.     public void aggiornaRiferimentoMessaggio(String riferimentoMessaggio)throws GestoreMessaggiException{
  1431.         this.aggiornaRiferimentoMessaggio(riferimentoMessaggio, false);
  1432.     }
  1433.     public void aggiornaRiferimentoMessaggio(String riferimentoMessaggio,boolean saveIntoDB)throws GestoreMessaggiException{

  1434.         if((this.openspcoopstate instanceof OpenSPCoopStateful) || saveIntoDB) {
  1435.             StateMessage state = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  1436.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  1437.             Connection connectionDB = state.getConnectionDB();

  1438.             PreparedStatement pstmt = null;
  1439.             try{    

  1440.                 // Costruzione Query
  1441.                 StringBuilder query = new StringBuilder();
  1442.                 query.append("UPDATE ");
  1443.                 query.append(GestoreMessaggi.MESSAGGI);
  1444.                 query.append(" SET RIFERIMENTO_MSG=? WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  1445.                 pstmt = connectionDB.prepareStatement(query.toString());
  1446.                 pstmt.setString(1,riferimentoMessaggio);
  1447.                 pstmt.setString(2,this.idBusta);
  1448.                 pstmt.setString(3,this.tipo);

  1449.                 // Add PreparedStatement
  1450.                 state.getPreparedStatement().put("UPDATE aggiornaRiferimentoMessaggioOpenSPCoop "+this.tipo+"/"+this.idBusta,pstmt);

  1451.                 // add in cache
  1452.                 if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){
  1453.                     try{
  1454.                         this.msgDiag.highDebug("Aggiornamento riferimentoMessaggio per ["+this.tipo+"/"+riferimentoMessaggio+"] a ["+this.idBusta+"] ...");
  1455.                         GestoreMessaggi.addIntoCache_MappingRifMsgToId(this.msgDiag,this.tipo,riferimentoMessaggio,this.idBusta);
  1456.                         this.msgDiag.highDebug("Aggiornamento riferimentoMessaggio per ["+this.tipo+"/"+riferimentoMessaggio+"] a ["+this.idBusta+"] effettuata.");
  1457.                     }catch(Exception e){
  1458.                         this.msgDiag.logErroreGenerico(e,"GestoreMessaggi.addIntoCache_MappingRifMsgToId(Per:"+this.tipo+"/"+riferimentoMessaggio+",Value:"+this.idBusta+"");
  1459.                     }
  1460.                 }

  1461.             } catch(Exception e) {
  1462.                 String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento riferimento messaggio "+this.tipo+"/"+this.idBusta+": "+e.getMessage();        
  1463.                 try{
  1464.                     if(pstmt != null)
  1465.                         pstmt.close();
  1466.                 } catch(Exception er) {
  1467.                     // close
  1468.                 }
  1469.                 this.log.error(errorMsg,e);
  1470.                 throw new GestoreMessaggiException(errorMsg,e);
  1471.             }
  1472.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  1473.             // NOP
  1474.         }else{
  1475.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido"); //cambiare la firma ?
  1476.         }
  1477.     }


  1478.     /**
  1479.      * Aggiorna lo stato di un messaggio gestito da OpenSPCoop, configurando il motivo di un eventuale errore verificatosi
  1480.      * durante la gestione del messaggio stesso.
  1481.      *
  1482.      * @param motivoErrore Motivo dell'errore
  1483.      *
  1484.      */
  1485.     public void aggiornaErroreProcessamentoMessaggio(String motivoErrore,String servizioApplicativo) throws GestoreMessaggiException{
  1486.         aggiornaErroreProcessamentoMessaggio(motivoErrore, servizioApplicativo, true);
  1487.     }
  1488.     public boolean aggiornaErroreProcessamentoMessaggio(String motivoErrore,String servizioApplicativo, boolean throwExceptionConnectionNull) throws GestoreMessaggiException{

  1489.         if( (this.openspcoopstate instanceof OpenSPCoopStateful) || this.oneWayVersione11) {
  1490.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  1491.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  1492.             Connection connectionDB = stateMSG.getConnectionDB();

  1493.             if(connectionDB==null) {
  1494.                 if(throwExceptionConnectionNull) {
  1495.                     throw new GestoreMessaggiException("Connessione non disponibile");
  1496.                 }
  1497.                 else {
  1498.                     return false;
  1499.                 }
  1500.             }
  1501.            
  1502.             String motivoErroreGiaRegistrato = this.getErroreProcessamentoMessaggio(servizioApplicativo);
  1503.             String prefix = "";
  1504.             if(motivoErroreGiaRegistrato!=null &&
  1505.                 motivoErroreGiaRegistrato.startsWith(GestoreMessaggi.NUMERO_RISPEDIZIONE)){
  1506.                 int index =  motivoErroreGiaRegistrato.indexOf("]");
  1507.                 prefix = motivoErroreGiaRegistrato.substring(0,(index+2));
  1508.                 motivoErroreGiaRegistrato = motivoErroreGiaRegistrato.substring(index+2);
  1509.             }

  1510.             // aggiorno il motivo dell'errore solo se ho un errore diverso da quanto e' capitato precedentemente
  1511.             // o se non avevo ancora registrato un errore.
  1512.             if(motivoErroreGiaRegistrato==null ||
  1513.                     (motivoErroreGiaRegistrato.equals(motivoErrore)==false)){

  1514.                 PreparedStatement pstmt = null;
  1515.                 try{    

  1516.                     // Costruzione Query
  1517.                     StringBuilder query = new StringBuilder();
  1518.                     query.append("UPDATE ");
  1519.                     if(servizioApplicativo==null) {
  1520.                         query.append(GestoreMessaggi.MESSAGGI);
  1521.                         query.append(" SET ERRORE_PROCESSAMENTO=? WHERE ID_MESSAGGIO = ?");
  1522.                     }else {
  1523.                         query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  1524.                         query.append(" SET ERRORE_PROCESSAMENTO=?, ERRORE_PROCESSAMENTO_COMPACT=? WHERE ID_MESSAGGIO = ?");
  1525.                     }
  1526.                     if(servizioApplicativo!=null)
  1527.                         query.append(" AND SERVIZIO_APPLICATIVO=?");
  1528.                     else
  1529.                         query.append(" AND TIPO=?");
  1530.                     pstmt = connectionDB.prepareStatement(query.toString());
  1531.                     int index = 1;
  1532.                     this.log.debug("UPDATE ERRORE PROCESSAMENTO TIPO-1 ["+prefix+"]["+motivoErrore+"] tipo["+this.tipo+"] sa["+servizioApplicativo+"]");
  1533.                     pstmt.setString(index++,prefix+motivoErrore);
  1534.                     if(servizioApplicativo!=null) {
  1535.                         if(motivoErrore!=null && motivoErrore.length()>=200) { // per evitare anche caratteri strani che occupano maggiore spazio
  1536.                             pstmt.setString(index++,motivoErrore.substring(0, 200)+" ...");
  1537.                         }
  1538.                         else {
  1539.                             pstmt.setString(index++,motivoErrore);
  1540.                         }
  1541.                     }
  1542.                     pstmt.setString(index++,this.idBusta);
  1543.                     if(servizioApplicativo!=null)
  1544.                         pstmt.setString(index++,servizioApplicativo);
  1545.                     else
  1546.                         pstmt.setString(index++,this.tipo);

  1547.                     pstmt.execute();
  1548.                     pstmt.close();

  1549.                 } catch(Exception e) {
  1550.                     String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento errore processamento messaggio "+this.tipo+"/"+this.idBusta+" sa["+servizioApplicativo+"]: "+e.getMessage();      
  1551.                     try{
  1552.                         if(pstmt != null)
  1553.                             pstmt.close();
  1554.                     } catch(Exception er) {
  1555.                         // close
  1556.                     }
  1557.                     this.log.error(errorMsg,e);
  1558.                     throw new GestoreMessaggiException(errorMsg,e);
  1559.                 }
  1560.             }
  1561.            
  1562.             return true;
  1563.            
  1564.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  1565.             //NOP
  1566.             return false;
  1567.         }else{
  1568.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  1569.         }
  1570.     }

  1571.     public void aggiungiMessaggioSerializzato(IJDBCAdapter adapter,byte [] msgByte) throws GestoreMessaggiException {

  1572.         StateMessage stateMsg = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  1573.                 : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  1574.         Connection connectionDB = stateMsg.getConnectionDB();


  1575.         PreparedStatement pstmt = null;
  1576.         try{    

  1577.             // Costruzione Query
  1578.             StringBuilder query = new StringBuilder();
  1579.             query.append("UPDATE ");
  1580.             query.append(GestoreMessaggi.MESSAGGI);
  1581.             query.append(" SET msg_bytes=? WHERE id_messaggio= ? and tipo= ?");



  1582.             pstmt = connectionDB.prepareStatement(query.toString());
  1583.             adapter.setBinaryData(pstmt,1,msgByte);
  1584.             pstmt.setString(2,this.idBusta);
  1585.             pstmt.setString(3, this.tipo);


  1586.             // Add PreparedStatement
  1587.             stateMsg.getPreparedStatement().put("UPDATE aggiungiMessaggioSerializzatoInMessaggioOpenSPCoop "+this.tipo+"/"+this.idBusta,pstmt);
  1588.         }catch (Exception e){      
  1589.             String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento errore processamento messaggio "+this.tipo+"/"+this.idBusta+" "+e.getMessage();        
  1590.             try{
  1591.                 if(pstmt != null)
  1592.                     pstmt.close();
  1593.             } catch(Exception er) {
  1594.                 // close
  1595.             }
  1596.             this.log.error(errorMsg,e);
  1597.             throw new GestoreMessaggiException(errorMsg,e);
  1598.         }

  1599.     }

  1600.     public void ripristinaMessaggio() throws GestoreMessaggiException {

  1601.         StateMessage stateMsg = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  1602.                 : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  1603.         Connection connectionDB = stateMsg.getConnectionDB();
  1604.         PreparedStatement pstmt = null;

  1605.         String sql = "UPDATE MESSAGGI SET scheduling=0 where id_messaggio=? AND tipo=?";

  1606.         try {
  1607.             pstmt = connectionDB.prepareStatement(sql);
  1608.             pstmt.setString(1,this.idBusta);
  1609.             pstmt.setString(2,this.tipo);
  1610.             pstmt.execute();
  1611.         }catch (Exception e){      
  1612.             String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento errore processamento messaggio "+this.tipo+"/"+this.idBusta+" "+e.getMessage();        
  1613.             this.log.error(errorMsg,e);
  1614.             throw new GestoreMessaggiException(errorMsg,e);
  1615.         }finally {
  1616.             try{
  1617.                 if(pstmt != null)
  1618.                     pstmt.close();
  1619.             } catch(Exception er) {
  1620.                 // close
  1621.             }
  1622.         }
  1623.     }









  1624.     public static final String NUMERO_RISPEDIZIONE = "[spedizione n.";

  1625.     /**
  1626.      * Aggiorna la data di rispedizione di un messaggio gestito da OpenSPCoop.
  1627.      *
  1628.      * @param dataRispedizione Data di rispedizione
  1629.      *
  1630.      */
  1631.     public void aggiornaDataRispedizione(java.sql.Timestamp dataRispedizione,String servizioApplicativo)throws GestoreMessaggiException{

  1632.         if( (this.openspcoopstate instanceof OpenSPCoopStateful) || this.oneWayVersione11) {
  1633.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  1634.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  1635.             Connection connectionDB = stateMSG.getConnectionDB();

  1636.             String motivoErroreGiaRegistrato = this.getErroreProcessamentoMessaggio(servizioApplicativo);

  1637.             PreparedStatement pstmt = null;
  1638.             try{    
  1639.                 boolean updateErroreProcessamento = true;
  1640.                
  1641.                 int numeroSpedizione = 0;
  1642.                 // Costruzione numero rispedizione
  1643.                 if(motivoErroreGiaRegistrato==null){
  1644.                     motivoErroreGiaRegistrato = GestoreMessaggi.NUMERO_RISPEDIZIONE + "1] ";
  1645.                     numeroSpedizione = 1;
  1646.                 }else{
  1647.                     if( motivoErroreGiaRegistrato.startsWith(GestoreMessaggi.NUMERO_RISPEDIZIONE) == false ){
  1648.                         motivoErroreGiaRegistrato = GestoreMessaggi.NUMERO_RISPEDIZIONE + "1] "+motivoErroreGiaRegistrato;
  1649.                         numeroSpedizione = 1 ;
  1650.                     }else{
  1651.                        
  1652.                         if(this.pddContext!=null && this.pddContext.containsKey(CostantiPdD.OPENSPCOOP2_PDD_CONTEXT_NUMERO_TENTATIVI_RICONSEGNA_UPDATED)) {
  1653.                             updateErroreProcessamento = false;
  1654.                             numeroSpedizione = (Integer) this.pddContext.getObject(CostantiPdD.OPENSPCOOP2_PDD_CONTEXT_NUMERO_TENTATIVI_RICONSEGNA_UPDATED);
  1655.                         }
  1656.                         if(updateErroreProcessamento) {
  1657.                             int indexNumber = motivoErroreGiaRegistrato.indexOf("]");
  1658.                             if(indexNumber == -1)
  1659.                                 throw new GestoreMessaggiException("Errore processamento corrotto (] non presente)");
  1660.                             try{
  1661.                                 StringBuilder bf = new StringBuilder();
  1662.                                 int j = indexNumber - 1;
  1663.                                 while( motivoErroreGiaRegistrato.charAt(j)!='.' ){
  1664.                                     bf.append(motivoErroreGiaRegistrato.charAt(j));
  1665.                                     j = j - 1;
  1666.                                 }
  1667.                                 bf.reverse();
  1668.                                 numeroSpedizione = Integer.parseInt(bf.toString());
  1669.                                 numeroSpedizione = numeroSpedizione+1;
  1670.                                 String oldMotivo = motivoErroreGiaRegistrato.substring(indexNumber+2);
  1671.                                 motivoErroreGiaRegistrato = GestoreMessaggi.NUMERO_RISPEDIZIONE + numeroSpedizione + "] "+oldMotivo;
  1672.                             }catch(Exception e){
  1673.                                 throw new GestoreMessaggiException("Aggiornamento numero spedizione non riuscito: "+e.getMessage(),e);
  1674.                             }
  1675.                         }
  1676.                     }
  1677.                 }

  1678.                 // incremento dataSpedizione
  1679.                 long spedizione = dataRispedizione.getTime();
  1680.                 if(this.propertiesReader.isRitardoConsegnaAbilitato() && numeroSpedizione>1){
  1681.                     long ritardoEsponenziale = this.propertiesReader.getRitardoConsegnaEsponenziale();
  1682.                     long ritardo = 1;
  1683.                     boolean moltiplicazione = this.propertiesReader.isRitardoConsegnaEsponenzialeConMoltiplicazione();
  1684.                     if(moltiplicazione==false)
  1685.                         ritardo = 0;
  1686.                     long limite = (numeroSpedizione-1);
  1687.                     if(limite > this.propertiesReader.getRitardoConsegnaEsponenzialeLimite())
  1688.                         limite = this.propertiesReader.getRitardoConsegnaEsponenzialeLimite();
  1689.                     for(int i=0; i<limite; i++){
  1690.                         if(moltiplicazione){
  1691.                             ritardo = ritardo * ritardoEsponenziale;
  1692.                         }
  1693.                         else{
  1694.                             ritardo = ritardo + ritardoEsponenziale;
  1695.                         }
  1696.                     }
  1697.                     spedizione = spedizione + (ritardo*1000);
  1698.                 }


  1699.                 // Costruzione Query
  1700.                 StringBuilder query = new StringBuilder();
  1701.                 query.append("UPDATE ");
  1702.                 if(servizioApplicativo!=null)
  1703.                     query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  1704.                 else
  1705.                     query.append(GestoreMessaggi.MESSAGGI);
  1706.                 query.append(" SET RISPEDIZIONE=?");
  1707.                 if(updateErroreProcessamento) {
  1708.                     query.append(", ERRORE_PROCESSAMENTO=?");
  1709.                 }
  1710.                 query.append(" WHERE  ID_MESSAGGIO = ?"); // non devo aggiornare ERRORE_PROCESSAMENTO_COMPACT poichè li non vi è l'informazione sulla rispedizione.
  1711.                 if(servizioApplicativo!=null)
  1712.                     query.append(" AND SERVIZIO_APPLICATIVO=?");
  1713.                 else
  1714.                     query.append(" AND TIPO=?");
  1715.                 pstmt = connectionDB.prepareStatement(query.toString());
  1716.                 Timestamp t = new Timestamp(spedizione);
  1717.                 int index = 1;
  1718.                 pstmt.setTimestamp(index++,t);
  1719.                 if(updateErroreProcessamento) {
  1720.                     this.log.debug("UPDATE ERRORE PROCESSAMENTO TIPO-2 ["+motivoErroreGiaRegistrato+"] tipo["+this.tipo+"] sa["+servizioApplicativo+"]");
  1721.                     pstmt.setString(index++,motivoErroreGiaRegistrato);
  1722.                 }
  1723.                 pstmt.setString(index++,this.idBusta);
  1724.                 if(servizioApplicativo!=null)
  1725.                     pstmt.setString(index++,servizioApplicativo);
  1726.                 else
  1727.                     pstmt.setString(index++,this.tipo);

  1728.                 /*
  1729.             if(servizioApplicativo!=null)
  1730.                 this.log.debug("[aggiornaDataRispedizione SA("+servizioApplicativo+")] Aggiorno MSG["+this.tipo+"/"+this.idBusta+"] RISPEDIZIONE["+t.toString()+"]");
  1731.             else
  1732.                 this.log.debug("[aggiornaDataRispedizione] Aggiorno MSG["+this.tipo+"/"+this.idBusta+"] RISPEDIZIONE["+t.toString()+"]");
  1733.                  */

  1734.                 pstmt.execute();
  1735.                 pstmt.close();
  1736.                
  1737.                 if(updateErroreProcessamento) {
  1738.                     if(this.pddContext!=null) {
  1739.                         this.pddContext.addObject(CostantiPdD.OPENSPCOOP2_PDD_CONTEXT_NUMERO_TENTATIVI_RICONSEGNA_UPDATED, numeroSpedizione);
  1740.                     }
  1741.                 }

  1742.             } catch(Exception e) {
  1743.                 String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento data rispedizione Messaggio "+this.tipo+"/"+this.idBusta+" sa["+servizioApplicativo+"]: "+e.getMessage();      
  1744.                 try{
  1745.                     if(pstmt != null)
  1746.                         pstmt.close();
  1747.                 } catch(Exception er) {
  1748.                     // close
  1749.                 }
  1750.                 this.log.error(errorMsg,e);
  1751.                 throw new GestoreMessaggiException(errorMsg,e);
  1752.             }
  1753.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  1754.             //NOP
  1755.         }else{
  1756.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  1757.         }
  1758.     }

  1759.     /**
  1760.      * Aggiorna l'id JMS di un messaggio ricevuto da un nodo di OpenSPCoop.
  1761.      *
  1762.      * @param nodoOpenSPCoop  Nodo OpenSPCoop che ha ricevuto il messaggio
  1763.      * @param idHeaderJMS Identificativo JMS del messaggio ricevuto
  1764.      *
  1765.      */
  1766.     public void aggiornaIDHeaderJMS(String nodoOpenSPCoop,String idHeaderJMS) throws GestoreMessaggiException{
  1767.         aggiornaIDHeaderJMS(nodoOpenSPCoop,idHeaderJMS,null);
  1768.     }
  1769.     /**
  1770.      * Aggiorna l'id JMS di un messaggio ricevuto da un nodo di OpenSPCoop.
  1771.      *
  1772.      * @param nodoOpenSPCoop  Nodo OpenSPCoop che ha ricevuto il messaggio
  1773.      * @param idHeaderJMS Identificativo JMS del messaggio ricevuto
  1774.      * @param servizioApplicativo Servizio Applicativo utilizzato come chiave insieme all'idBusta
  1775.      *
  1776.      */
  1777.     public void aggiornaIDHeaderJMS(String nodoOpenSPCoop,String idHeaderJMS,String servizioApplicativo) throws GestoreMessaggiException{
  1778.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  1779.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  1780.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  1781.             Connection connectionDB = stateful.getConnectionDB();
  1782.             PreparedStatement pstmt = null;
  1783.             try{    

  1784.                 // Costruzione Query
  1785.                 String query = null;
  1786.                 if( ConsegnaContenutiApplicativi.ID_MODULO.equals(nodoOpenSPCoop)  ){
  1787.                     query = "UPDATE "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" SET "+getColonnaSQL(nodoOpenSPCoop)+
  1788.                             "=? WHERE  ID_MESSAGGIO = ? AND SERVIZIO_APPLICATIVO=?";
  1789.                 }else{
  1790.                     query = "UPDATE "+GestoreMessaggi.MESSAGGI+" SET "+getColonnaSQL(nodoOpenSPCoop)+"=? WHERE  ID_MESSAGGIO = ? AND TIPO=?";
  1791.                 }
  1792.                 pstmt = connectionDB.prepareStatement(query);
  1793.                 pstmt.setString(1,idHeaderJMS);
  1794.                 pstmt.setString(2,this.idBusta);
  1795.                 if( ConsegnaContenutiApplicativi.ID_MODULO.equals(nodoOpenSPCoop)  )
  1796.                     pstmt.setString(3,servizioApplicativo);
  1797.                 else
  1798.                     pstmt.setString(3,this.tipo);
  1799.                 pstmt.execute();
  1800.                 pstmt.close();

  1801.             } catch(Exception e) {
  1802.                 String errorMsg = "GESTORE_MESSAGGI, Errore di aggiornamento IDHeaderJMS "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  1803.                 try{
  1804.                     if(pstmt != null)
  1805.                         pstmt.close();
  1806.                 } catch(Exception er) {
  1807.                     // close
  1808.                 }
  1809.                 this.log.error(errorMsg,e);
  1810.                 throw new GestoreMessaggiException(errorMsg,e);
  1811.             }
  1812.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  1813.             //NOP
  1814.         }else{
  1815.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  1816.         }
  1817.     }













  1818.     /* ********  R E A D    M E S S A G E   (Gestione Transazione Interna di OpenSPCoop) ******** */


  1819.     /**
  1820.      * Ritorna il proprietario (nodo OpenSPCoop) di un messaggio gestito da OpenSPCoop.
  1821.      * La lettura del proprietario viene effettuata in Serializable Level
  1822.      *
  1823.      * @param attesaAttiva AttesaAttiva per la gestione del livello di serializable
  1824.      * @param checkInterval Intervallo di check per la gestione  del livello di serializable
  1825.      * @return il proprietario di un messaggio
  1826.      *
  1827.      */
  1828.     public String getProprietario_SerializableRead(String idModulo,long attesaAttiva,int checkInterval) throws GestoreMessaggiException{
  1829.         return getProprietario(idModulo,true,attesaAttiva,checkInterval,false);
  1830.     }
  1831.     /**
  1832.      * Ritorna il proprietario (nodo OpenSPCoop) di un messaggio gestito da OpenSPCoop.
  1833.      * La lettura del proprietario viene effettuata in Serializable Level
  1834.      *
  1835.      * @param attesaAttiva AttesaAttiva per la gestione del livello di serializable
  1836.      * @param checkInterval Intervallo di check per la gestione  del livello di serializable
  1837.      * @return il proprietario di un messaggio
  1838.      *
  1839.      */
  1840.     public String getProprietario_SerializableRead(String idModulo,long attesaAttiva,int checkInterval,boolean onlyCache) throws GestoreMessaggiException{
  1841.         return getProprietario(idModulo,true,attesaAttiva,checkInterval,onlyCache);
  1842.     }
  1843.     /**
  1844.      * Ritorna il proprietario (nodo OpenSPCoop) di un messaggio gestito da OpenSPCoop.
  1845.      *
  1846.      * @return il proprietario di un messaggio
  1847.      *
  1848.      */
  1849.     public String getProprietario(String idModulo) throws GestoreMessaggiException{
  1850.         return getProprietario(idModulo,false,-1,-1,false);
  1851.     }
  1852.     /**
  1853.      * Ritorna il proprietario (nodo OpenSPCoop) di un messaggio gestito da OpenSPCoop.
  1854.      *
  1855.      * @return il proprietario di un messaggio
  1856.      *
  1857.      */
  1858.     public String getProprietario(String idModulo,boolean onlyCache) throws GestoreMessaggiException{
  1859.         return getProprietario(idModulo,false,-1,-1,onlyCache);
  1860.     }
  1861.     /**
  1862.      * Ritorna il proprietario (nodo OpenSPCoop) di un messaggio gestito da OpenSPCoop.
  1863.      *
  1864.      * @param serializable Indicazione se la ricerca deve avvenire in serializable mode
  1865.      * @param attesaAttiva AttesaAttiva per la gestione del livello di serializable
  1866.      * @param checkInterval Intervallo di check per la gestione  del livello di serializable
  1867.      * @return il proprietario di un messaggio
  1868.      *
  1869.      */
  1870.     private String getProprietario(String idModulo,boolean serializable,long attesaAttiva,int checkInterval,boolean onlyCache) throws GestoreMessaggiException{

  1871.         if ( (this.openspcoopstate instanceof OpenSPCoopStateless) && (this.oneWayVersione11==false) ) {
  1872.             return (this.isRichiesta) ? ((OpenSPCoopStateless)this.openspcoopstate).getDestinatarioRequestMsgLib()
  1873.                     : ((OpenSPCoopStateless)this.openspcoopstate).getDestinatarioResponseMsgLib();
  1874.         }
  1875.         else if ( (this.openspcoopstate instanceof OpenSPCoopStateful) || (this.oneWayVersione11)) {

  1876.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  1877.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  1878.             Connection connectionDB = stateMSG.getConnectionDB();

  1879.             if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){

  1880.                 try{
  1881.                     // get from cache
  1882.                     this.msgDiag.highDebug("getProprietario, read from cache...");
  1883.                     String proprietario = GestoreMessaggi.getFromCache_Proprietario(idModulo,this.tipo,this.idBusta);
  1884.                     if(proprietario!=null)
  1885.                         return proprietario;
  1886.                     else{
  1887.                         if(onlyCache){
  1888.                             return null;
  1889.                         }
  1890.                     }
  1891.                 }catch(Exception e){
  1892.                     String errorMsg = "GESTORE_MESSAGGI, error getProprietario (Cache) "+this.tipo+"/"+this.idBusta+": "+e.getMessage();        
  1893.                     this.log.error(errorMsg,e);
  1894.                     throw new GestoreMessaggiException(errorMsg,e);
  1895.                 }

  1896.             }

  1897.             this.msgDiag.highDebug("getProprietario, read from DB...");


  1898.             if(serializable == false){
  1899.                 // NON SERIALIZABLE MODE

  1900.                 PreparedStatement pstmt = null;
  1901.                 ResultSet rs = null;
  1902.                 String value = null;
  1903.                 try{
  1904.                     String query = "SELECT PROPRIETARIO FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO=? AND TIPO=?";
  1905.                     //log.debug("Query: "+query);
  1906.                     pstmt = connectionDB.prepareStatement(query);
  1907.                     pstmt.setString(1,this.idBusta);
  1908.                     pstmt.setString(2,this.tipo);
  1909.                     rs = pstmt.executeQuery();      
  1910.                     if(rs.next()){
  1911.                         value = rs.getString("PROPRIETARIO");
  1912.                     }
  1913.                     rs.close();
  1914.                     pstmt.close();
  1915.                 } catch(Exception e) {
  1916.                     try{
  1917.                         if(rs != null)
  1918.                             rs.close();
  1919.                     } catch(Exception er) {
  1920.                         // close
  1921.                     }
  1922.                     try{
  1923.                         if(pstmt != null)
  1924.                             pstmt.close();
  1925.                     } catch(Exception er) {
  1926.                         // close
  1927.                     }
  1928.                 }
  1929.                 return value;

  1930.             }else{

  1931.                 // SERIALIZABLE MODE

  1932.                 /*
  1933.           Viene realizzato con livello di isolamento SERIALIZABLE, per essere sicuri
  1934.           che esecuzioni parallele non leggano dati inconsistenti.
  1935.           Con il livello SERIALIZABLE, se ritorna una eccezione, deve essere riprovato
  1936.           La sincronizzazione e' necessaria per via del possibile accesso simultaneo del servizio Gop
  1937.           e del servizio che si occupa di eliminare destinatari di messaggi
  1938.                  */
  1939.                 // setAutoCommit e livello Isolamento
  1940.                 int oldTransactionIsolation = -1;
  1941.                 try{
  1942.                     oldTransactionIsolation = connectionDB.getTransactionIsolation();
  1943.                     connectionDB.setAutoCommit(false);
  1944.                     JDBCUtilities.setTransactionIsolationSerializable(this.propertiesReader.getDatabaseType(), connectionDB);
  1945.                 } catch(Exception er) {
  1946.                     String errorMsg = "GESTORE_MESSAGGI, Errore getProprietario Messaggio(setIsolation) "+this.tipo+"/"+this.idBusta+": "+er.getMessage();      
  1947.                     this.log.error(errorMsg,er);
  1948.                     throw new GestoreMessaggiException(errorMsg,er);
  1949.                 }

  1950.                 PreparedStatement pstmt = null;
  1951.                 ResultSet rs = null;
  1952.                 boolean getProprietarioOK = false;
  1953.                 String value = null;

  1954.                 long scadenzaWhile = DateManager.getTimeMillis() + attesaAttiva;

  1955.                 while(getProprietarioOK==false && DateManager.getTimeMillis() < scadenzaWhile){

  1956.                     try{    
  1957.                         // Costruzione Query
  1958.                         String query = "SELECT PROPRIETARIO FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO=? AND TIPO=? FOR UPDATE";
  1959.                         //log.debug("Query: "+query);
  1960.                         pstmt = connectionDB.prepareStatement(query);
  1961.                         pstmt.setString(1,this.idBusta);
  1962.                         pstmt.setString(2,this.tipo);
  1963.                         rs = pstmt.executeQuery();      
  1964.                         if(rs.next()){
  1965.                             value = rs.getString("PROPRIETARIO");
  1966.                         }
  1967.                         rs.close();
  1968.                         pstmt.close();

  1969.                         // Chiusura Transazione
  1970.                         connectionDB.commit();

  1971.                         // ID Costruito
  1972.                         getProprietarioOK = true;

  1973.                     } catch(Exception e) {
  1974.                         try{
  1975.                             if(rs != null)
  1976.                                 rs.close();
  1977.                         } catch(Exception er) {
  1978.                             // close
  1979.                         }
  1980.                         try{
  1981.                             if(pstmt != null)
  1982.                                 pstmt.close();
  1983.                         } catch(Exception er) {
  1984.                             // close
  1985.                         }
  1986.                         try{
  1987.                             connectionDB.rollback();
  1988.                         } catch(Exception er) {
  1989.                             // ignore
  1990.                         }
  1991.                     }

  1992.                     if(getProprietarioOK == false){
  1993.                         // Per aiutare ad evitare conflitti
  1994.                         try{
  1995.                             Utilities.sleep((getRandom()).nextInt(checkInterval)); // random da 0ms a checkIntervalms
  1996.                         }catch(Exception eRandom){
  1997.                             // ignore
  1998.                         }
  1999.                     }
  2000.                 }
  2001.                 // Ripristino Transazione
  2002.                 try{
  2003.                     connectionDB.setTransactionIsolation(oldTransactionIsolation);
  2004.                     connectionDB.setAutoCommit(true);
  2005.                     stateMSG.updateConnection(connectionDB);
  2006.                 } catch(Exception er) {
  2007.                     String errorMsg = "GESTORE_MESSAGGI, Errore getProprietario Messaggio(ripristinoIsolation) "+this.tipo+"/"+this.idBusta+": "+er.getMessage();      
  2008.                     this.log.error(errorMsg,er);
  2009.                     throw new GestoreMessaggiException(errorMsg,er);

  2010.                 }
  2011.                 return value;
  2012.             }
  2013.         }else{
  2014.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2015.         }
  2016.     }


  2017.     /**
  2018.      * Ritorna l'id JMS di un messaggio ricevuto da un nodo di OpenSPCoop.
  2019.      *
  2020.      * @param nodoOpenSPCoop  Nodo OpenSPCoop desiderato
  2021.      *
  2022.      */
  2023.     public String getIDJMSRicevuto(String nodoOpenSPCoop) throws GestoreMessaggiException{
  2024.         return getIDJMSRicevuto(nodoOpenSPCoop,null);
  2025.     }
  2026.     /**
  2027.      * Ritorna l'id JMS di un messaggio ricevuto da un nodo di OpenSPCoop.
  2028.      *
  2029.      * @param nodoOpenSPCoop  Nodo OpenSPCoop desiderato
  2030.      * @param servizioApplicativo Servizio Applicativo utilizzato come chiave insieme all'id
  2031.      *
  2032.      */
  2033.     public String getIDJMSRicevuto(String nodoOpenSPCoop,String servizioApplicativo) throws GestoreMessaggiException{
  2034.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  2035.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  2036.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  2037.             Connection connectionDB = stateful.getConnectionDB();
  2038.             PreparedStatement pstmt = null;
  2039.             ResultSet rs = null;
  2040.             try{    
  2041.                 // Costruzione Query
  2042.                 String query = null;
  2043.                 if( ConsegnaContenutiApplicativi.ID_MODULO.equals(nodoOpenSPCoop)  ){
  2044.                     query = "SELECT "+getColonnaSQL(nodoOpenSPCoop)+" FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+
  2045.                             " WHERE ID_MESSAGGIO=? AND SERVIZIO_APPLICATIVO=?";
  2046.                 }else{
  2047.                     query = "SELECT "+getColonnaSQL(nodoOpenSPCoop)+" FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO=? AND TIPO=?";
  2048.                 }
  2049.                 //log.debug("Query: "+query);
  2050.                 pstmt = connectionDB.prepareStatement(query);
  2051.                 pstmt.setString(1,this.idBusta);
  2052.                 if( ConsegnaContenutiApplicativi.ID_MODULO.equals(nodoOpenSPCoop)  )
  2053.                     pstmt.setString(2,servizioApplicativo);
  2054.                 else
  2055.                     pstmt.setString(2,this.tipo);
  2056.                 rs = pstmt.executeQuery();
  2057.                 String value = null;
  2058.                 if(rs.next()){
  2059.                     value = rs.getString(getColonnaSQL(nodoOpenSPCoop));
  2060.                 }
  2061.                 rs.close();
  2062.                 pstmt.close();

  2063.                 return value;

  2064.             } catch(Exception e) {
  2065.                 String errorMsg = "GESTORE_MESSAGGI, Errore get IDHeaderJMS "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  2066.                 try{
  2067.                     if(rs != null)
  2068.                         rs.close();
  2069.                 } catch(Exception er) {
  2070.                     // close
  2071.                 }
  2072.                 try{
  2073.                     if(pstmt != null)
  2074.                         pstmt.close();
  2075.                 } catch(Exception er) {
  2076.                     // close
  2077.                 }
  2078.                 this.log.error(errorMsg,e);
  2079.                 throw new GestoreMessaggiException(errorMsg,e);
  2080.             }  
  2081.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  2082.             //          //TODO Metodo stateful only
  2083.             //          return null;
  2084.         }else{
  2085.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2086.         }
  2087.     }

















  2088.     /* ********  R E A D    M E S S A G E   ******** */
  2089.     /**
  2090.      * Ritorna true se il messaggi risulta gia' registrato
  2091.      *
  2092.      * @return true se il  messaggio risulta gia' registrato
  2093.      * @throws GestoreMessaggiException
  2094.      *
  2095.      */
  2096.     public boolean existsMessage_onlyCache(boolean searchForRiferimentoMsg) throws GestoreMessaggiException{
  2097.         return existsMessage_engine(searchForRiferimentoMsg,true,false);
  2098.     }

  2099.     /**
  2100.      * Ritorna true se il messaggi risulta gia' registrato
  2101.      *
  2102.      * @return true se il  messaggio risulta gia' registrato
  2103.      * @throws GestoreMessaggiException
  2104.      *
  2105.      */
  2106.     public boolean existsMessage_onlyCache() throws GestoreMessaggiException{
  2107.         return existsMessage_engine(false,true,false);
  2108.     }

  2109.     /**
  2110.      * Ritorna true se il messaggi risulta gia' registrato
  2111.      *
  2112.      * @return true se il  messaggio risulta gia' registrato
  2113.      * @throws GestoreMessaggiException
  2114.      *
  2115.      */
  2116.     public boolean existsMessage_noCache(boolean searchForRiferimentoMsg) throws GestoreMessaggiException{
  2117.         return existsMessage_engine(searchForRiferimentoMsg,false,true);
  2118.     }

  2119.     /**
  2120.      * Ritorna true se il messaggi risulta gia' registrato
  2121.      *
  2122.      * @return true se il  messaggio risulta gia' registrato
  2123.      * @throws GestoreMessaggiException
  2124.      *
  2125.      */
  2126.     public boolean existsMessage_noCache() throws GestoreMessaggiException{
  2127.         return existsMessage_engine(false,false,true);
  2128.     }

  2129.     /**
  2130.      * Ritorna true se il messaggi risulta gia' registrato
  2131.      *
  2132.      * @return true se il  messaggio risulta gia' registrato
  2133.      * @throws GestoreMessaggiException
  2134.      *
  2135.      */
  2136.     public boolean existsMessage(boolean searchForRiferimentoMsg) throws GestoreMessaggiException{
  2137.         return existsMessage_engine(searchForRiferimentoMsg,false,false);
  2138.     }

  2139.     /**
  2140.      * Ritorna true se il messaggi risulta gia' registrato
  2141.      *
  2142.      * @return true se il  messaggio risulta gia' registrato
  2143.      * @throws GestoreMessaggiException
  2144.      *
  2145.      */
  2146.     public boolean existsMessage() throws GestoreMessaggiException{
  2147.         return existsMessage_engine(false,false,false);
  2148.     }

  2149.     /**
  2150.      * Ritorna true se il messaggi risulta gia' registrato
  2151.      *
  2152.      * @return true se il  messaggio risulta gia' registrato
  2153.      * @throws GestoreMessaggiException
  2154.      *
  2155.      */
  2156.     private boolean existsMessage_engine(boolean searchForRiferimentoMsg,boolean onlyCache,boolean noCache) throws GestoreMessaggiException{

  2157.         if( (this.openspcoopstate instanceof OpenSPCoopStateless) &&
  2158.                 ( (this.oneWayVersione11==false) || (this.routingStateless)  ) ){
  2159.             return false; // il messaggio non viene mai salvato
  2160.         }



  2161.         StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  2162.                 : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  2163.         Connection connectionDB = stateMSG.getConnectionDB();


  2164.         // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  2165.         // come riferimento Messaggio l'ID del gestore.
  2166.         // In caso di esistenza uso l'ID del messaggio trovato e non quello del gestore
  2167.         String idBustaSearch = this.idBusta;
  2168.         if(searchForRiferimentoMsg){
  2169.             try{
  2170.                 idBustaSearch = mapRiferimentoIntoIDBusta();
  2171.             }catch(Exception e){
  2172.                 // ignore
  2173.             }
  2174.             //System.out.println("Cerco riferimento di id["+this.idBusta+"]: "+idBustaSearch);
  2175.             if(idBustaSearch==null){
  2176.                 return false;
  2177.             }
  2178.         }

  2179.         if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null && (noCache==false) ){

  2180.             try{
  2181.                 // get from cache
  2182.                 this.msgDiag.highDebug("existsMessage, read from cache ID["+idBustaSearch+"]...");
  2183.                 Object value = GestoreMessaggi.getFromCache_existsMessage(this.tipo,idBustaSearch);

  2184.                 if((value!=null) && (((Boolean)value)==true)){
  2185.                     return true;
  2186.                 }else{
  2187.                     if(onlyCache){
  2188.                         return false;
  2189.                     }
  2190.                 }
  2191.             }catch(Exception e){
  2192.                 String errorMsg = "GESTORE_MESSAGGI, error existsMessage (Cache) "+this.tipo+"/"+idBustaSearch+": "+e.getMessage();    
  2193.                 this.log.error(errorMsg,e);
  2194.                 return false;
  2195.             }

  2196.         }

  2197.         this.msgDiag.highDebug("existsMessage, read from DB ID["+idBustaSearch+"]...");

  2198.         PreparedStatement pstmt = null;
  2199.         ResultSet rs = null;
  2200.         try{    
  2201.             // Costruzione Query
  2202.             String query = "SELECT ID_MESSAGGIO FROM "+GestoreMessaggi.MESSAGGI+
  2203.                     " WHERE ID_MESSAGGIO=? AND TIPO=?";
  2204.             //log.debug("Query: "+query);
  2205.             pstmt = connectionDB.prepareStatement(query);
  2206.             pstmt.setString(1,idBustaSearch);
  2207.             pstmt.setString(2,this.tipo);
  2208.             rs = pstmt.executeQuery();
  2209.             if(rs.next()){
  2210.                 rs.close();
  2211.                 pstmt.close();
  2212.                 return true;
  2213.             }
  2214.             rs.close();
  2215.             pstmt.close();

  2216.             return false;

  2217.         } catch(Exception e) {
  2218.             String errorMsg = "GESTORE_MESSAGGI, Errore existsMessage "+this.tipo+"/"+idBustaSearch+": "+e.getMessage();        
  2219.             try{
  2220.                 if(rs != null)
  2221.                     rs.close();
  2222.             } catch(Exception er) {
  2223.                 // close
  2224.             }
  2225.             try{
  2226.                 if(pstmt != null)
  2227.                     pstmt.close();
  2228.             } catch(Exception er) {
  2229.                 // close
  2230.             }
  2231.             this.log.error(errorMsg,e);
  2232.             return false;
  2233.         }
  2234.     }


  2235.     /**
  2236.      * Ritorna il messaggio gestito da OpenSPCoop.
  2237.      *
  2238.      * @return il  messaggio
  2239.      *
  2240.      */
  2241.     public OpenSPCoop2Message getMessage() throws GestoreMessaggiException{
  2242.         return getMessage(null);
  2243.     }
  2244.     public OpenSPCoop2Message getMessage(Date oraRegistrazione) throws GestoreMessaggiException{
  2245.         return getMessage(false, oraRegistrazione);
  2246.     }

  2247.     /**
  2248.      * Ritorna il messaggio gestito da OpenSPCoop.
  2249.      *
  2250.      * @param searchForRiferimentoMsg Se true, il messaggio viene ricercato per Riferimento Messaggio
  2251.      * @return il  messaggio
  2252.      *
  2253.      */
  2254.     public OpenSPCoop2Message getMessage(boolean searchForRiferimentoMsg) throws GestoreMessaggiException{
  2255.         return getMessage(searchForRiferimentoMsg, null);
  2256.     }
  2257.     public OpenSPCoop2Message getMessage(boolean searchForRiferimentoMsg, Date oraRegistrazione) throws GestoreMessaggiException{

  2258.         //      if (openspcoopstate instanceof OpenSPCoopStateless) {
  2259.         //          if (isRichiesta) return ((OpenSPCoopStateless)openspcoopstate).getRichiestaMsg() ;
  2260.         //          else return ((OpenSPCoopStateless)openspcoopstate).getRispostaMsg() ;
  2261.         //      }

  2262.         OpenSPCoop2Message msg = null;

  2263.         // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  2264.         // come riferimento Messaggio l'ID del gestore.
  2265.         // In caso di esistenza uso l'ID del messaggio trovato e non quello del gestore
  2266.         String idBustaSearch = this.idBusta;
  2267.         if(searchForRiferimentoMsg){
  2268.             idBustaSearch = mapRiferimentoIntoIDBusta();
  2269.         }

  2270.         SavedMessage soapMsg = null;
  2271.         try{
  2272.             soapMsg = new SavedMessage(idBustaSearch, this.openspcoopstate, this.tipo,this.workDir,GestoreMessaggi.adapter,this.log);
  2273.             msg = soapMsg.read(this.isRichiesta, (this.portaDiTipoStateless || this.routingStateless), oraRegistrazione);
  2274.         }catch(Exception e){
  2275.             String errorMsg = "GESTORE_MESSAGGI, getMessage "+this.tipo+"/"+this.idBusta+": "+e.getMessage();
  2276.             this.log.error(errorMsg,e);
  2277.             throw new GestoreMessaggiException(errorMsg,e);
  2278.         }
  2279.         return msg;
  2280.     }

  2281.    
  2282.     public OpenSPCoop2Message getResponseMessage(boolean updateTransportRequest, boolean throwExceptionIfNotExists) throws GestoreMessaggiException{
  2283.         return getResponseMessage(null, updateTransportRequest, throwExceptionIfNotExists);
  2284.     }
  2285.     public OpenSPCoop2Message getResponseMessage(Date oraRegistrazione, boolean updateTransportRequest, boolean throwExceptionIfNotExists) throws GestoreMessaggiException{

  2286.         //      if (openspcoopstate instanceof OpenSPCoopStateless) {
  2287.         //          if (isRichiesta) return ((OpenSPCoopStateless)openspcoopstate).getRichiestaMsg() ;
  2288.         //          else return ((OpenSPCoopStateless)openspcoopstate).getRispostaMsg() ;
  2289.         //      }

  2290.         OpenSPCoop2Message msg = null;

  2291.         // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  2292.         // come riferimento Messaggio l'ID del gestore.
  2293.         // In caso di esistenza uso l'ID del messaggio trovato e non quello del gestore
  2294.         String idBustaSearch = this.idBusta;
  2295.        
  2296.         SavedMessage soapMsg = null;
  2297.         try{
  2298.             soapMsg = new SavedMessage(idBustaSearch, this.openspcoopstate, this.tipo,this.workDir,GestoreMessaggi.adapter,this.log);
  2299.             msg = soapMsg.readResponse(oraRegistrazione, throwExceptionIfNotExists);
  2300.         }catch(Exception e){
  2301.             String errorMsg = "GESTORE_MESSAGGI, getMessage "+this.tipo+"/"+this.idBusta+": "+e.getMessage();
  2302.             this.log.error(errorMsg,e);
  2303.             throw new GestoreMessaggiException(errorMsg,e);
  2304.         }
  2305.        
  2306.         try{
  2307.             if(updateTransportRequest) {
  2308.                 if(msg.getTransportResponseContext()!=null &&
  2309.                         msg.getTransportResponseContext().getHeaders()!=null &&
  2310.                         !msg.getTransportResponseContext().getHeaders().isEmpty()) {
  2311.                     if(msg.getTransportRequestContext()==null) {
  2312.                         msg.setTransportRequestContext(new TransportRequestContext());
  2313.                     }
  2314.                     if(msg.getTransportRequestContext().getHeaders()==null) {
  2315.                         msg.getTransportRequestContext().setHeaders(msg.getTransportResponseContext().getHeaders());
  2316.                     }
  2317.                     else if(msg.getTransportRequestContext().getHeaders().isEmpty()) {
  2318.                         msg.getTransportRequestContext().getHeaders().putAll(msg.getTransportResponseContext().getHeaders());
  2319.                     }
  2320.                     else {
  2321.                         for (String hdr : msg.getTransportResponseContext().getHeaders().keySet()) {
  2322.                             List<String> vResponse = msg.getTransportResponseContext().getHeaderValues(hdr);
  2323.                             if(vResponse!=null && !vResponse.isEmpty()){
  2324.                                 List<String> vRequest = msg.getTransportRequestContext().getHeaderValues(hdr);
  2325.                                 if(vRequest==null || vRequest.isEmpty()) {
  2326.                                     msg.getTransportRequestContext().getHeaders().put(hdr, vResponse);
  2327.                                 }
  2328.                                 else{
  2329.                                     for (String v : vResponse) {
  2330.                                         if(!vRequest.contains(v)) {
  2331.                                             vRequest.add(v);
  2332.                                         }
  2333.                                     }
  2334.                                 }
  2335.                             }
  2336.                         }
  2337.                     }
  2338.                 }
  2339.             }
  2340.         }catch(Exception e){
  2341.             String errorMsg = "GESTORE_MESSAGGI, getMessage "+this.tipo+"/"+this.idBusta+" (fixTransportRequest): "+e.getMessage();
  2342.             this.log.error(errorMsg,e);
  2343.             throw new GestoreMessaggiException(errorMsg,e);
  2344.         }
  2345.        
  2346.         return msg;
  2347.     }
  2348.    
  2349.     public Context getSyncTransactionContext() throws GestoreMessaggiException{
  2350.         return getSyncTransactionContext(null);
  2351.     }
  2352.     public Context getSyncTransactionContext(Date oraRegistrazione) throws GestoreMessaggiException{

  2353.         Context context = null;

  2354.         // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  2355.         // come riferimento Messaggio l'ID del gestore.
  2356.         // In caso di esistenza uso l'ID del messaggio trovato e non quello del gestore
  2357.         String idBustaSearch = this.idBusta;
  2358.        
  2359.         SavedMessage soapMsg = null;
  2360.         try{
  2361.             soapMsg = new SavedMessage(idBustaSearch, this.openspcoopstate, this.tipo,this.workDir,GestoreMessaggi.adapter,this.log);
  2362.             context = soapMsg.readTransactionContext(oraRegistrazione);
  2363.         }catch(Exception e){
  2364.             String errorMsg = "GESTORE_MESSAGGI, getSyncTransactionContext "+this.tipo+"/"+this.idBusta+": "+e.getMessage();
  2365.             this.log.error(errorMsg,e);
  2366.             throw new GestoreMessaggiException(errorMsg,e);
  2367.         }
  2368.                
  2369.         return context;
  2370.     }
  2371.    

  2372.     /**
  2373.      * Ritorna l'idBusta di un messaggio che possiede come riferimento messaggio l'ID del gestore.
  2374.      *
  2375.      * @return l'idBusta di un messaggio che possiede come riferimento messaggio l'ID del gestore in caso di esistenza del messaggio
  2376.      *         cercato, null altrimenti
  2377.      *
  2378.      */
  2379.     public String mapRiferimentoIntoIDBusta()throws GestoreMessaggiException{
  2380.         return mapRiferimentoIntoIDBusta(false);
  2381.     }

  2382.     /**
  2383.      * Ritorna l'idBusta di un messaggio che possiede come riferimento messaggio l'ID del gestore.
  2384.      *
  2385.      * @return l'idBusta di un messaggio che possiede come riferimento messaggio l'ID del gestore in caso di esistenza del messaggio
  2386.      *         cercato, null altrimenti
  2387.      *
  2388.      */
  2389.     public String mapRiferimentoIntoIDBusta(boolean onlyCache)throws GestoreMessaggiException{
  2390.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  2391.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  2392.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  2393.             Connection connectionDB = stateful.getConnectionDB();

  2394.             if(GestoreMessaggi.cacheMappingGestoreMessaggi!=null){

  2395.                 try{
  2396.                     // get from cache
  2397.                     this.msgDiag.highDebug("mapRiferimentoIntoIDBusta, read from cache ...");
  2398.                     String id = GestoreMessaggi.getFromCache_idFromRifMsgMapping(this.tipo,this.idBusta);
  2399.                     if(id!=null)
  2400.                         return id;
  2401.                     else{
  2402.                         if(onlyCache){
  2403.                             return null;
  2404.                         }
  2405.                     }
  2406.                 }catch(Exception e){
  2407.                     String errorMsg = "GESTORE_MESSAGGI, error mapRiferimentoIntoIDBusta (Cache) "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  2408.                     this.log.error(errorMsg,e);
  2409.                     throw new GestoreMessaggiException(errorMsg,e);
  2410.                 }

  2411.             }

  2412.             this.msgDiag.highDebug("mapRiferimentoIntoIDBusta, read from DB ...");

  2413.             PreparedStatement pstmt = null;
  2414.             ResultSet rs = null;
  2415.             try{    
  2416.                 // Costruzione Query
  2417.                 String query = "SELECT ID_MESSAGGIO FROM "+GestoreMessaggi.MESSAGGI+" WHERE RIFERIMENTO_MSG=? AND TIPO=? AND PROPRIETARIO IS NOT NULL AND PROPRIETARIO != ? ORDER BY ORA_REGISTRAZIONE DESC";
  2418.                 //log.debug("Query: "+query);
  2419.                 pstmt = connectionDB.prepareStatement(query);
  2420.                 pstmt.setString(1,this.idBusta);
  2421.                 pstmt.setString(2,this.tipo);
  2422.                 pstmt.setString(3,TimerGestoreMessaggi.ID_MODULO);
  2423.                 rs = pstmt.executeQuery();
  2424.                 String value = null;
  2425.                 if(rs.next()){
  2426.                     value = rs.getString("ID_MESSAGGIO");
  2427.                 }

  2428.                 //System.out.println("GET FROM DB RIFERIMENTO RIF["+this.tipo+"_"+this.idBusta+"] ID TROVATO: ["+value+"]");

  2429.                 rs.close();
  2430.                 pstmt.close();

  2431.                 return value;

  2432.             } catch(Exception e) {
  2433.                 String errorMsg = "GESTORE_MESSAGGI, error mapRiferimentoIntoIDBusta "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  2434.                 try{
  2435.                     if(rs != null)
  2436.                         rs.close();
  2437.                 } catch(Exception er) {
  2438.                     // close
  2439.                 }
  2440.                 try{
  2441.                     if(pstmt != null)
  2442.                         pstmt.close();
  2443.                 } catch(Exception er) {
  2444.                     // close
  2445.                 }
  2446.                 this.log.error(errorMsg,e);
  2447.                 throw new GestoreMessaggiException(errorMsg,e);
  2448.             }  
  2449.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  2450.             //          //TODO Metodo stateful only
  2451.             //          return null;
  2452.         }else{
  2453.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2454.         }

  2455.     }

  2456.     public String getErroreProcessamentoMessaggio(String servizioApplicativo) throws GestoreMessaggiException{
  2457.         if( (this.openspcoopstate instanceof OpenSPCoopStateful) || this.oneWayVersione11) {
  2458.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  2459.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  2460.             Connection connectionDB = stateMSG.getConnectionDB();
  2461.             PreparedStatement pstmtRead = null;
  2462.             ResultSet rs = null;
  2463.             String motivoErroreGiaRegistrato = null;
  2464.             try{    
  2465.                 // Costruzione Query
  2466.                 String query = null;
  2467.                 if(servizioApplicativo==null)
  2468.                     query = "SELECT ERRORE_PROCESSAMENTO FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO = ? AND TIPO=?";
  2469.                 else
  2470.                     query = "SELECT ERRORE_PROCESSAMENTO FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" WHERE ID_MESSAGGIO = ? AND SERVIZIO_APPLICATIVO=?";

  2471.                 //log.debug("Query: "+query);
  2472.                 pstmtRead = connectionDB.prepareStatement(query);
  2473.                 pstmtRead.setString(1,this.idBusta);
  2474.                 if(servizioApplicativo!=null)
  2475.                     pstmtRead.setString(2,servizioApplicativo);
  2476.                 else
  2477.                     pstmtRead.setString(2,this.tipo);

  2478.                 rs = pstmtRead.executeQuery();
  2479.                 if(rs.next()){
  2480.                     motivoErroreGiaRegistrato = rs.getString("ERRORE_PROCESSAMENTO");
  2481.                 }
  2482.                 rs.close();
  2483.                 pstmtRead.close();

  2484.             } catch(Exception e) {
  2485.                 String errorMsg = "GESTORE_MESSAGGI, Errore getErroreProcessamentoMessaggio "+this.tipo+"/"+this.idBusta+" sa["+servizioApplicativo+"]: "+e.getMessage();      
  2486.                 try{
  2487.                     if(rs != null)
  2488.                         rs.close();
  2489.                 } catch(Exception er) {
  2490.                     // close
  2491.                 }
  2492.                 try{
  2493.                     if(pstmtRead != null)
  2494.                         pstmtRead.close();
  2495.                 } catch(Exception er) {
  2496.                     // close
  2497.                 }
  2498.                 this.log.error(errorMsg,e);
  2499.                 throw new GestoreMessaggiException(errorMsg,e);
  2500.             }

  2501.             return motivoErroreGiaRegistrato;
  2502.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  2503.             //          //TODO Metodo stateful only
  2504.             //          return null;
  2505.         }else{
  2506.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2507.         }
  2508.     }

  2509.     public Timestamp getOraRegistrazioneMessaggio() throws GestoreMessaggiException{

  2510.         Timestamp t = null;

  2511.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  2512.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  2513.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  2514.             Connection connectionDB = stateful.getConnectionDB();

  2515.             PreparedStatement pstmtRead = null;
  2516.             ResultSet rs = null;
  2517.             try{    
  2518.                 // Costruzione Query
  2519.                 String query = "SELECT ORA_REGISTRAZIONE FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO = ? AND TIPO=?";

  2520.                 //log.debug("Query: "+query);
  2521.                 pstmtRead = connectionDB.prepareStatement(query);
  2522.                 pstmtRead.setString(1,this.idBusta);
  2523.                 pstmtRead.setString(2,this.tipo);

  2524.                 rs = pstmtRead.executeQuery();
  2525.                 if(rs.next()){
  2526.                     t = rs.getTimestamp("ORA_REGISTRAZIONE");
  2527.                 }
  2528.                 rs.close();
  2529.                 pstmtRead.close();

  2530.                 if(t==null)
  2531.                     throw new Exception("Ora registrazione non registrata");
  2532.                 return t;

  2533.             } catch(Exception e) {
  2534.                 String errorMsg = "GESTORE_MESSAGGI, Errore getOraRegistrazioneMessaggio "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  2535.                 try{
  2536.                     if(rs != null)
  2537.                         rs.close();
  2538.                 } catch(Exception er) {
  2539.                     // close
  2540.                 }
  2541.                 try{
  2542.                     if(pstmtRead != null)
  2543.                         pstmtRead.close();
  2544.                 } catch(Exception er) {
  2545.                     // close
  2546.                 }
  2547.                 this.log.error(errorMsg,e);
  2548.                 throw new GestoreMessaggiException(errorMsg,e);
  2549.             }

  2550.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){

  2551.             if (this.isRichiesta)
  2552.                 t = ((OpenSPCoopStateless)this.openspcoopstate).getTempiAttraversamentoPDD().getRicezioneMsgIngresso();
  2553.             else
  2554.                 t = ((OpenSPCoopStateless)this.openspcoopstate).getTempiAttraversamentoPDD().getRicezioneMsgRisposta();

  2555.             if (t == null) throw new GestoreMessaggiException("Ora registrazione non registrata");

  2556.             return t;

  2557.         }else{
  2558.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2559.         }
  2560.     }

  2561.     public Timestamp getDataRispedizioneMessaggio() throws GestoreMessaggiException{

  2562.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  2563.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  2564.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  2565.             Connection connectionDB = stateful.getConnectionDB();
  2566.             PreparedStatement pstmtRead = null;
  2567.             ResultSet rs = null;
  2568.             try{    
  2569.                 // Costruzione Query
  2570.                 String query = "SELECT RISPEDIZIONE FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO = ? AND TIPO=?";

  2571.                 //log.debug("Query: "+query);
  2572.                 pstmtRead = connectionDB.prepareStatement(query);
  2573.                 pstmtRead.setString(1,this.idBusta);
  2574.                 pstmtRead.setString(2,this.tipo);

  2575.                 rs = pstmtRead.executeQuery();
  2576.                 Timestamp t = null;
  2577.                 if(rs.next()){
  2578.                     t = rs.getTimestamp("RISPEDIZIONE");
  2579.                 }
  2580.                 rs.close();
  2581.                 pstmtRead.close();

  2582.                 if(t==null)
  2583.                     throw new Exception("Ora rispedizione non registrata");
  2584.                 return t;

  2585.             } catch(Exception e) {
  2586.                 String errorMsg = "GESTORE_MESSAGGI, Errore getDataRispedizioneMessaggio "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  2587.                 try{
  2588.                     if(rs != null)
  2589.                         rs.close();
  2590.                 } catch(Exception er) {
  2591.                     // close
  2592.                 }
  2593.                 try{
  2594.                     if(pstmtRead != null)
  2595.                         pstmtRead.close();
  2596.                 } catch(Exception er) {
  2597.                     // close
  2598.                 }
  2599.                 this.log.error(errorMsg,e);
  2600.                 throw new GestoreMessaggiException(errorMsg,e);
  2601.             }
  2602.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  2603.             //          //TODO Metodo stateful only
  2604.             //          return null;
  2605.             // do the right thing
  2606.         }else{
  2607.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2608.         }
  2609.     }

  2610.     /**
  2611.      * Controlla se il msg deve essere riconsegnato.
  2612.      *
  2613.      * @return true se la data di riconsegna del msg e' scaduta
  2614.      *
  2615.      */
  2616.     public boolean isPrimaConsegna(String servizioApplicativo) throws GestoreMessaggiException{
  2617.         if( (this.openspcoopstate instanceof OpenSPCoopStateful) || (this.oneWayVersione11) ) {
  2618.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  2619.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  2620.             Connection connectionDB = stateMSG.getConnectionDB();
  2621.             PreparedStatement pstmtRead = null;
  2622.             ResultSet rs = null;
  2623.             try{    

  2624.                 // Costruzione Query
  2625.                 String query = null;
  2626.                 if(servizioApplicativo==null)
  2627.                     query = "SELECT "+GestoreMessaggi.MESSAGGI+".RISPEDIZIONE,"+GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO = ? AND TIPO=?";
  2628.                 else
  2629.                     query = "SELECT "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".RISPEDIZIONE,"+GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE FROM "
  2630.                             +GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+","+GestoreMessaggi.MESSAGGI+" WHERE "
  2631.                             +GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ID_MESSAGGIO="+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO AND "+
  2632.                             ""+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO= ? AND "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SERVIZIO_APPLICATIVO=? AND "+GestoreMessaggi.MESSAGGI+".TIPO=?";

  2633.                 //log.debug("Query: "+query);
  2634.                 pstmtRead = connectionDB.prepareStatement(query);
  2635.                 pstmtRead.setString(1,this.idBusta);
  2636.                 if(servizioApplicativo!=null){
  2637.                     pstmtRead.setString(2,servizioApplicativo);
  2638.                     pstmtRead.setString(3, Costanti.INBOX);
  2639.                 }
  2640.                 else
  2641.                     pstmtRead.setString(2,this.tipo);

  2642.                 rs = pstmtRead.executeQuery();
  2643.                 Timestamp oraRegistrazione = null;
  2644.                 Timestamp rispedizione = null;
  2645.                 if(rs.next()){
  2646.                     oraRegistrazione = rs.getTimestamp("ORA_REGISTRAZIONE");
  2647.                     rispedizione = rs.getTimestamp("RISPEDIZIONE");
  2648.                 }
  2649.                 rs.close();
  2650.                 pstmtRead.close();

  2651.                 //this.log.debug("[isPrimaConsegna] MSG["+this.tipo+"/"+this.ididBusta+"] ORA_REGISTRAZIONE["+oraRegistrazione.toString()+"] RISPEDIZIONE["+rispedizione.toString()+"]");

  2652.                 if(oraRegistrazione==null)
  2653.                     this.log.error("OraRegistrazione is null");
  2654.                 if(rispedizione==null)
  2655.                     this.log.error("Rispedizione is null");

  2656.                 return  oraRegistrazione!=null && rispedizione!=null && (oraRegistrazione.compareTo(rispedizione) == 0) ;

  2657.             } catch(Exception e) {
  2658.                 String errorMsg = "GESTORE_MESSAGGI, Errore isPrimaConsegna "+this.tipo+"/"+this.idBusta+" sa["+servizioApplicativo+"]: "+e.getMessage();      
  2659.                 try{
  2660.                     if(rs != null)
  2661.                         rs.close();
  2662.                 } catch(Exception er) {
  2663.                     // close
  2664.                 }
  2665.                 try{
  2666.                     if(pstmtRead != null)
  2667.                         pstmtRead.close();
  2668.                 } catch(Exception er) {
  2669.                     // close
  2670.                 }
  2671.                 this.log.error(errorMsg,e);
  2672.                 throw new GestoreMessaggiException(errorMsg,e);
  2673.             }
  2674.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  2675.             //          //TODO Metodo stateful only
  2676.             //          return null;
  2677.             // do the right thing
  2678.         }else{
  2679.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2680.         }
  2681.     }

  2682.     /**
  2683.      * Controlla se il msg deve essere riconsegnato.
  2684.      *
  2685.      * @return true se la data di riconsegna del msg e' scaduta
  2686.      *
  2687.      */
  2688.     public boolean isRiconsegnaMessaggio(String servizioApplicativo) throws GestoreMessaggiException{

  2689.         if( (this.openspcoopstate instanceof OpenSPCoopStateful) || (this.oneWayVersione11) ) {
  2690.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  2691.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  2692.             Connection connectionDB = stateMSG.getConnectionDB();
  2693.             if(this.isPrimaConsegna(servizioApplicativo))
  2694.                 return true;

  2695.             PreparedStatement pstmt = null;
  2696.             ResultSet rs = null;
  2697.             try{    
  2698.                 // Costruzione Query
  2699.                 StringBuilder bf = new StringBuilder();
  2700.                 bf.append("SELECT RISPEDIZIONE FROM ");
  2701.                 if(servizioApplicativo!=null)
  2702.                     bf.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  2703.                 else
  2704.                     bf.append(GestoreMessaggi.MESSAGGI);
  2705.                 bf.append(" WHERE ID_MESSAGGIO=?");
  2706.                 if(servizioApplicativo!=null)
  2707.                     bf.append(" AND SERVIZIO_APPLICATIVO=?");
  2708.                 else
  2709.                     bf.append(" AND TIPO=?");
  2710.                 //log.debug("Query: "+query);
  2711.                 pstmt = connectionDB.prepareStatement(bf.toString());
  2712.                 pstmt.setString(1,this.idBusta);
  2713.                 if(servizioApplicativo!=null)
  2714.                     pstmt.setString(2,servizioApplicativo);
  2715.                 else
  2716.                     pstmt.setString(2,this.tipo);
  2717.                 rs = pstmt.executeQuery();
  2718.                 java.sql.Timestamp riconsegna = null;
  2719.                 if(rs.next()){
  2720.                     riconsegna = rs.getTimestamp("RISPEDIZIONE");
  2721.                 }
  2722.                 rs.close();
  2723.                 pstmt.close();

  2724.                 java.sql.Timestamp now = DateManager.getTimestamp();

  2725.                 //this.log.debug("[isRiconsegnaMessaggio] MSG["+this.tipo+"/"+this.idBusta+"] NOW["+now.toString()+"] RISPEDIZIONE["+riconsegna.toString()+"]");


  2726.                 // Eventuale msg Scaduto.
  2727.                 if(riconsegna==null){
  2728.                     //return false;
  2729.                     // Ritorno false, almeno la riconsegna viene riprovata dopo un po'...
  2730.                     // Il valore della riconsegna era null, poiche' il messaggio non era presente. Al prossimo giro l'algoritmo di TransactionManager
  2731.                     // Rendera' invalido il messaggio.
  2732.                     this.log.error("Calcolo riconsegna non riuscito ["+this.tipo+"/"+this.idBusta+"], riconsegna is null? query["+bf.toString()+"] sa["+servizioApplicativo+"]");
  2733.                     throw new Exception("Calcolo riconsegna non riuscito ["+this.tipo+"/"+this.idBusta+"]");
  2734.                 }


  2735.                 if (riconsegna.before(now))
  2736.                     return true;
  2737.                 else{
  2738.                     this.log.debug("Riconsegna messaggio prematura ["+this.tipo+"/"+this.idBusta+"] RICONSEGNA["+riconsegna.toString()+"] < NOW["+now.toString()+"] == false");
  2739.                     return false;
  2740.                 }

  2741.             } catch(Exception e) {
  2742.                 String errorMsg = "GESTORE_MESSAGGI, Errore isRiconsegnaMessaggio "+this.tipo+"/"+this.idBusta+": "+e.getMessage();    
  2743.                 try{
  2744.                     if(rs != null)
  2745.                         rs.close();
  2746.                 } catch(Exception er) {
  2747.                     // close
  2748.                 }
  2749.                 try{
  2750.                     if(pstmt != null)
  2751.                         pstmt.close();
  2752.                 } catch(Exception er) {
  2753.                     // close
  2754.                 }
  2755.                 this.log.error(errorMsg,e);
  2756.                 throw new GestoreMessaggiException(errorMsg,e);
  2757.             }  
  2758.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  2759.             return true;
  2760.         }else{
  2761.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2762.         }
  2763.     }

  2764.     /**
  2765.      * Ritorna il riferimento messaggio associato al messaggio gestito da OpenSPCoop.
  2766.      *
  2767.      * @return il riferimento messaggio associato al messaggio
  2768.      *
  2769.      */
  2770.     public String getRiferimentoMessaggio() throws GestoreMessaggiException{
  2771.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  2772.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  2773.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  2774.             Connection connectionDB = stateful.getConnectionDB();
  2775.             PreparedStatement pstmt = null;
  2776.             ResultSet rs = null;
  2777.             try{    
  2778.                 // Costruzione Query
  2779.                 String query = "SELECT RIFERIMENTO_MSG FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO=? AND TIPO=?";
  2780.                 //log.debug("Query: "+query);
  2781.                 pstmt = connectionDB.prepareStatement(query);
  2782.                 pstmt.setString(1,this.idBusta);
  2783.                 pstmt.setString(2,this.tipo);
  2784.                 rs = pstmt.executeQuery();
  2785.                 String value = null;
  2786.                 if(rs.next()){
  2787.                     value = rs.getString("RIFERIMENTO_MSG");
  2788.                 }
  2789.                 rs.close();
  2790.                 pstmt.close();

  2791.                 return value;

  2792.             } catch(Exception e) {
  2793.                 String errorMsg = "GESTORE_MESSAGGI, Errore get RIFERIMENTO_MSG "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  2794.                 try{
  2795.                     if(rs != null)
  2796.                         rs.close();
  2797.                 } catch(Exception er) {
  2798.                     // close
  2799.                 }
  2800.                 try{
  2801.                     if(pstmt != null)
  2802.                         pstmt.close();
  2803.                 } catch(Exception er) {
  2804.                     // close
  2805.                 }
  2806.                 this.log.error(errorMsg,e);
  2807.                 throw new GestoreMessaggiException(errorMsg,e);
  2808.             }  
  2809.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  2810.             //          //TODO Metodo stateful only
  2811.             //          return null;
  2812.             // do the right thing
  2813.         }else{
  2814.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2815.         }
  2816.     }

  2817.     public String getIDCorrelazioneApplicativa() throws GestoreMessaggiException{

  2818.         String id = null;

  2819.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  2820.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  2821.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  2822.             Connection connectionDB = stateful.getConnectionDB();

  2823.             PreparedStatement pstmtRead = null;
  2824.             ResultSet rs = null;
  2825.             try{    
  2826.                 // Costruzione Query
  2827.                 String query = "SELECT CORRELAZIONE_APPLICATIVA FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO = ? AND TIPO=?";

  2828.                 //log.debug("Query: "+query);
  2829.                 pstmtRead = connectionDB.prepareStatement(query);
  2830.                 pstmtRead.setString(1,this.idBusta);
  2831.                 pstmtRead.setString(2,this.tipo);

  2832.                 rs = pstmtRead.executeQuery();
  2833.                 if(rs.next()){
  2834.                     id = rs.getString("CORRELAZIONE_APPLICATIVA");
  2835.                 }
  2836.                 rs.close();
  2837.                 pstmtRead.close();

  2838.                 if(id==null)
  2839.                     throw new Exception("ID di CorrelazioneApplicativa non registrata");
  2840.                 return id;

  2841.             } catch(Exception e) {
  2842.                 String errorMsg = "GESTORE_MESSAGGI, Errore getIDCorrelazioneApplicativa "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  2843.                 try{
  2844.                     if(rs != null)
  2845.                         rs.close();
  2846.                 } catch(Exception er) {
  2847.                     // close
  2848.                 }
  2849.                 try{
  2850.                     if(pstmtRead != null)
  2851.                         pstmtRead.close();
  2852.                 } catch(Exception er) {
  2853.                     // close
  2854.                 }
  2855.                 if(!e.getMessage().equals("ID di CorrelazioneApplicativa non registrata"))
  2856.                     this.log.error(errorMsg,e);
  2857.                 else
  2858.                     this.log.debug(errorMsg);
  2859.                 throw new GestoreMessaggiException(errorMsg,e);
  2860.             }

  2861.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){

  2862.             return ((OpenSPCoopStateless)this.openspcoopstate).getIDCorrelazioneApplicativa();

  2863.         }else{
  2864.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2865.         }
  2866.     }

  2867.     public String getIDCorrelazioneApplicativaRisposta() throws GestoreMessaggiException{

  2868.         String id = null;

  2869.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  2870.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  2871.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  2872.             Connection connectionDB = stateful.getConnectionDB();

  2873.             PreparedStatement pstmtRead = null;
  2874.             ResultSet rs = null;
  2875.             try{    
  2876.                 // Costruzione Query
  2877.                 String query = "SELECT CORRELAZIONE_RISPOSTA FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO = ? AND TIPO=?";

  2878.                 //log.debug("Query: "+query);
  2879.                 pstmtRead = connectionDB.prepareStatement(query);
  2880.                 pstmtRead.setString(1,this.idBusta);
  2881.                 pstmtRead.setString(2,this.tipo);

  2882.                 rs = pstmtRead.executeQuery();
  2883.                 if(rs.next()){
  2884.                     id = rs.getString("CORRELAZIONE_RISPOSTA");
  2885.                 }
  2886.                 rs.close();
  2887.                 pstmtRead.close();

  2888.                 if(id==null)
  2889.                     throw new Exception("ID di CorrelazioneApplicativaRisposta non registrata");
  2890.                 return id;

  2891.             } catch(Exception e) {
  2892.                 String errorMsg = "GESTORE_MESSAGGI, Errore getIDCorrelazioneApplicativaRisposta "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  2893.                 try{
  2894.                     if(rs != null)
  2895.                         rs.close();
  2896.                 } catch(Exception er) {
  2897.                     // close
  2898.                 }
  2899.                 try{
  2900.                     if(pstmtRead != null)
  2901.                         pstmtRead.close();
  2902.                 } catch(Exception er) {
  2903.                     // close
  2904.                 }
  2905.                 if(!e.getMessage().equals("ID di CorrelazioneApplicativaRisposta non registrata")){
  2906.                     this.log.error(errorMsg,e);
  2907.                     throw new GestoreMessaggiException(errorMsg,e);
  2908.                 }
  2909.                 else{
  2910.                     this.log.debug(errorMsg);
  2911.                     return null;
  2912.                 }
  2913.             }

  2914.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){

  2915.             return ((OpenSPCoopStateless)this.openspcoopstate).getIDCorrelazioneApplicativaRisposta();

  2916.         }else{
  2917.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  2918.         }
  2919.     }

  2920.     public PdDContext getPdDContext() throws GestoreMessaggiException{
  2921.         return this.getPdDContext(false);
  2922.     }
  2923.     public PdDContext getPdDContext(boolean saveInInstance) throws GestoreMessaggiException{

  2924.         if(this.openspcoopstate==null) {
  2925.             return this.pddContext;
  2926.         }
  2927.        
  2928.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  2929.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  2930.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  2931.             Connection connectionDB = stateful.getConnectionDB();

  2932.             PreparedStatement pstmtRead = null;
  2933.             ResultSet rs = null;
  2934.             try{    

  2935.                 // PdDContext
  2936.                 StringBuilder fieldNamesPdDContext_db = new StringBuilder();
  2937.                 Map<String, String> mapping = new HashMap<>();
  2938.                 if(GestoreMessaggi.pddContextSerializer!=null){
  2939.                     Map<String, String> contextSerializerParameters = GestoreMessaggi.pddContextSerializer.getGestoreMessaggiKeywords();
  2940.                     if(contextSerializerParameters!=null && contextSerializerParameters.size()>0){
  2941.                         for (String keyword : contextSerializerParameters.keySet()) {
  2942.                             if(fieldNamesPdDContext_db.length()>0)
  2943.                                 fieldNamesPdDContext_db.append(" , ");
  2944.                             String nomeDB = contextSerializerParameters.get(keyword);
  2945.                             fieldNamesPdDContext_db.append(nomeDB);
  2946.                             mapping.put(nomeDB, keyword);
  2947.                         }
  2948.                     }
  2949.                 }
  2950.                 if(fieldNamesPdDContext_db.length() != 0)
  2951.                     fieldNamesPdDContext_db.append(" , ");
  2952.                 fieldNamesPdDContext_db.append("PROTOCOLLO");
  2953.                 mapping.put("PROTOCOLLO", org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME.getValue());
  2954.                 PdDContext pddContext = new PdDContext();
  2955.                 if(mapping.size()<=0){
  2956.                     return pddContext;
  2957.                 }

  2958.                 // Costruzione Query
  2959.                 String query = "SELECT id_transazione, "+fieldNamesPdDContext_db.toString()+" FROM "+GestoreMessaggi.MESSAGGI+" WHERE ID_MESSAGGIO = ? AND TIPO=?";

  2960.                 //log.debug("Query: "+query);
  2961.                 pstmtRead = connectionDB.prepareStatement(query);
  2962.                 pstmtRead.setString(1,this.idBusta);
  2963.                 pstmtRead.setString(2,this.tipo);

  2964.                 rs = pstmtRead.executeQuery();
  2965.                 if(rs.next()){

  2966.                     for (String keyDB : mapping.keySet()) {
  2967.                         Object object = rs.getObject(keyDB);
  2968.                         String key = mapping.get(keyDB);
  2969.                         MapKey<String> mapKey = org.openspcoop2.utils.Map.newMapKey(key);
  2970.                         pddContext.addObject(mapKey, object);
  2971.                     }
  2972.                    
  2973.                     String idTransazione = rs.getString("id_transazione");
  2974.                     if(idTransazione!=null) {
  2975.                         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, idTransazione);
  2976.                     }

  2977.                 }else{
  2978.                     throw new Exception("Messaggio non trovato");
  2979.                 }
  2980.                 rs.close();
  2981.                 pstmtRead.close();

  2982.                 if(saveInInstance) {
  2983.                     this.pddContext = pddContext;
  2984.                 }
  2985.                 return pddContext;

  2986.             } catch(Exception e) {
  2987.                 String errorMsg = "GESTORE_MESSAGGI, Errore getPdDContext "+this.tipo+"/"+this.idBusta+": "+e.getMessage();    
  2988.                 try{
  2989.                     if(rs != null)
  2990.                         rs.close();
  2991.                 } catch(Exception er) {
  2992.                     // close
  2993.                 }
  2994.                 try{
  2995.                     if(pstmtRead != null)
  2996.                         pstmtRead.close();
  2997.                 } catch(Exception er) {
  2998.                     // close
  2999.                 }
  3000.                 if(!e.getMessage().equals("Messaggio non trovato"))
  3001.                     this.log.error(errorMsg,e);
  3002.                 else
  3003.                     this.log.debug(errorMsg,e);
  3004.                 throw new GestoreMessaggiException(errorMsg,e);
  3005.             }

  3006.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){

  3007.             return ((OpenSPCoopStateless)this.openspcoopstate).getPddContext();

  3008.         }else{
  3009.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  3010.         }
  3011.     }











  3012.     /* ********  R E A D    M E S S A G E   (Destinato ad un SIL)  ******** */

  3013.     /**
  3014.      * Controlla l'esistenza di un messaggio gestito da OpenSPCoop, il quale e' stato associato ad un servizio applicativo.
  3015.      *
  3016.      * @param servizioApplicativo Servizio Applicativo
  3017.      * @return true se il messaggio esiste
  3018.      *
  3019.      */
  3020.     public MessaggioIM readMessageForSIL(String servizioApplicativo, Date oraRegistrazione)throws GestoreMessaggiException{
  3021.         return readMessageForSIL(servizioApplicativo,false,oraRegistrazione);
  3022.     }
  3023.     /**
  3024.      * Controlla l'esistenza di un messaggio gestito da OpenSPCoop, il quale e' stato associato ad un servizio applicativo.
  3025.      *
  3026.      * @param servizioApplicativo Servizio Applicativo
  3027.      * @param searchForRiferimentoMsg Se true, il messaggio viene ricercato per Riferimento Messaggio
  3028.      * @return true se il messaggio esiste
  3029.      *
  3030.      */
  3031.     public MessaggioIM readMessageForSIL(String servizioApplicativo,boolean searchForRiferimentoMsg, Date oraRegistrazione)throws GestoreMessaggiException{
  3032.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  3033.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  3034.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  3035.             Connection connectionDB = stateful.getConnectionDB();
  3036.             PreparedStatement pstmt = null;
  3037.             ResultSet rs = null;
  3038.             try{    

  3039.                 // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  3040.                 // come riferimento Messaggio l'ID del gestore.
  3041.                 // In caso di esistenza uso l'idBusta del messaggio trovato e non quello del gestore
  3042.                 String idBustaSearch = this.idBusta;
  3043.                 if(searchForRiferimentoMsg){
  3044.                     idBustaSearch = mapRiferimentoIntoIDBusta();
  3045.                 }

  3046.                 // Ricerco messaggio assiciato
  3047.                 String query = null;
  3048.                 if(Configurazione.getSqlQueryObjectType()==null){
  3049.                     query = "SELECT "+
  3050.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".INTEGRATION_MANAGER as authIM, "+
  3051.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SBUSTAMENTO_SOAP as sbSoap, "+
  3052.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SBUSTAMENTO_INFO_PROTOCOL as sbProtocol "+
  3053.                             GestoreMessaggi.MESSAGGI+".RIFERIMENTO_MSG as rifMsg, "+
  3054.                             GestoreMessaggi.MESSAGGI+".id_transazione as idtransazione, "+
  3055.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SERVIZIO_APPLICATIVO as sa, "+
  3056.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".NOME_PORTA as nomePorta, "+
  3057.                             GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE as oramess "+
  3058.                             " FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+","+GestoreMessaggi.MESSAGGI+
  3059.                             " WHERE ";
  3060.                     if(oraRegistrazione!=null) {
  3061.                         query = query + "("+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ORA_REGISTRAZIONE BETWEEN ? AND ?) AND ";
  3062.                         query = query + "("+GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE BETWEEN ? AND ?) AND ";
  3063.                     }
  3064.                     query = query + GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ID_MESSAGGIO=? AND " +
  3065.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SERVIZIO_APPLICATIVO=? AND "+
  3066.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ID_MESSAGGIO="+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO AND "+
  3067.                             GestoreMessaggi.MESSAGGI+".PROPRIETARIO=?";
  3068.                 }
  3069.                 else {
  3070.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  3071.                     sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI,"m");
  3072.                     sqlQueryObject.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,"sa");
  3073.                    
  3074.                     sqlQueryObject.addSelectAliasField("sa", "INTEGRATION_MANAGER", "authIM");
  3075.                     sqlQueryObject.addSelectAliasField("sa", "SBUSTAMENTO_SOAP", "sbSoap");
  3076.                     sqlQueryObject.addSelectAliasField("sa", "SBUSTAMENTO_INFO_PROTOCOL", "sbProtocol");
  3077.                     sqlQueryObject.addSelectAliasField("m", "RIFERIMENTO_MSG", "rifMsg");
  3078.                     sqlQueryObject.addSelectAliasField("m", "id_transazione", "idtransazione");
  3079.                     sqlQueryObject.addSelectAliasField("sa", "SERVIZIO_APPLICATIVO", "sa");
  3080.                     sqlQueryObject.addSelectAliasField("sa", "NOME_PORTA", "nomePorta");
  3081.                     sqlQueryObject.addSelectAliasField("m", "ORA_REGISTRAZIONE", "oramess");
  3082.                    
  3083.                     if(oraRegistrazione!=null) {
  3084.                         sqlQueryObject.addWhereBetweenCondition("sa.ORA_REGISTRAZIONE", false, "?", "?");
  3085.                         sqlQueryObject.addWhereBetweenCondition("m.ORA_REGISTRAZIONE", false, "?", "?");
  3086.                     }
  3087.                                        
  3088.                     sqlQueryObject.addWhereCondition("sa.ID_MESSAGGIO=?");
  3089.                     sqlQueryObject.addWhereCondition("sa.SERVIZIO_APPLICATIVO=?");
  3090.                    
  3091.                     // join
  3092.                     sqlQueryObject.addWhereCondition("m.ID_MESSAGGIO=sa.ID_MESSAGGIO");
  3093.                    
  3094.                     sqlQueryObject.addWhereCondition("m.PROPRIETARIO=?");
  3095.                    
  3096.                     sqlQueryObject.setANDLogicOperator(true);
  3097.                    
  3098.                     query = sqlQueryObject.createSQLQuery();
  3099.                 }
  3100.                 //log.debug("Query: "+query);
  3101.                 pstmt = connectionDB.prepareStatement(query);
  3102.                 int index = 1;
  3103.                
  3104.                 Timestamp leftValue = null;
  3105.                 Timestamp rightValue = null;
  3106.                 if(oraRegistrazione!=null) {
  3107.                     leftValue = new Timestamp(oraRegistrazione.getTime() - (1000*60*5));
  3108.                     rightValue = new Timestamp(oraRegistrazione.getTime() + (1000*60*5));
  3109.                     pstmt.setTimestamp(index++,leftValue);
  3110.                     pstmt.setTimestamp(index++,rightValue);
  3111.                     pstmt.setTimestamp(index++,leftValue);
  3112.                     pstmt.setTimestamp(index++,rightValue);
  3113.                 }
  3114.                
  3115.                 pstmt.setString(index++,idBustaSearch);
  3116.                 pstmt.setString(index++,servizioApplicativo);
  3117.                 pstmt.setString(index++,ConsegnaContenutiApplicativi.ID_MODULO);
  3118.                 rs = pstmt.executeQuery();
  3119.                 if(rs.next()==true){                
  3120.                     MessaggioIM messaggio = new MessaggioIM();
  3121.                     messaggio.setAuthorized(rs.getInt("authIM") == CostantiDB.TRUE);
  3122.                     messaggio.setSbustamentoSoap(rs.getInt("sbSoap") == CostantiDB.TRUE);
  3123.                     messaggio.setSbustamentoInformazioniProtocollo(rs.getInt("sbProtocol") == CostantiDB.TRUE);
  3124.                     messaggio.setRiferimentoMessaggio(rs.getString("rifMsg"));
  3125.                     messaggio.setIdentificativoRichiesta(idBustaSearch);
  3126.                     messaggio.setIdTransazione(rs.getString("idtransazione"));
  3127.                     messaggio.setServizioApplicativo(rs.getString("sa"));
  3128.                     messaggio.setOraRegistrazione(rs.getTimestamp("oramess"));
  3129.                     messaggio.setNomePorta(rs.getString("nomePorta"));
  3130.                    
  3131.                     rs.close();
  3132.                     pstmt.close();
  3133.                    
  3134.                     return messaggio;
  3135.                 }
  3136.                 rs.close();
  3137.                 pstmt.close();

  3138.                 return null;

  3139.             } catch(Exception e) {
  3140.                 String errorMsg = "GESTORE_MESSAGGI, error readMessageForSIL "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  3141.                 try{
  3142.                     if(rs != null)
  3143.                         rs.close();
  3144.                 } catch(Exception er) {
  3145.                     // close
  3146.                 }
  3147.                 try{
  3148.                     if(pstmt != null)
  3149.                         pstmt.close();
  3150.                 } catch(Exception er) {
  3151.                     // close
  3152.                 }
  3153.                 this.log.error(errorMsg,e);
  3154.                 throw new GestoreMessaggiException(errorMsg,e);
  3155.             }  
  3156.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  3157.             //          //TODO Metodo stateful only
  3158.             //          return null;
  3159.             // do the right thing
  3160.         }else{
  3161.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  3162.         }
  3163.     }
  3164.    
  3165.    
  3166.    
  3167.    
  3168.    
  3169.     /**
  3170.      * Controlla l'esistenza di un messaggio gestito da OpenSPCoop, il quale e' stato associato ad un servizio applicativo.
  3171.      *
  3172.      * @param servizioApplicativo Servizio Applicativo
  3173.      * @return true se il messaggio esiste
  3174.      *
  3175.      */
  3176.     public boolean existsMessageForSIL(String servizioApplicativo)throws GestoreMessaggiException{
  3177.         return existsMessageForSIL(servizioApplicativo,false);
  3178.     }
  3179.     /**
  3180.      * Controlla l'esistenza di un messaggio gestito da OpenSPCoop, il quale e' stato associato ad un servizio applicativo.
  3181.      *
  3182.      * @param servizioApplicativo Servizio Applicativo
  3183.      * @param searchForRiferimentoMsg Se true, il messaggio viene ricercato per Riferimento Messaggio
  3184.      * @return true se il messaggio esiste
  3185.      *
  3186.      */
  3187.     public boolean existsMessageForSIL(String servizioApplicativo,boolean searchForRiferimentoMsg)throws GestoreMessaggiException{
  3188.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  3189.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  3190.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  3191.             Connection connectionDB = stateful.getConnectionDB();
  3192.             PreparedStatement pstmt = null;
  3193.             ResultSet rs = null;
  3194.             try{    

  3195.                 // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  3196.                 // come riferimento Messaggio l'ID del gestore.
  3197.                 // In caso di esistenza uso l'idBusta del messaggio trovato e non quello del gestore
  3198.                 String idBustaSearch = this.idBusta;
  3199.                 if(searchForRiferimentoMsg){
  3200.                     idBustaSearch = mapRiferimentoIntoIDBusta();
  3201.                 }


  3202.                 // Ricerco messaggio assiciato
  3203.                 String query = "SELECT * FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+","+GestoreMessaggi.MESSAGGI+
  3204.                         " WHERE ";
  3205.                 query = query + GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ID_MESSAGGIO=? AND " +
  3206.                         GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SERVIZIO_APPLICATIVO=? AND "+
  3207.                         GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ID_MESSAGGIO="+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO AND "+
  3208.                         GestoreMessaggi.MESSAGGI+".PROPRIETARIO=?";
  3209.                 //log.debug("Query: "+query);
  3210.                 pstmt = connectionDB.prepareStatement(query);
  3211.                 int index = 1;
  3212.                 pstmt.setString(index++,idBustaSearch);
  3213.                 pstmt.setString(index++,servizioApplicativo);
  3214.                 pstmt.setString(index++,ConsegnaContenutiApplicativi.ID_MODULO);
  3215.                 rs = pstmt.executeQuery();
  3216.                 if(rs.next()==true){
  3217.                     rs.close();
  3218.                     pstmt.close();
  3219.                     return true;
  3220.                 }
  3221.                 rs.close();
  3222.                 pstmt.close();

  3223.                 return false;

  3224.             } catch(Exception e) {
  3225.                 String errorMsg = "GESTORE_MESSAGGI, error existsMessage "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  3226.                 try{
  3227.                     if(rs != null)
  3228.                         rs.close();
  3229.                 } catch(Exception er) {
  3230.                     // close
  3231.                 }
  3232.                 try{
  3233.                     if(pstmt != null)
  3234.                         pstmt.close();
  3235.                 } catch(Exception er) {
  3236.                     // close
  3237.                 }
  3238.                 this.log.error(errorMsg,e);
  3239.                 throw new GestoreMessaggiException(errorMsg,e);
  3240.             }  
  3241.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  3242.             //          //TODO Metodo stateful only
  3243.             //          return null;
  3244.             // do the right thing
  3245.         }else{
  3246.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  3247.         }
  3248.     }

  3249.     /**
  3250.      * Ritorna true se il servizio applicativo e' autorizzato ad utilizzare il servizio IntegrationManager
  3251.      * per ricevere il messaggio
  3252.      *
  3253.      * @param servizioApplicativo Servizio Applicativo
  3254.      * @return Ritorna true se il servizio applicativo e' autorizzato ad utilizzare il servizio IntegrationManager
  3255.      *
  3256.      */
  3257.     public boolean checkAutorizzazione(String servizioApplicativo)throws GestoreMessaggiException{
  3258.         return checkAutorizzazione(servizioApplicativo,false);
  3259.     }
  3260.     /**
  3261.      * Ritorna true se il servizio applicativo e' autorizzato ad utilizzare il servizio IntegrationManager
  3262.      * per ricevere il messaggio
  3263.      *
  3264.      * @param servizioApplicativo Servizio Applicativo
  3265.      * @param searchForRiferimentoMsg Se true, il messaggio viene ricercato per Riferimento Messaggio
  3266.      * @return Ritorna true se il servizio applicativo e' autorizzato ad utilizzare il servizio IntegrationManager
  3267.      *
  3268.      */
  3269.     public boolean checkAutorizzazione(String servizioApplicativo,boolean searchForRiferimentoMsg)throws GestoreMessaggiException{
  3270.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  3271.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  3272.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  3273.             Connection connectionDB = stateful.getConnectionDB();
  3274.             PreparedStatement pstmt = null;
  3275.             ResultSet rs = null;
  3276.             try{  
  3277.                 // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  3278.                 // come riferimento Messaggio l'ID del gestore.
  3279.                 // In caso di esistenza uso l'idBusta del messaggio trovato e non quello del gestore
  3280.                 String idBustaSearch = this.idBusta;
  3281.                 if(searchForRiferimentoMsg){
  3282.                     idBustaSearch = mapRiferimentoIntoIDBusta();
  3283.                 }


  3284.                 // Costruzione Query
  3285.                 String query = "SELECT INTEGRATION_MANAGER FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI
  3286.                         +" WHERE ID_MESSAGGIO=? AND SERVIZIO_APPLICATIVO=?";
  3287.                 //log.debug("Query: "+query);
  3288.                 pstmt =  connectionDB.prepareStatement(query);
  3289.                 pstmt.setString(1,idBustaSearch);
  3290.                 pstmt.setString(2,servizioApplicativo);
  3291.                 rs = pstmt.executeQuery();
  3292.                 boolean auth = false;
  3293.                 if(rs.next()){
  3294.                     if( rs.getInt("INTEGRATION_MANAGER") == 1)
  3295.                         auth = true;
  3296.                 }
  3297.                 rs.close();
  3298.                 pstmt.close();

  3299.                 return auth;

  3300.             } catch(Exception e) {
  3301.                 String errorMsg = "GESTORE_MESSAGGI, error existsMessage "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  3302.                 try{
  3303.                     if(rs != null)
  3304.                         rs.close();
  3305.                 } catch(Exception er) {
  3306.                     // close
  3307.                 }
  3308.                 try{
  3309.                     if(pstmt != null)
  3310.                         pstmt.close();
  3311.                 } catch(Exception er) {
  3312.                     // close
  3313.                 }
  3314.                 this.log.error(errorMsg,e);
  3315.                 throw new GestoreMessaggiException(errorMsg,e);
  3316.             }                  
  3317.             //}else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  3318.             //          //TODO Metodo stateful only
  3319.             //          return null;
  3320.             // do the right thing
  3321.         }else{
  3322.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  3323.         }
  3324.     }

  3325.     /**
  3326.      * Ritorna true se il servizio applicativo ha richiesto lo sbustamento per il messaggio a lui destinato
  3327.      *
  3328.      * @param servizioApplicativo Servizio Applicativo
  3329.      * @return Ritorna true se il servizio applicativo ha richiesto lo sbustamento soap
  3330.      *
  3331.      */
  3332.     public boolean sbustamentoSOAP(String servizioApplicativo)throws GestoreMessaggiException{
  3333.         return sbustamentoSOAP(servizioApplicativo,false);
  3334.     }
  3335.     /**
  3336.      * Ritorna true se il servizio applicativo ha richiesto lo sbustamento per il messaggio a lui destinato
  3337.      *
  3338.      * @param servizioApplicativo Servizio Applicativo
  3339.      * @param searchForRiferimentoMsg Se true, il messaggio viene ricercato per Riferimento Messaggio
  3340.      * @return Ritorna true se il servizio applicativo ha richiesto lo sbustamento soap
  3341.      *
  3342.      */
  3343.     public boolean sbustamentoSOAP(String servizioApplicativo,boolean searchForRiferimentoMsg)throws GestoreMessaggiException{
  3344.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  3345.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  3346.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  3347.             Connection connectionDB = stateful.getConnectionDB();
  3348.             PreparedStatement pstmt = null;
  3349.             ResultSet rs = null;
  3350.             try{
  3351.                 // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  3352.                 // come riferimento Messaggio l'ID del gestore.
  3353.                 // In caso di esistenza uso l'idBusta del messaggio trovato e non quello del gestore
  3354.                 String idBustaSearch = this.idBusta;
  3355.                 if(searchForRiferimentoMsg){
  3356.                     idBustaSearch = mapRiferimentoIntoIDBusta();
  3357.                 }


  3358.                 // Costruzione Query
  3359.                 String query = "SELECT SBUSTAMENTO_SOAP FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI
  3360.                         +" WHERE ID_MESSAGGIO=? AND SERVIZIO_APPLICATIVO=?";
  3361.                 //log.debug("Query: "+query);
  3362.                 pstmt =  connectionDB.prepareStatement(query);
  3363.                 pstmt.setString(1,idBustaSearch);
  3364.                 pstmt.setString(2,servizioApplicativo);
  3365.                 rs = pstmt.executeQuery();
  3366.                 boolean sbustamento = false;
  3367.                 if(rs.next()){
  3368.                     if( rs.getInt("SBUSTAMENTO_SOAP") == 1)
  3369.                         sbustamento = true;
  3370.                 }
  3371.                 rs.close();
  3372.                 pstmt.close();

  3373.                 return sbustamento;

  3374.             } catch(Exception e) {
  3375.                 String errorMsg = "GESTORE_MESSAGGI, error getSbustamentoSoap "+this.tipo+"/"+this.idBusta+": "+e.getMessage();    
  3376.                 try{
  3377.                     if(rs != null)
  3378.                         rs.close();
  3379.                 } catch(Exception er) {
  3380.                     // close
  3381.                 }
  3382.                 try{
  3383.                     if(pstmt != null)
  3384.                         pstmt.close();
  3385.                 } catch(Exception er) {
  3386.                     // close
  3387.                 }
  3388.                 this.log.error(errorMsg,e);
  3389.                 throw new GestoreMessaggiException(errorMsg,e);
  3390.             }      
  3391.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  3392.             //          //TODO Metodo stateful only
  3393.             //          return null;
  3394.             // do the right thing
  3395.         }else{
  3396.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  3397.         }
  3398.     }

  3399.     /**
  3400.      * Ritorna true se il servizio applicativo ha richiesto lo sbustamento per il messaggio a lui destinato
  3401.      *
  3402.      * @param servizioApplicativo Servizio Applicativo
  3403.      * @return Ritorna true se il servizio applicativo ha richiesto lo sbustamento soap
  3404.      *
  3405.      */
  3406.     public boolean sbustamentoInformazioniProtocollo(String servizioApplicativo)throws GestoreMessaggiException{
  3407.         return sbustamentoInformazioniProtocollo(servizioApplicativo,false);
  3408.     }
  3409.     /**
  3410.      * Ritorna true se il servizio applicativo ha richiesto lo sbustamento per il messaggio a lui destinato
  3411.      *
  3412.      * @param servizioApplicativo Servizio Applicativo
  3413.      * @param searchForRiferimentoMsg Se true, il messaggio viene ricercato per Riferimento Messaggio
  3414.      * @return Ritorna true se il servizio applicativo ha richiesto lo sbustamento soap
  3415.      *
  3416.      */
  3417.     public boolean sbustamentoInformazioniProtocollo(String servizioApplicativo,boolean searchForRiferimentoMsg)throws GestoreMessaggiException{
  3418.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  3419.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  3420.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  3421.             Connection connectionDB = stateful.getConnectionDB();
  3422.             PreparedStatement pstmt = null;
  3423.             ResultSet rs = null;
  3424.             try{
  3425.                 // Se devo cercare per riferimentoMessaggio, prima cerco un messaggio registrato, che possiede
  3426.                 // come riferimento Messaggio l'ID del gestore.
  3427.                 // In caso di esistenza uso l'idBusta del messaggio trovato e non quello del gestore
  3428.                 String idBustaSearch = this.idBusta;
  3429.                 if(searchForRiferimentoMsg){
  3430.                     idBustaSearch = mapRiferimentoIntoIDBusta();
  3431.                 }


  3432.                 // Costruzione Query
  3433.                 String query = "SELECT SBUSTAMENTO_INFO_PROTOCOL FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI
  3434.                         +" WHERE ID_MESSAGGIO=? AND SERVIZIO_APPLICATIVO=?";
  3435.                 //log.debug("Query: "+query);
  3436.                 pstmt =  connectionDB.prepareStatement(query);
  3437.                 pstmt.setString(1,idBustaSearch);
  3438.                 pstmt.setString(2,servizioApplicativo);
  3439.                 rs = pstmt.executeQuery();
  3440.                 boolean sbustamento = false;
  3441.                 if(rs.next()){
  3442.                     if( rs.getInt("SBUSTAMENTO_INFO_PROTOCOL") == 1)
  3443.                         sbustamento = true;
  3444.                 }
  3445.                 rs.close();
  3446.                 pstmt.close();

  3447.                 return sbustamento;

  3448.             } catch(Exception e) {
  3449.                 String errorMsg = "GESTORE_MESSAGGI, error getSbustamentoSoap "+this.tipo+"/"+this.idBusta+": "+e.getMessage();    
  3450.                 try{
  3451.                     if(rs != null)
  3452.                         rs.close();
  3453.                 } catch(Exception er) {
  3454.                     // close
  3455.                 }
  3456.                 try{
  3457.                     if(pstmt != null)
  3458.                         pstmt.close();
  3459.                 } catch(Exception er) {
  3460.                     // close
  3461.                 }
  3462.                 this.log.error(errorMsg,e);
  3463.                 throw new GestoreMessaggiException(errorMsg,e);
  3464.             }      
  3465.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  3466.             //          //TODO Metodo stateful only
  3467.             //          return null;
  3468.             // do the right thing
  3469.         }else{
  3470.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  3471.         }
  3472.     }

  3473.     /**
  3474.      * Ritorna true se il messaggio risulta in gestione
  3475.      *
  3476.      * @return true se il  messaggio risulta in gestione
  3477.      * @throws GestoreMessaggiException
  3478.      *
  3479.      */
  3480.     public boolean existsMessageInProcessamento() throws GestoreMessaggiException{
  3481.         return this.existsMessageInProcessamento(false);
  3482.     }

  3483.     /**
  3484.      * Ritorna true se il messaggio con quel riferimento messaggio risulta in gestione
  3485.      *
  3486.      * @return true se il  messaggio con quel riferimento messaggio risulta in gestione
  3487.      * @throws GestoreMessaggiException
  3488.      *
  3489.      */
  3490.     public boolean existsMessageInProcessamentoByReference() throws GestoreMessaggiException{
  3491.         return this.existsMessageInProcessamento(true);
  3492.     }

  3493.     /**
  3494.      * Ritorna true se il messaggio risulta in gestione
  3495.      *
  3496.      * @return true se il  messaggio risulta in gestione
  3497.      * @throws GestoreMessaggiException
  3498.      *
  3499.      */
  3500.     private boolean existsMessageInProcessamento(boolean rifMsg) throws GestoreMessaggiException{
  3501.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  3502.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  3503.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  3504.             Connection connectionDB = stateful.getConnectionDB();
  3505.             PreparedStatement pstmt = null;
  3506.             ResultSet rs = null;
  3507.             try{    
  3508.                 // Costruzione Query
  3509.                 StringBuilder bf = new StringBuilder();
  3510.                 bf.append("SELECT ID_MESSAGGIO FROM ");
  3511.                 bf.append(GestoreMessaggi.MESSAGGI);
  3512.                 bf.append(" WHERE ");
  3513.                 if(!rifMsg){
  3514.                     bf.append("ID_MESSAGGIO=?");
  3515.                 }else{
  3516.                     bf.append("RIFERIMENTO_MSG=?");
  3517.                 }
  3518.                 bf.append(" AND TIPO=? AND PROPRIETARIO<>?");
  3519.                 //log.debug("Query: "+query);
  3520.                 pstmt = connectionDB.prepareStatement(bf.toString());
  3521.                 pstmt.setString(1,this.idBusta);
  3522.                 pstmt.setString(2,this.tipo);
  3523.                 pstmt.setString(3,TimerGestoreMessaggi.ID_MODULO);
  3524.                 rs = pstmt.executeQuery();
  3525.                 if(rs.next()){
  3526.                     rs.close();
  3527.                     pstmt.close();
  3528.                     return true;
  3529.                 }
  3530.                 rs.close();
  3531.                 pstmt.close();
  3532.                 return false;

  3533.             } catch(Exception e) {
  3534.                 String errorMsg = "GESTORE_MESSAGGI, Errore existsMessageInProcessamento "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  3535.                 try{
  3536.                     if(rs != null)
  3537.                         rs.close();
  3538.                 } catch(Exception er) {
  3539.                     // close
  3540.                 }
  3541.                 try{
  3542.                     if(pstmt != null)
  3543.                         pstmt.close();
  3544.                 } catch(Exception er) {
  3545.                     // close
  3546.                 }
  3547.                 this.log.error(errorMsg,e);
  3548.                 return false;
  3549.             }
  3550.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  3551.             //          //TODO Metodo stateful only
  3552.             //          return null;
  3553.             // do the right thing
  3554.         }else{
  3555.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  3556.         }
  3557.     }

















  3558.     /* ********  GET ID MESSAGGI DESTINATI AD UN SERVIZIO APPLICATIVO   ******** */

  3559.     /**
  3560.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo
  3561.      *
  3562.      * @param servizioApplicativo Servizio Applicativo
  3563.      * @return ID dei messaggi destinati ad un servizio applicativo
  3564.      *
  3565.      */
  3566.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo)throws GestoreMessaggiException{

  3567.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, -1, -1, null, null, null);

  3568.     }


  3569.     /**
  3570.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo
  3571.      *
  3572.      * @param servizioApplicativo Servizio Applicativo
  3573.      * @param counter Indica il numero di id da ritornare
  3574.      * @return ID dei messaggi destinati ad un servizio applicativo
  3575.      *
  3576.      */
  3577.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo,int counter)throws GestoreMessaggiException{

  3578.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, counter, -1, null, null, null);

  3579.     }

  3580.     /**
  3581.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo
  3582.      *
  3583.      * @param servizioApplicativo Servizio Applicativo
  3584.      * @param counter Indica il numero di id da ritornare
  3585.      * @param offset offset
  3586.      * @return ID dei messaggi destinati ad un servizio applicativo
  3587.      *
  3588.      */
  3589.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo,int counter, int offset)throws GestoreMessaggiException{

  3590.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, counter, offset, null, null, null);

  3591.     }


  3592.     /**
  3593.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo i quali possiedono un determinato servizio
  3594.      *
  3595.      * @param servizioApplicativo Servizio Applicativo
  3596.      * @param tipoServizio Filtro per TipoServizio
  3597.      * @param servizio Filtro per Servizio
  3598.      * @return ID dei messaggi destinati ad un servizio applicativo
  3599.      *
  3600.      */
  3601.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo,
  3602.             String tipoServizio,String servizio)throws GestoreMessaggiException{

  3603.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, -1, -1, tipoServizio, servizio, null);

  3604.     }

  3605.     /**
  3606.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo i quali possiedono un determinato servizio
  3607.      *
  3608.      * @param servizioApplicativo Servizio Applicativo
  3609.      * @param tipoServizio Filtro per TipoServizio
  3610.      * @param servizio Filtro per Servizio
  3611.      * @param counter Indica il numero di id da ritornare
  3612.      * @return ID dei messaggi destinati ad un servizio applicativo
  3613.      *
  3614.      */
  3615.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo,
  3616.             String tipoServizio,String servizio,int counter)throws GestoreMessaggiException{

  3617.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, counter, -1, tipoServizio, servizio, null);

  3618.     }

  3619.     /**
  3620.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo i quali possiedono un determinato servizio
  3621.      *
  3622.      * @param servizioApplicativo Servizio Applicativo
  3623.      * @param tipoServizio Filtro per TipoServizio
  3624.      * @param servizio Filtro per Servizio
  3625.      * @param counter Indica il numero di id da ritornare
  3626.      * @param offset offset
  3627.      * @return ID dei messaggi destinati ad un servizio applicativo
  3628.      *
  3629.      */
  3630.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo,
  3631.             String tipoServizio,String servizio,int counter, int offset)throws GestoreMessaggiException{

  3632.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, counter, offset, tipoServizio, servizio, null);

  3633.     }

  3634.     /**
  3635.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo i quali possiedono un determinato servizio e azione
  3636.      *
  3637.      * @param servizioApplicativo Servizio Applicativo
  3638.      * @param tipoServizio Filtro per TipoServizio
  3639.      * @param servizio Filtro per Servizio
  3640.      * @param azione Filtro per Azione
  3641.      * @return ID dei messaggi destinati ad un servizio applicativo
  3642.      *
  3643.      */
  3644.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo,
  3645.             String tipoServizio,String servizio,String azione)throws GestoreMessaggiException{

  3646.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, -1, -1, tipoServizio, servizio, azione);

  3647.     }

  3648.     /**
  3649.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo i quali possiedono un determinato servizio e azione
  3650.      *
  3651.      * @param servizioApplicativo Servizio Applicativo
  3652.      * @param tipoServizio Filtro per TipoServizio
  3653.      * @param servizio Filtro per Servizio
  3654.      * @param azione Filtro per Azione
  3655.      * @param counter Indica il numero di id da ritornare
  3656.      * @return ID dei messaggi destinati ad un servizio applicativo
  3657.      *
  3658.      */
  3659.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo,
  3660.             String tipoServizio,String servizio,String azione,int counter)throws GestoreMessaggiException{

  3661.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, counter, -1, tipoServizio, servizio, azione);

  3662.     }

  3663.     /**
  3664.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo i quali possiedono un determinato servizio e azione
  3665.      *
  3666.      * @param servizioApplicativo Servizio Applicativo
  3667.      * @param tipoServizio Filtro per TipoServizio
  3668.      * @param servizio Filtro per Servizio
  3669.      * @param azione Filtro per Azione
  3670.      * @param counter Indica il numero di id da ritornare
  3671.      * @param offset offset
  3672.      * @return ID dei messaggi destinati ad un servizio applicativo
  3673.      *
  3674.      */
  3675.     public List<IdentificativoIM> getIDMessaggi_ServizioApplicativo(String servizioApplicativo,
  3676.             String tipoServizio,String servizio,String azione,int counter, int offset)throws GestoreMessaggiException{

  3677.         return this.getIDMessaggi_ServizioApplicativo_engine(servizioApplicativo, counter, offset, tipoServizio, servizio, azione);

  3678.     }





  3679.     /**
  3680.      * Ritorna gli ID dei messaggi destinati ad un servizio applicativo
  3681.      *
  3682.      * @param servizioApplicativo Servizio Applicativo
  3683.      * @param counter Indica il numero di id da ritornare
  3684.      * @param tipoServizio Filtro per TipoServizio
  3685.      * @param servizio Filtro per Servizio
  3686.      * @param azione Filtro per Azione
  3687.      * @return ID dei messaggi destinati ad un servizio applicativo
  3688.      *
  3689.      */
  3690.     private List<IdentificativoIM> getIDMessaggi_ServizioApplicativo_engine(String servizioApplicativo,
  3691.             int counterParam,int offset,String tipoServizio,String servizio,String azione)throws GestoreMessaggiException{

  3692.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  3693.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  3694.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  3695.             Connection connectionDB = stateful.getConnectionDB();
  3696.             PreparedStatement pstmt = null;
  3697.             ResultSet rs = null;
  3698.             List<IdentificativoIM> ids = new ArrayList<IdentificativoIM>();
  3699.             String queryString = null;
  3700.             try{
  3701.                
  3702.                 int limit = counterParam;
  3703.                 if(limit<=0) {
  3704.                     Integer defaultV = this.propertiesReader.getIntegrationManagerIdsLimit();
  3705.                     if(defaultV!=null && defaultV.intValue()>0) {
  3706.                         limit = defaultV.intValue();
  3707.                     }
  3708.                 }
  3709.                
  3710.                 // Calcolo data minima
  3711.                 queryString = getQueryStringGetAllMessagesId(servizioApplicativo,
  3712.                         limit, offset, tipoServizio, servizio, azione,
  3713.                         true);
  3714.                 pstmt = connectionDB.prepareStatement(queryString);
  3715.                 setPreparedStatementGetAllMessagesId(pstmt,
  3716.                         servizioApplicativo,
  3717.                         tipoServizio,servizio,azione,
  3718.                         null);
  3719.                 //System.out.println("QUERY MIN DATE ID MESSAGGI IS: ["+queryString+"]");
  3720.                 rs = pstmt.executeQuery();
  3721.                 Timestamp minDate = null;
  3722.                 if(rs.next()) {
  3723.                     minDate = rs.getTimestamp("MinOraRegistrazione");
  3724.                 }
  3725.                 rs.close();
  3726.                 pstmt.close();
  3727.                
  3728.                 if(minDate!=null) {
  3729.                
  3730.                     // Effettuo ricerca ID DEL SERVIZIO APPLICATIVO
  3731.    
  3732.                     queryString = getQueryStringGetAllMessagesId(servizioApplicativo,
  3733.                             limit, offset, tipoServizio, servizio, azione,
  3734.                             false);
  3735.                     //System.out.println("QUERY ID MESSAGGI IS: ["+queryString+"]");
  3736.    
  3737.                     pstmt = connectionDB.prepareStatement(queryString);
  3738.                     setPreparedStatementGetAllMessagesId(pstmt,
  3739.                             servizioApplicativo,
  3740.                             tipoServizio,servizio,azione,
  3741.                             minDate);
  3742.                     rs = pstmt.executeQuery();
  3743.    
  3744.    
  3745.                     int countLimit = 0;
  3746.                     while(rs.next()){
  3747.                        
  3748.                         IdentificativoIM idIM = new IdentificativoIM(rs.getString("IdMsgServizioApplicativo"), rs.getTimestamp("OraMessaggio"));
  3749.                         ids.add(idIM);
  3750.                        
  3751.                         // LIMIT Applicativo
  3752.                         if(limit>=0 && Configurazione.getSqlQueryObjectType()==null){
  3753.                             countLimit++;
  3754.                             if(countLimit==limit)
  3755.                                 break;
  3756.                         }
  3757.                     }
  3758.                     rs.close();
  3759.                     pstmt.close();
  3760.                    
  3761.                 }

  3762.             } catch(Exception e) {
  3763.                 String errorMsg = "[GestoreMessaggi.getIDMessaggi_ServizioApplicativo_engine] errore, queryString["+queryString+"]: "+e.getMessage();      
  3764.                 try{
  3765.                     if(rs != null)
  3766.                         rs.close();
  3767.                 } catch(Exception er) {
  3768.                     // close
  3769.                 }
  3770.                 try{
  3771.                     if(pstmt != null)
  3772.                         pstmt.close();
  3773.                 } catch(Exception er) {
  3774.                     // close
  3775.                 }
  3776.                 this.log.error(errorMsg,e);
  3777.                 throw new GestoreMessaggiException(errorMsg,e);
  3778.             }

  3779.             return ids;
  3780.             //          }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  3781.             //          //TODO Metodo stateful only
  3782.             //          return null;
  3783.             // do the right thing
  3784.         }else{
  3785.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  3786.         }
  3787.     }
  3788.    
  3789.     private String getQueryStringGetAllMessagesId(String servizioApplicativo,
  3790.             int counter,int offset,String tipoServizio,String servizio,String azione,
  3791.             boolean findMinDate) throws Exception {
  3792.         String queryString = null;
  3793.         if(Configurazione.getSqlQueryObjectType()==null){

  3794.             if(offset>=0){
  3795.                 throw new GestoreMessaggiException("La funzione di ricerca tramite offset e limit non e' utilizzabile se nella configurazione della PdD non viene specificato il tipo di database");
  3796.             }

  3797.             StringBuilder query = new StringBuilder();
  3798.             query.append("SELECT ");

  3799.             // Select
  3800.             if(findMinDate) {
  3801.                 query.append("MIN(");
  3802.                 query.append(GestoreMessaggi.MESSAGGI);
  3803.                 query.append(".ORA_REGISTRAZIONE) as MinOraRegistrazione ");
  3804.             }
  3805.             else {
  3806.                 query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  3807.                 query.append(".ID_MESSAGGIO as IdMsgServizioApplicativo, ");
  3808.                 query.append(GestoreMessaggi.MESSAGGI);
  3809.                 query.append(".ORA_REGISTRAZIONE as OraMessaggio ");
  3810.             }
  3811.            
  3812.             query.append(" FROM ");

  3813.             // FROM
  3814.             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  3815.             query.append(",");
  3816.             query.append(GestoreMessaggi.MESSAGGI);
  3817.             if(tipoServizio!=null || servizio!=null || azione!=null){
  3818.                 query.append(",");
  3819.                 query.append(Costanti.REPOSITORY);
  3820.             }
  3821.             query.append(" WHERE ");

  3822.             // join MSG_SERVIZI_APPLICATIVI con MESSAGGI
  3823.             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  3824.             query.append(".ID_MESSAGGIO=");
  3825.             query.append(GestoreMessaggi.MESSAGGI);
  3826.             query.append(".ID_MESSAGGIO AND ");

  3827.             if(tipoServizio!=null || servizio!=null || azione!=null){
  3828.                 // join REPOSITORY_BUSTE con MESSAGGI
  3829.                 query.append(Costanti.REPOSITORY);
  3830.                 query.append(".ID_MESSAGGIO=");
  3831.                 query.append(GestoreMessaggi.MESSAGGI);
  3832.                 query.append(".ID_MESSAGGIO AND ");
  3833.                 query.append(Costanti.REPOSITORY);
  3834.                 query.append(".TIPO=");
  3835.                 query.append(GestoreMessaggi.MESSAGGI);
  3836.                 query.append(".TIPO AND ");
  3837.             }

  3838.             // Selezione messaggio del servizio applicativo
  3839.             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  3840.             query.append(".SERVIZIO_APPLICATIVO=? AND ");
  3841.             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  3842.             query.append(".INTEGRATION_MANAGER=1 AND ");
  3843.             query.append(GestoreMessaggi.MESSAGGI);
  3844.             query.append(".TIPO=? AND ");
  3845.             query.append(GestoreMessaggi.MESSAGGI);
  3846.             query.append(".PROPRIETARIO=? ");
  3847.             if(!findMinDate) {
  3848.                 query.append("AND ");
  3849.                 query.append(GestoreMessaggi.MESSAGGI);
  3850.                 query.append(".ORA_REGISTRAZIONE>=? ");
  3851.             }

  3852.             // Filtro busta
  3853.             if(tipoServizio!=null){
  3854.                 query.append("AND ");
  3855.                 query.append(Costanti.REPOSITORY);
  3856.                 query.append(".TIPO_SERVIZIO=? ");
  3857.             }
  3858.             if(servizio!=null){
  3859.                 query.append("AND ");
  3860.                 query.append(Costanti.REPOSITORY);
  3861.                 query.append(".SERVIZIO=? ");
  3862.             }
  3863.             if(azione!=null){
  3864.                 query.append("AND ");
  3865.                 query.append(Costanti.REPOSITORY);
  3866.                 query.append(".AZIONE=? ");
  3867.             }

  3868.             // Ordine risultato
  3869.             if(!findMinDate) {
  3870.                 query.append("ORDER BY ");
  3871.                 query.append(GestoreMessaggi.MESSAGGI);
  3872.                 query.append(".ORA_REGISTRAZIONE,");
  3873.                 query.append(GestoreMessaggi.MESSAGGI);
  3874.                 query.append(".ID_MESSAGGIO");
  3875.             }
  3876.             queryString = query.toString();
  3877.         }else{
  3878.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  3879.             //  FROM
  3880.             sqlQueryObject.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  3881.             sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  3882.             if(tipoServizio!=null || servizio!=null || azione!=null){
  3883.                 sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  3884.             }
  3885.            
  3886.             // Select
  3887.             if(findMinDate) {
  3888.                 sqlQueryObject.addSelectMinField(GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE", "MinOraRegistrazione");
  3889.             }
  3890.             else {
  3891.                 sqlQueryObject.addSelectAliasField(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,"ID_MESSAGGIO","IdMsgServizioApplicativo");
  3892.                 sqlQueryObject.addSelectAliasField(GestoreMessaggi.MESSAGGI,"ID_MESSAGGIO","IdBustaMessaggio");
  3893.                 sqlQueryObject.addSelectAliasField(GestoreMessaggi.MESSAGGI,"TIPO","TipoMessaggio");
  3894.                 sqlQueryObject.addSelectAliasField(GestoreMessaggi.MESSAGGI,"ORA_REGISTRAZIONE","OraMessaggio");
  3895.                 sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,"PROPRIETARIO");
  3896.                 sqlQueryObject.addSelectField(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,"SERVIZIO_APPLICATIVO");
  3897.                 sqlQueryObject.addSelectField(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,"INTEGRATION_MANAGER");
  3898.             }

  3899.             sqlQueryObject.setANDLogicOperator(true);
  3900.                        
  3901.             // join MSG_SERVIZI_APPLICATIVI con MESSAGGI
  3902.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ID_MESSAGGIO="+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO");

  3903.             if(tipoServizio!=null || servizio!=null || azione!=null){
  3904.                 // join REPOSITORY_BUSTE con MESSAGGI
  3905.                 if(!findMinDate) {
  3906.                     sqlQueryObject.addSelectAliasField(Costanti.REPOSITORY,"ID_MESSAGGIO","IdBustaRepositoryBuste");
  3907.                     sqlQueryObject.addSelectAliasField(Costanti.REPOSITORY,"TIPO","TipoBustaRepositoryBuste");
  3908.                     sqlQueryObject.addSelectAliasField(Costanti.REPOSITORY,"ORA_REGISTRAZIONE","OraRepositoryBuste"); // per risolvere ambiguita oracle con OraRegistrazione dei messaggi
  3909.                 }
  3910.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".ID_MESSAGGIO="+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO");
  3911.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".TIPO="+GestoreMessaggi.MESSAGGI+".TIPO");
  3912.             }

  3913.             //  Selezione messaggio del servizio applicativo
  3914.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SERVIZIO_APPLICATIVO=?");
  3915.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".INTEGRATION_MANAGER=1");
  3916.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".TIPO=?");
  3917.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".PROPRIETARIO=?");
  3918.             if(!findMinDate) {
  3919.                 sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE>=?");
  3920.             }

  3921.             // Filtro busta
  3922.             if(tipoServizio!=null){
  3923.                 if(!findMinDate) {
  3924.                     sqlQueryObject.addSelectField(Costanti.REPOSITORY,"TIPO_SERVIZIO");
  3925.                 }
  3926.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".TIPO_SERVIZIO=?");
  3927.             }
  3928.             if(servizio!=null){
  3929.                 if(!findMinDate) {
  3930.                     sqlQueryObject.addSelectField(Costanti.REPOSITORY,"SERVIZIO");
  3931.                 }
  3932.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".SERVIZIO=?");
  3933.             }
  3934.             if(azione!=null){
  3935.                 if(!findMinDate) {
  3936.                     sqlQueryObject.addSelectField(Costanti.REPOSITORY,"AZIONE");
  3937.                 }
  3938.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".AZIONE=?");
  3939.             }

  3940.             if(!findMinDate) {
  3941.                 // Ordine risultato
  3942.                 sqlQueryObject.addOrderBy("OraMessaggio");
  3943.                 sqlQueryObject.addOrderBy("IdBustaMessaggio");
  3944.                 sqlQueryObject.setSortType(true);

  3945.                 // Limit
  3946.                 if(counter>=0)
  3947.                     sqlQueryObject.setLimit(counter);

  3948.                 // Offset
  3949.                 if(offset>=0)
  3950.                     sqlQueryObject.setOffset(offset);
  3951.             }

  3952.             queryString = sqlQueryObject.createSQLQuery();
  3953.         }
  3954.         return queryString;
  3955.     }
  3956.    
  3957.     private void setPreparedStatementGetAllMessagesId(PreparedStatement pstmt,
  3958.             String servizioApplicativo,
  3959.             String tipoServizio,String servizio,String azione,
  3960.             Timestamp minDate) throws Exception {
  3961.         pstmt.setString(1,servizioApplicativo);
  3962.         pstmt.setString(2,Costanti.INBOX);
  3963.         pstmt.setString(3,ConsegnaContenutiApplicativi.ID_MODULO);

  3964.         int indexPstmt = 4;
  3965.         if(minDate!=null) {
  3966.             pstmt.setTimestamp(indexPstmt,minDate);
  3967.             indexPstmt++;
  3968.         }
  3969.         if(tipoServizio!=null){
  3970.             pstmt.setString(indexPstmt,tipoServizio);
  3971.             indexPstmt++;
  3972.         }
  3973.         if(servizio!=null){
  3974.             pstmt.setString(indexPstmt,servizio);
  3975.             indexPstmt++;
  3976.         }
  3977.         if(azione!=null){
  3978.             pstmt.setString(indexPstmt,azione);
  3979.             indexPstmt++;
  3980.         }
  3981.     }








  3982.     /* ------------- ELIMINAZIONE DESTINATARIO MESSAGGI (SIL) -------------- */
  3983.     /**
  3984.      * Elimina dalla Tabella MSG_SERVIZI_APPLICATIVI l'entry che possiede l'ID del messaggio e il servizioApplicativo
  3985.      * passato come parametro.
  3986.      * Effettua poi un controllo sulla tabella per verificare che esistano altri servizi applicativi che sono
  3987.      * interessati al messaggio identificato dall'ID. Se ne esistono, il metodo termina.
  3988.      * Se non vi sono altri servizi applicativi, il metodo elimina dalla Tabella MESSAGGIO il messaggio che possiede l'ID,
  3989.      * ed inoltre effettua una deleteFromDB e deleteFromFileSystem del messaggio salvato precedentemente.
  3990.      *
  3991.      * @param servizioApplicativo ServizioApplicativo
  3992.      * @param riferimentoMessaggio Eventuale messaggio riferito
  3993.      * @deprecated utilizzare la versione non serializable
  3994.      */
  3995.     @Deprecated
  3996.     public void eliminaDestinatarioMessaggio_serializable(String servizioApplicativo,String riferimentoMessaggio)throws GestoreMessaggiException{
  3997.         this.eliminaDestinatarioMessaggio_serializable(servizioApplicativo,riferimentoMessaggio,Costanti.GESTIONE_SERIALIZABLE_ATTESA_ATTIVA,Costanti.GESTIONE_SERIALIZABLE_CHECK_INTERVAL);
  3998.     }

  3999.     /**
  4000.      * Elimina dalla Tabella MSG_SERVIZI_APPLICATIVI l'entry che possiede l'ID del messaggio e il servizioApplicativo
  4001.      * passato come parametro.
  4002.      * Effettua poi un controllo sulla tabella per verificare che esistano altri servizi applicativi che sono
  4003.      * interessati al messaggio identificato dall'ID. Se ne esistono, il metodo termina.
  4004.      * Se non vi sono altri servizi applicativi, il metodo elimina dalla Tabella MESSAGGIO il messaggio che possiede l'ID,
  4005.      * ed inoltre effettua una deleteFromDB e deleteFromFileSystem del messaggio salvato precedentemente.
  4006.      *
  4007.      * @param servizioApplicativo ServizioApplicativo
  4008.      * @param riferimentoMessaggio Eventuale messaggio riferito
  4009.      * @param attesaAttiva AttesaAttiva per la gestione del livello di serializable
  4010.      * @param checkInterval Intervallo di check per la gestione  del livello di serializable
  4011.      * @deprecated utilizzare la versione non serializable
  4012.      */
  4013.     @Deprecated
  4014.     public void eliminaDestinatarioMessaggio_serializable(String servizioApplicativo,String riferimentoMessaggio,
  4015.             long attesaAttiva,int checkInterval)throws GestoreMessaggiException{
  4016.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  4017.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  4018.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  4019.             Connection connectionDB = stateful.getConnectionDB();
  4020.             /*
  4021.       Viene realizzato con livello di isolamento SERIALIZABLE, per essere sicuri
  4022.       che esecuzioni parallele non leggano dati inconsistenti.
  4023.       Con il livello SERIALIZABLE, se ritorna una eccezione, deve essere riprovato
  4024.              */
  4025.             // setAutoCommit e livello Isolamento
  4026.             int oldTransactionIsolation = -1;
  4027.             try{
  4028.                 oldTransactionIsolation = connectionDB.getTransactionIsolation();
  4029.                 connectionDB.setAutoCommit(false);
  4030.                 JDBCUtilities.setTransactionIsolationSerializable(this.propertiesReader.getDatabaseType(), connectionDB);
  4031.             } catch(Exception er) {
  4032.                 String errorMsg = "GESTORE_MESSAGGI, error  eliminaDestinatarioMessaggio (setIsolation)"+this.idBusta+"/"+servizioApplicativo+": "+er.getMessage();    
  4033.                 this.log.error(errorMsg,er);
  4034.                 throw new GestoreMessaggiException(errorMsg,er);
  4035.             }


  4036.             // ELIMINAZIONE DESTINATARIO
  4037.             boolean deleteDestinatarioOK = false;
  4038.             //int silDelete = -1;

  4039.             long scadenzaWhile = DateManager.getTimeMillis() + attesaAttiva;

  4040.             while(deleteDestinatarioOK==false && DateManager.getTimeMillis() < scadenzaWhile){

  4041.                 PreparedStatement pstmtDeleteSIL = null;
  4042.                 try{

  4043.                     // Costruzione Query
  4044.                     String query = "DELETE FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" WHERE ID_MESSAGGIO=? AND SERVIZIO_APPLICATIVO=?";
  4045.                     //log.debug("Query: "+query);
  4046.                     pstmtDeleteSIL=connectionDB.prepareStatement(query);
  4047.                     pstmtDeleteSIL.setString(1,this.idBusta);
  4048.                     pstmtDeleteSIL.setString(2,servizioApplicativo);
  4049.                     //silDelete = pstmtDeleteSIL.executeUpdate();
  4050.                     pstmtDeleteSIL.executeUpdate();
  4051.                     pstmtDeleteSIL.close();

  4052.                     // Chiusura Transazione
  4053.                     connectionDB.commit();
  4054.                     stateful.updateConnection(connectionDB);
  4055.                     if(this.isRichiesta) this.openspcoopstate.setStatoRichiesta(stateful);
  4056.                     else this.openspcoopstate.setStatoRisposta(stateful);
  4057.                     // Eliminazione Destinatario effettuata
  4058.                     deleteDestinatarioOK = true;

  4059.                 } catch(Exception e) {
  4060.                     //log.error("ERROR ELIMINAZIONE DESTINATARIO MESSAGGIO ["+e.getMessage()+"]");
  4061.                     try{
  4062.                         if( pstmtDeleteSIL != null  )
  4063.                             pstmtDeleteSIL.close();
  4064.                     } catch(Exception er) {
  4065.                         // close
  4066.                     }
  4067.                     try{
  4068.                         connectionDB.rollback();
  4069.                         stateful.updateConnection(connectionDB);
  4070.                         if(this.isRichiesta) this.openspcoopstate.setStatoRichiesta(stateful);
  4071.                         else this.openspcoopstate.setStatoRisposta(stateful);
  4072.                     } catch(Exception er) {
  4073.                         // ignore
  4074.                     }
  4075.                 }

  4076.                 if(deleteDestinatarioOK == false){
  4077.                     // Per aiutare ad evitare conflitti
  4078.                     try{
  4079.                         Utilities.sleep((getRandom()).nextInt(checkInterval)); // random da 0ms a checkIntervalms
  4080.                     }catch(Exception eRandom){
  4081.                         // ignore
  4082.                     }
  4083.                 }
  4084.             }


  4085.             // Se ho eliminato un sil
  4086.             // (puo' darsi che accessi sincronizzati di Gop e ConsegneContenutiApplicativi faccino uno il lavoro per l'altro)
  4087.             //if(silDelete>0){


  4088.             // ELIMINAZIONE RIFERIMENTO MSG
  4089.             boolean deleteRiferimentoMsgOK = false;
  4090.             boolean eliminazioneRifCompleta = false;

  4091.             scadenzaWhile = DateManager.getTimeMillis() + attesaAttiva;

  4092.             while(deleteRiferimentoMsgOK==false && DateManager.getTimeMillis() < scadenzaWhile){

  4093.                 PreparedStatement pstmtUpdateMsg= null;
  4094.                 PreparedStatement pstmt = null;
  4095.                 ResultSet rs = null;
  4096.                 try{


  4097.                     // VERIFICA SE CI SONO ALTRI DESTINATARI
  4098.                     String query = "SELECT  * FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" WHERE ID_MESSAGGIO=? FOR UPDATE";
  4099.                     //log.debug("Query: "+query);
  4100.                     pstmt = connectionDB.prepareStatement(query);
  4101.                     pstmt.setString(1,this.idBusta);
  4102.                     rs = pstmt.executeQuery();
  4103.                     eliminazioneRifCompleta = !rs.next();

  4104.                     /*
  4105.               if(eliminazioneRifCompleta==false){
  4106.               log.info("---------------------");
  4107.               log.info("-------ELIMINATO["+servizioApplicativo+"]--------------");
  4108.               log.info("------- ["+rs.getString("SERVIZIO_APPLICATIVO")+"] ---------");
  4109.               while(rs.next())
  4110.               log.info("------- ["+rs.getString("SERVIZIO_APPLICATIVO")+"] ---------");
  4111.               log.info("---------------------");
  4112.               }else{
  4113.               log.info("ELIMINAZIONE COMPLETA");
  4114.               }
  4115.                      */

  4116.                     rs.close();
  4117.                     pstmt.close();


  4118.                     // ELIMINAZIONE MESSAGGIO
  4119.                     if (eliminazioneRifCompleta) {      

  4120.                         // Imposto lo stato del messaggio ad 'eliminabile'
  4121.                         // Costruzione Query
  4122.                         StringBuilder queryUpdate = new StringBuilder();
  4123.                         queryUpdate.append("UPDATE ");
  4124.                         queryUpdate.append(GestoreMessaggi.MESSAGGI);
  4125.                         queryUpdate.append(" SET PROPRIETARIO=? WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  4126.                         pstmtUpdateMsg =  connectionDB.prepareStatement(queryUpdate.toString());
  4127.                         pstmtUpdateMsg.setString(1,TimerGestoreMessaggi.ID_MODULO);
  4128.                         pstmtUpdateMsg.setString(2,this.idBusta);
  4129.                         pstmtUpdateMsg.setString(3,Costanti.INBOX); // i messaggi con destinatari sono tutti di tipo 'INBOX'
  4130.                         pstmtUpdateMsg.execute();
  4131.                         pstmtUpdateMsg.close();

  4132.                         // Add Proprietario into table
  4133.                         this.addProprietarioIntoTable(Costanti.INBOX, this.idBusta, TimerGestoreMessaggi.ID_MODULO);

  4134.                     }
  4135.                     //else
  4136.                     //  log.info("ELIMINAZIONE PARZIALE");


  4137.                     // Chiusura Transazione
  4138.                     connectionDB.commit();
  4139.                     stateful.updateConnection(connectionDB);
  4140.                     if(this.isRichiesta) this.openspcoopstate.setStatoRichiesta(stateful);
  4141.                     else this.openspcoopstate.setStatoRisposta(stateful);

  4142.                     // Eliminazione Destinatario effettuata
  4143.                     deleteRiferimentoMsgOK = true;

  4144.                 } catch(Exception e) {
  4145.                     //log.error("ERROR ELIMINAZIONE DESTINATARIO MESSAGGIO ["+e.getMessage()+"]");
  4146.                     try{
  4147.                         if( pstmtUpdateMsg != null )
  4148.                             pstmtUpdateMsg.close();
  4149.                     } catch(Exception er) {
  4150.                         // close
  4151.                     }
  4152.                     try{
  4153.                         if( rs != null )
  4154.                             rs.close();
  4155.                     } catch(Exception er) {
  4156.                         // close
  4157.                     }
  4158.                     try{
  4159.                         if( pstmt != null )
  4160.                             pstmt.close();
  4161.                     } catch(Exception er) {
  4162.                         // close
  4163.                     }
  4164.                     try{
  4165.                         connectionDB.rollback();
  4166.                         stateful.updateConnection(connectionDB);
  4167.                         if(this.isRichiesta) this.openspcoopstate.setStatoRichiesta(stateful);
  4168.                         else this.openspcoopstate.setStatoRisposta(stateful);
  4169.                     } catch(Exception er) {
  4170.                         // ignore
  4171.                     }
  4172.                 }

  4173.                 if(deleteRiferimentoMsgOK == false){
  4174.                     // Per aiutare ad evitare conflitti
  4175.                     try{
  4176.                         Utilities.sleep((getRandom()).nextInt(checkInterval)); // random da 0ms a checkIntervalms
  4177.                     }catch(Exception eRandom){
  4178.                         // ignore
  4179.                     }
  4180.                 }

  4181.                 if(eliminazioneRifCompleta){
  4182.                     // Aggiornamento cache proprietario messaggio
  4183.                     this.addProprietariIntoCache_readFromTable("GestoreMessaggi", "eliminaDestinatarioMessaggio_serializable",riferimentoMessaggio,false);
  4184.                 }
  4185.             }
  4186.             //}

  4187.             // Ripristino Transazione
  4188.             try{
  4189.                 connectionDB.setTransactionIsolation(oldTransactionIsolation);
  4190.                 connectionDB.setAutoCommit(true);
  4191.                 stateful.updateConnection(connectionDB);
  4192.                 if(this.isRichiesta) this.openspcoopstate.setStatoRichiesta(stateful);
  4193.                 else this.openspcoopstate.setStatoRisposta(stateful);
  4194.             } catch(Exception er) {
  4195.                 String errorMsg = "GESTORE_MESSAGGI, error  eliminaDestinatarioMessaggio (ripristinoIsolation)"+this.idBusta+"/"+servizioApplicativo+": "+er.getMessage();      
  4196.                 this.log.error(errorMsg,er);
  4197.                 throw new GestoreMessaggiException(errorMsg,er);
  4198.             }
  4199.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  4200.             //TODO checkme NOP
  4201.         }else{
  4202.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  4203.         }
  4204.     }

  4205.     /**
  4206.      * Elimina dalla Tabella MSG_SERVIZI_APPLICATIVI l'entry che possiede l'ID del messaggio e il servizioApplicativo
  4207.      * passato come parametro.
  4208.      * Effettua poi un controllo sulla tabella per verificare che esistano altri servizi applicativi che sono
  4209.      * interessati al messaggio identificato dall'ID. Se ne esistono, il metodo termina.
  4210.      * Se non vi sono altri servizi applicativi, il metodo elimina dalla Tabella MESSAGGIO il messaggio che possiede l'ID,
  4211.      * ed inoltre effettua una deleteFromDB e deleteFromFileSystem del messaggio salvato precedentemente.
  4212.      *
  4213.      * @param servizioApplicativo ServizioApplicativo
  4214.      * @param riferimentoMessaggio Eventuale messaggio riferito
  4215.      */
  4216.     public void eliminaDestinatarioMessaggio(String servizioApplicativo, String riferimentoMessaggio)throws GestoreMessaggiException{
  4217.         eliminaDestinatarioMessaggio(servizioApplicativo, riferimentoMessaggio, null);
  4218.     }
  4219.     public void eliminaDestinatarioMessaggio(String servizioApplicativo, String riferimentoMessaggio, Date oraRegistrazione)throws GestoreMessaggiException{
  4220.         if(this.openspcoopstate instanceof OpenSPCoopStateful || this.oneWayVersione11) {
  4221.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  4222.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  4223.             Connection connectionDB = stateMSG.getConnectionDB();

  4224.             Timestamp leftValue = null;
  4225.             Timestamp rightValue = null;
  4226.             if(oraRegistrazione!=null) {
  4227.                 leftValue = new Timestamp(oraRegistrazione.getTime() - (1000*60*5));
  4228.                 rightValue = new Timestamp(oraRegistrazione.getTime() + (1000*60*5));
  4229.             }
  4230.            
  4231.             PreparedStatement pstmtDeleteSIL = null;
  4232.             try{

  4233.                 //this.log.debug("DELETE MSG_SERVIZI_APPLICATIVI WHERE ID_MESSAGGIO='"+this.idBusta+"' AND SERVIZIO_APPLICATIVO='"+servizioApplicativo+"'");

  4234.                 // Costruzione Query
  4235.                 String query = "DELETE FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" WHERE ";
  4236.                 if(oraRegistrazione!=null) {
  4237.                     query = query +"( ORA_REGISTRAZIONE BETWEEN ? AND ?) AND ";
  4238.                 }
  4239.                 query = query +" ID_MESSAGGIO=? AND SERVIZIO_APPLICATIVO=?";
  4240.                
  4241.                 //log.debug("Query: "+query);
  4242.                 pstmtDeleteSIL= connectionDB.prepareStatement(query);
  4243.                 int index = 1;
  4244.                
  4245.                 if(oraRegistrazione!=null) {
  4246.                     pstmtDeleteSIL.setTimestamp(index++,leftValue);
  4247.                     pstmtDeleteSIL.setTimestamp(index++,rightValue);
  4248.                 }
  4249.                
  4250.                 pstmtDeleteSIL.setString(index++,this.idBusta);
  4251.                 pstmtDeleteSIL.setString(index++,servizioApplicativo);

  4252.                 pstmtDeleteSIL.executeUpdate();
  4253.                 pstmtDeleteSIL.close();

  4254.             } catch(Exception e) {
  4255.                 try{
  4256.                     if( pstmtDeleteSIL != null  )
  4257.                         pstmtDeleteSIL.close();
  4258.                 } catch(Exception er) {
  4259.                     // close
  4260.                 }
  4261.                 String msgError = "ERROR ELIMINAZIONE DESTINATARIO MESSAGGIO: "+e.getMessage();
  4262.                 this.log.error(msgError,e);
  4263.                 throw new GestoreMessaggiException(msgError,e);
  4264.             }

  4265.             PreparedStatement pstmtUpdateMsg= null;
  4266.             PreparedStatement pstmt = null;
  4267.             ResultSet rs = null;
  4268.             try{


  4269.                 // VERIFICA SE CI SONO ALTRI DESTINATARI
  4270.                 String query = "SELECT  * FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" WHERE ";
  4271.                 if(oraRegistrazione!=null) {
  4272.                     query = query +"( ORA_REGISTRAZIONE BETWEEN ? AND ?) AND ";
  4273.                 }
  4274.                 query = query +"ID_MESSAGGIO=?";
  4275.                            
  4276.                 //log.debug("Query: "+query);
  4277.                 pstmt =  connectionDB.prepareStatement(query);
  4278.                 int index = 1;
  4279.                
  4280.                 if(oraRegistrazione!=null) {
  4281.                     pstmt.setTimestamp(index++,leftValue);
  4282.                     pstmt.setTimestamp(index++,rightValue);
  4283.                 }
  4284.                
  4285.                 pstmt.setString(index++,this.idBusta);
  4286.                 rs = pstmt.executeQuery();
  4287.                 boolean eliminazioneRifCompleta = !rs.next();

  4288.                 /*
  4289.           if(eliminazioneRifCompleta==false){
  4290.           log.info("---------------------");
  4291.           log.info("-------ELIMINATO["+servizioApplicativo+"]--------------");
  4292.           log.info("------- ["+rs.getString("SERVIZIO_APPLICATIVO")+"] ---------");
  4293.           while(rs.next())
  4294.           log.info("------- ["+rs.getString("SERVIZIO_APPLICATIVO")+"] ---------");
  4295.           log.info("---------------------");
  4296.           }else{
  4297.           log.info("ELIMINAZIONE COMPLETA");
  4298.           }
  4299.                  */

  4300.                 rs.close();
  4301.                 pstmt.close();


  4302.                 // ELIMINAZIONE MESSAGGIO
  4303.                 if (eliminazioneRifCompleta) {      

  4304.                     // Elimino utilizzo

  4305.                     RepositoryBuste repositoryBuste= new RepositoryBuste(stateMSG, this.isRichiesta, this.protocolFactory);
  4306.                     repositoryBuste.eliminaUtilizzoPdDFromInBox(this.idBusta, oraRegistrazione);

  4307.                     if (this.oneWayVersione11) {
  4308.                         repositoryBuste.eliminaBustaStatelessFromInBox(this.idBusta, oraRegistrazione);
  4309.                     }

  4310.                     // Imposto lo stato del messaggio ad 'eliminabile'
  4311.                     // Costruzione Querya
  4312.                     StringBuilder queryUpdate = new StringBuilder();
  4313.                     queryUpdate.append("UPDATE ");
  4314.                     queryUpdate.append(GestoreMessaggi.MESSAGGI);
  4315.                     queryUpdate.append(" SET PROPRIETARIO=? WHERE ");
  4316.                     if(oraRegistrazione!=null) {
  4317.                         queryUpdate.append("(ORA_REGISTRAZIONE BETWEEN ? AND ?) AND ");
  4318.                     }
  4319.                     queryUpdate.append("ID_MESSAGGIO = ? AND TIPO=?");
  4320.                    
  4321.                     pstmtUpdateMsg = connectionDB.prepareStatement(queryUpdate.toString());
  4322.                     index = 1;
  4323.                     pstmtUpdateMsg.setString(index++,TimerGestoreMessaggi.ID_MODULO);
  4324.                    
  4325.                     if(oraRegistrazione!=null) {
  4326.                         pstmtUpdateMsg.setTimestamp(index++,leftValue);
  4327.                         pstmtUpdateMsg.setTimestamp(index++,rightValue);
  4328.                     }
  4329.                    
  4330.                     pstmtUpdateMsg.setString(index++,this.idBusta);
  4331.                     pstmtUpdateMsg.setString(index++,Costanti.INBOX); // i messaggi con destinatari sono tutti di tipo 'INBOX'

  4332.                     stateMSG.getPreparedStatement().put("UPDATE aggiornaProprietarioMessaggioOpenSPCoop "+this.tipo+"/"+this.idBusta,pstmtUpdateMsg);

  4333.                     // Add Proprietario into table
  4334.                     this.addProprietarioIntoTable(Costanti.INBOX, this.idBusta, TimerGestoreMessaggi.ID_MODULO);

  4335.                     // Commit
  4336.                     boolean oldValue = false;
  4337.                     if(this.oneWayVersione11){
  4338.                         oldValue = ((OpenSPCoopStateless)this.openspcoopstate).isUseConnection();
  4339.                         ((OpenSPCoopStateless)this.openspcoopstate).setUseConnection(true);
  4340.                     }
  4341.                     this.openspcoopstate.commit();
  4342.                     if(this.oneWayVersione11){
  4343.                         ((OpenSPCoopStateless)this.openspcoopstate).setUseConnection(oldValue);
  4344.                     }


  4345.                 }
  4346.                 //else
  4347.                 //  log.info("ELIMINAZIONE PARZIALE");


  4348.                 if(eliminazioneRifCompleta){
  4349.                     // Aggiornamento cache proprietario messaggio
  4350.                     this.addProprietariIntoCache_readFromTable("GestoreMessaggi", "eliminaDestinatarioMessaggio",riferimentoMessaggio,false);
  4351.                 }

  4352.                 if(this.isRichiesta) this.openspcoopstate.setStatoRichiesta(stateMSG);
  4353.                 else this.openspcoopstate.setStatoRisposta(stateMSG);


  4354.             } catch(Exception e) {
  4355.                 try{
  4356.                     if( pstmtUpdateMsg != null )
  4357.                         pstmtUpdateMsg.close();
  4358.                 } catch(Exception er) {
  4359.                     // close
  4360.                 }
  4361.                 try{
  4362.                     if( rs != null )
  4363.                         rs.close();
  4364.                 } catch(Exception er) {
  4365.                     // close
  4366.                 }
  4367.                 try{
  4368.                     if( pstmt != null )
  4369.                         pstmt.close();
  4370.                 } catch(Exception er) {
  4371.                     // close
  4372.                 }
  4373.                 String msgError = "ERROR ELIMINAZIONE DESTINATARIO MESSAGGIO, STEP 2: "+e.getMessage();
  4374.                 this.log.error(msgError,e);
  4375.                 throw new GestoreMessaggiException(msgError,e);
  4376.             }
  4377.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless && !this.oneWayVersione11){
  4378.             //NOP
  4379.         }else{
  4380.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  4381.         }

  4382.     }











  4383.     /* ------------- LETTURA MESSAGGI DA RICONSEGNARE -------------- */

  4384.     public static int abilitaSchedulingMessaggiDaRiconsegnareIntoBox(String servizioApplicativo, boolean checkEliminazioneLogica,
  4385.             Logger loggerSql, Connection connectionDB, boolean debug) throws GestoreMessaggiException{
  4386.         return _updateLockConsegnaMessaggiDaRiconsegnareIntoBox(servizioApplicativo, true,
  4387.                 checkEliminazioneLogica,
  4388.                 loggerSql, connectionDB, debug);
  4389.     }
  4390.     public static int disabilitaSchedulingMessaggiDaRiconsegnareIntoBox(String servizioApplicativo, boolean checkEliminazioneLogica,
  4391.             Logger loggerSql, Connection connectionDB, boolean debug) throws GestoreMessaggiException{
  4392.         return _updateLockConsegnaMessaggiDaRiconsegnareIntoBox(servizioApplicativo, false,
  4393.                 checkEliminazioneLogica,
  4394.                 loggerSql, connectionDB, debug);
  4395.     }
  4396.     private static int _updateLockConsegnaMessaggiDaRiconsegnareIntoBox(String servizioApplicativo, boolean abilitaScheduling, boolean checkEliminazioneLogica,
  4397.             Logger loggerSql, Connection connectionDB, boolean debug) throws GestoreMessaggiException{
  4398.    
  4399.         String idOperazione = abilitaScheduling ? "abilitaSchedulingNotificheAsincrone" : "disabilitaSchedulingNotificheAsincrone";
  4400.                
  4401.         PreparedStatement pstmt = null;
  4402.         String updateString = null;
  4403.         try{
  4404.            
  4405.             String tipoDatabase = Configurazione.getSqlQueryObjectType();
  4406.             if(tipoDatabase==null) {
  4407.                 throw new GestoreMessaggiException("Funzionalità supportata solamente se viene definito il tipo di database");
  4408.             }
  4409.            
  4410.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  4411.             sqlQueryObject.addSelectField(MESSAGGI_COLUMN_ID_MESSAGGIO);
  4412.             sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  4413.             sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_PROPRIETARIO+"<>?");
  4414.             sqlQueryObject.setANDLogicOperator(true);
  4415.            
  4416.             ISQLQueryObject sqlQueryObjectMsgServiziApplicativi = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  4417.             sqlQueryObjectMsgServiziApplicativi.addUpdateTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  4418.             sqlQueryObjectMsgServiziApplicativi.addUpdateField(MSG_SERVIZI_APPLICATIVI_COLUMN_LOCK_CONSEGNA, "?");
  4419.             sqlQueryObjectMsgServiziApplicativi.addWhereCondition(MSG_SERVIZI_APPLICATIVI_COLUMN_SERVIZIO_APPLICATIVO+"=?");
  4420.             if(checkEliminazioneLogica) {
  4421.                 sqlQueryObjectMsgServiziApplicativi.addWhereCondition(MSG_SERVIZI_APPLICATIVI_COLUMN_TIPO+"=?");
  4422.                 sqlQueryObjectMsgServiziApplicativi.addWhereINSelectSQLCondition(false, MSG_SERVIZI_APPLICATIVI_COLUMN_ID_MESSAGGIO, sqlQueryObject);
  4423.                     sqlQueryObjectMsgServiziApplicativi.setANDLogicOperator(true);
  4424.             }
  4425.             if(abilitaScheduling) {
  4426.                 sqlQueryObjectMsgServiziApplicativi.addWhereCondition(MSG_SERVIZI_APPLICATIVI_COLUMN_LOCK_CONSEGNA+"=?"); // precedentemente disabilitato
  4427.             }
  4428.             else {
  4429.                 sqlQueryObjectMsgServiziApplicativi.addWhereCondition(false,
  4430.                         MSG_SERVIZI_APPLICATIVI_COLUMN_LOCK_CONSEGNA+" is null",
  4431.                         MSG_SERVIZI_APPLICATIVI_COLUMN_LOCK_CONSEGNA+"<>?"); // gia' disabilitato
  4432.             }
  4433.             sqlQueryObjectMsgServiziApplicativi.setANDLogicOperator(true);
  4434.        
  4435.             updateString = sqlQueryObjectMsgServiziApplicativi.createSQLUpdate();
  4436.            
  4437.             pstmt = connectionDB.prepareStatement(updateString);
  4438.            
  4439.             int index = 1;
  4440.             List<Object> params = new ArrayList<>();
  4441.        
  4442.             if(abilitaScheduling) {
  4443.                 pstmt.setTimestamp(index++,null);
  4444.                 params.add("null");
  4445.             }
  4446.             else {
  4447.                 pstmt.setTimestamp(index++,TimerConsegnaContenutiApplicativiThread.LOCK_CONSEGNA_FUTURA);
  4448.                 params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(TimerConsegnaContenutiApplicativiThread.LOCK_CONSEGNA_FUTURA));
  4449.             }
  4450.                
  4451.             pstmt.setString(index++,servizioApplicativo); params.add(servizioApplicativo);
  4452.             if(checkEliminazioneLogica) {
  4453.                 pstmt.setString(index++,Costanti.INBOX); params.add(Costanti.INBOX);
  4454.                 pstmt.setString(index++,TimerGestoreMessaggi.ID_MODULO); params.add(TimerGestoreMessaggi.ID_MODULO);
  4455.             }
  4456.            
  4457.             pstmt.setTimestamp(index++,TimerConsegnaContenutiApplicativiThread.LOCK_CONSEGNA_FUTURA);
  4458.             params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(TimerConsegnaContenutiApplicativiThread.LOCK_CONSEGNA_FUTURA));
  4459.            
  4460.             long startDateSQLCommand = DateManager.getTimeMillis();
  4461.             String comandoSql = null;
  4462.             if(debug) {
  4463.                 comandoSql = DBUtils.formatSQLString(updateString, params.toArray());
  4464.                 loggerSql.debug("[UPDATE] (Messaggi."+idOperazione+") ["+comandoSql+"] ...");
  4465.             }
  4466.             int result = pstmt.executeUpdate();
  4467.             long endDateSQLCommand = DateManager.getTimeMillis();
  4468.             long diffSQLCommand = endDateSQLCommand - startDateSQLCommand;
  4469.             if(debug) {
  4470.                 loggerSql.debug("[UPDATE] (Messaggi."+idOperazione+") ["+comandoSql+"] [row:"+result+"] effettuato in "+Utilities.convertSystemTimeIntoStringMillisecondi(diffSQLCommand, true));
  4471.             }
  4472.            
  4473.             return result;
  4474.        
  4475.         } catch(Exception e) {
  4476.             String errorMsg = "[GestoreMessaggi."+idOperazione+"] errore, queryString["+updateString+"]: "+e.getMessage();
  4477.             loggerSql.error(errorMsg,e);
  4478.             throw new GestoreMessaggiException(errorMsg,e);
  4479.         }finally {
  4480.             try{
  4481.                 if(pstmt != null)
  4482.                     pstmt.close();
  4483.             } catch(Exception er) {
  4484.                 // close
  4485.             }
  4486.         }
  4487.     }
  4488.    
  4489.     public List<MessaggioServizioApplicativo> readMessaggiDaRiconsegnareIntoBoxByPriorita(int limit,
  4490.             boolean verificaPresenzaMessaggiDaRispedire, boolean calcolaDataMinimaMessaggiRispedire, Integer secondiAnzianitaPerIniziareSpedireNuovoMessaggio,
  4491.             Date riconsegna, int presaInConsegnaMaxLife,
  4492.             boolean debug, RunnableLogger loggerSql,
  4493.             String coda, String priorita)throws GestoreMessaggiException{
  4494.         return  _readMessaggiDaRiconsegnareIntoBox(limit,
  4495.                 verificaPresenzaMessaggiDaRispedire, calcolaDataMinimaMessaggiRispedire, secondiAnzianitaPerIniziareSpedireNuovoMessaggio,
  4496.                 riconsegna, presaInConsegnaMaxLife,
  4497.                 debug, loggerSql,
  4498.                 coda, priorita);
  4499.     }
  4500.     public List<MessaggioServizioApplicativo> readMessaggiDaRiconsegnareIntoBoxByServiziApplicativPrioritari(int limit,
  4501.             boolean verificaPresenzaMessaggiDaRispedire, boolean calcolaDataMinimaMessaggiRispedire, Integer secondiAnzianitaPerIniziareSpedireNuovoMessaggio,
  4502.             Date riconsegna, int presaInConsegnaMaxLife,
  4503.             boolean debug, RunnableLogger loggerSql,
  4504.             String coda, String ... serviziApplicativiPrioritari)throws GestoreMessaggiException{
  4505.         return  _readMessaggiDaRiconsegnareIntoBox(limit,
  4506.                 verificaPresenzaMessaggiDaRispedire, calcolaDataMinimaMessaggiRispedire, secondiAnzianitaPerIniziareSpedireNuovoMessaggio,
  4507.                 riconsegna, presaInConsegnaMaxLife,
  4508.                 debug, loggerSql,
  4509.                 coda, null,
  4510.                 serviziApplicativiPrioritari);
  4511.     }
  4512.    
  4513.     private List<MessaggioServizioApplicativo> _readMessaggiDaRiconsegnareIntoBox(int limit,
  4514.             boolean verificaPresenzaMessaggiDaRispedire, boolean calcolaDataMinimaMessaggiRispedire, Integer secondiAnzianitaPerIniziareSpedireNuovoMessaggio,
  4515.             Date riconsegna, int presaInConsegnaMaxLife,
  4516.             boolean debug, RunnableLogger loggerSql,
  4517.             String coda, String priorita,
  4518.             String ... serviziApplicativiPrioritari)throws GestoreMessaggiException{

  4519.         boolean verificaPresenzaMessaggiDaRispedire_consideraAncheNuoviMessaggi = true;
  4520.        
  4521.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  4522.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  4523.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  4524.             Connection connectionDB = stateful.getConnectionDB();

  4525.             List<MessaggioServizioApplicativo> idMsg = new ArrayList<MessaggioServizioApplicativo>();

  4526.             Date dataRilascioLock = new Date( DateManager.getTimeMillis() - this.propertiesReader.getTimerConsegnaContenutiApplicativiPresaInConsegnaMaxLife() );
  4527.            
  4528.             String tipo = Costanti.INBOX;
  4529.                        
  4530.             Date dataAttualeVerificaNow = DateManager.getDate();
  4531.             boolean checkOraLegale = OpenSPCoop2Properties.getInstance().isTimerConsegnaContenutiApplicativiSchedulingCheckPassaggioOraLegaleVersoOraSolare();
  4532.             boolean isMinutiMancantiPassaggioOraLegaleVersoOraSolare = false;
  4533.             if(checkOraLegale) {
  4534.                 isMinutiMancantiPassaggioOraLegaleVersoOraSolare = isMinutiMancantiPassaggioOraLegaleVersoOraSolare(debug, loggerSql, dataAttualeVerificaNow, 60); // devo verificare di non essere nella potenziale ora tornata indietro
  4535.             }
  4536.            
  4537.             if(debug) {
  4538.                 loggerSql.debug("[QUERY] Parametri ricerca (coda:"+coda+" priorita:"+priorita+"): verificaPresenzaMessaggiDaRispedire:"+verificaPresenzaMessaggiDaRispedire+" calcolaDataMinimaMessaggiRispedire:"+calcolaDataMinimaMessaggiRispedire+" isMinutiMancantiPassaggioOraLegaleVersoOraSolare:"+isMinutiMancantiPassaggioOraLegaleVersoOraSolare+"");
  4539.             }
  4540.            
  4541.             Timestamp dataMinima = null;
  4542.             if(verificaPresenzaMessaggiDaRispedire && calcolaDataMinimaMessaggiRispedire) {
  4543.                 PreparedStatement pstmt = null;
  4544.                 ResultSet rs = null;
  4545.                 String queryString = null;
  4546.                 try{

  4547.                     if(Configurazione.getSqlQueryObjectType()==null){
  4548.                         StringBuilder query = new StringBuilder();
  4549.                         query.append("SELECT min("+GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE as minOraMess ");
  4550.                        
  4551.                         query.append(" FROM ");
  4552.                         query.append(GestoreMessaggi.MESSAGGI);
  4553.                         query.append(",");
  4554.                         query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  4555.                        
  4556.                         query.append(" WHERE ");
  4557.                        
  4558.                         if(secondiAnzianitaPerIniziareSpedireNuovoMessaggio!=null && secondiAnzianitaPerIniziareSpedireNuovoMessaggio>0) {
  4559.                             // Per non prendere immediatamente i messaggi in carico ed evitare problemi di serializzazione con le tracce, se ancora non è stata scritta
  4560.                             if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  4561.                                 query.append("(");
  4562.                                
  4563.                                 // controllo che non sia nell'intervallo tra now e i precedenti x secondi
  4564.                                 query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE<=? ");
  4565.                                
  4566.                                 query.append(" OR ");
  4567.                                
  4568.                                 // se è una data futura rispetto al now la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera
  4569.                                 query.append("(");
  4570.                                 query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE>? ");
  4571.                                 query.append(" AND ");
  4572.                                 query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE<? ");
  4573.                                 query.append(")");
  4574.                                
  4575.                                 query.append(")");
  4576.                                
  4577.                                 query.append(" AND ");
  4578.                             }
  4579.                             else {
  4580.                                 query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE<=? ").append(" AND ");
  4581.                             }
  4582.                         }
  4583.                        
  4584.                         // join
  4585.                         query.append(" ");
  4586.                         query.append(GestoreMessaggi.MESSAGGI);
  4587.                         query.append(".ID_MESSAGGIO=");
  4588.                         query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  4589.                         query.append(".ID_MESSAGGIO AND ");
  4590.                        
  4591.                         query.append(" ").append(GestoreMessaggi.MESSAGGI).append(".TIPO=? AND ").
  4592.                               append(GestoreMessaggi.MESSAGGI).append(".PROPRIETARIO=? ");
  4593.                         query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".TIPO_CONSEGNA=? ");
  4594.                         query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ATTESA_ESITO=? ");
  4595.                         query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".CODA=? ");
  4596.                         if(serviziApplicativiPrioritari!=null && serviziApplicativiPrioritari.length>0) {
  4597.                             query.append(" AND (");
  4598.                             if(serviziApplicativiPrioritari.length==1) {
  4599.                                 query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".SERVIZIO_APPLICATIVO=?");
  4600.                             }
  4601.                             else {
  4602.                                 query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".SERVIZIO_APPLICATIVO IN (");
  4603.                                 for (int i = 0; i < serviziApplicativiPrioritari.length; i++) {
  4604.                                     if(i>0) {
  4605.                                         query.append(",");
  4606.                                     }
  4607.                                     query.append(serviziApplicativiPrioritari[i]);
  4608.                                 }
  4609.                                 query.append(") ");
  4610.                             }
  4611.                             query.append(")");
  4612.                         }
  4613.                         else if(priorita!=null) {
  4614.                             query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".PRIORITA=? ");
  4615.                         }
  4616.                        
  4617.                         // per non intralciare con la "prima" registrazione (forse e' un controllo inutile)
  4618.                         query.append(" AND ")
  4619.                             .append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ERRORE_PROCESSAMENTO_COMPACT is not null ");
  4620.                         if(!verificaPresenzaMessaggiDaRispedire_consideraAncheNuoviMessaggi) {
  4621.                             // per non intralciare con la "prima" consegna
  4622.                             query.append(" AND ")
  4623.                                 .append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ERRORE_PROCESSAMENTO_COMPACT <> ? ");
  4624.                         }
  4625.                        
  4626.                         if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  4627.                             query.append(" AND (");
  4628.                            
  4629.                             // data di rispedizione precedente ad adesso
  4630.                             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".RISPEDIZIONE<=? ");
  4631.                            
  4632.                             // data futura che combacia con l'ora di registrazione, la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera
  4633.                             query.append(" OR (");
  4634.                             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".RISPEDIZIONE=").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ORA_REGISTRAZIONE");
  4635.                             query.append(" AND ");
  4636.                             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".RISPEDIZIONE<=? ");
  4637.                             query.append(") ");
  4638.                            
  4639.                             query.append(") ");
  4640.                         }
  4641.                         else {
  4642.                             query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".RISPEDIZIONE<=? ");
  4643.                         }
  4644.                        
  4645.                         query.append(" AND (").
  4646.                             append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".LOCK_CONSEGNA is null ").
  4647.                             append(" OR ").
  4648.                             append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".LOCK_CONSEGNA < ? ").
  4649.                             append(")");
  4650.                        
  4651.                         queryString = query.toString();
  4652.                     }else{

  4653.                         ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  4654.                         sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI,"m");
  4655.                         sqlQueryObject.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,"sa");

  4656.                         sqlQueryObject.addSelectMinField("m", "ORA_REGISTRAZIONE", "minOraMess");
  4657.                        
  4658.                         if(secondiAnzianitaPerIniziareSpedireNuovoMessaggio!=null && secondiAnzianitaPerIniziareSpedireNuovoMessaggio>0) {
  4659.                             // Per non prendere immediatamente i messaggi in carico ed evitare problemi di serializzazione con le tracce, se ancora non è stata scritta
  4660.                             if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  4661.                                 sqlQueryObject.addWhereCondition(false,
  4662.                                         "m.ORA_REGISTRAZIONE<=?", // controllo che non sia nell'intervallo tra now e i precedenti x secondi
  4663.                                         "(m.ORA_REGISTRAZIONE>? AND m.ORA_REGISTRAZIONE<?)" // se è una data futura rispetto al now la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera
  4664.                                         );
  4665.                             }
  4666.                             else {
  4667.                                 sqlQueryObject.addWhereCondition("m.ORA_REGISTRAZIONE<=?");
  4668.                             }
  4669.                         }
  4670.                        
  4671.                         // join
  4672.                         sqlQueryObject.addWhereCondition("m.ID_MESSAGGIO=sa.ID_MESSAGGIO");
  4673.                        
  4674.                         sqlQueryObject.addWhereCondition("m.TIPO=?");
  4675.                         sqlQueryObject.addWhereCondition("m.PROPRIETARIO=?");
  4676.                         sqlQueryObject.addWhereCondition("sa.TIPO_CONSEGNA=?");
  4677.                         sqlQueryObject.addWhereCondition("sa.ATTESA_ESITO=?");
  4678.                         sqlQueryObject.addWhereCondition("sa.CODA=?");
  4679.                         if(serviziApplicativiPrioritari!=null && serviziApplicativiPrioritari.length>0) {
  4680.                             if(serviziApplicativiPrioritari.length==1) {
  4681.                                 sqlQueryObject.addWhereCondition("sa.SERVIZIO_APPLICATIVO=?");
  4682.                             }
  4683.                             else {
  4684.                                 sqlQueryObject.addWhereINCondition("sa.SERVIZIO_APPLICATIVO", true, serviziApplicativiPrioritari);
  4685.                             }
  4686.                         }
  4687.                         else if(priorita!=null) {
  4688.                             sqlQueryObject.addWhereCondition("sa.PRIORITA=?");
  4689.                         }
  4690.                        
  4691.                         // per non intralciare con la "prima" registrazione (forse e' un controllo inutile)
  4692.                         sqlQueryObject.addWhereCondition("sa.ERRORE_PROCESSAMENTO_COMPACT is not null");
  4693.                         if(!verificaPresenzaMessaggiDaRispedire_consideraAncheNuoviMessaggi) {
  4694.                             // per non intralciare con la "prima" consegna
  4695.                             sqlQueryObject.addWhereCondition("sa.ERRORE_PROCESSAMENTO_COMPACT <> ?");
  4696.                         }
  4697.                        
  4698.                         if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  4699.                             sqlQueryObject.addWhereCondition(false,
  4700.                                     // data di rispedizione precedente ad adesso
  4701.                                     "sa.RISPEDIZIONE<=?",
  4702.                                     // data futura che combacia con l'ora di registrazione, la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera
  4703.                                     "(sa.RISPEDIZIONE=sa.ORA_REGISTRAZIONE  AND sa.RISPEDIZIONE<=?)"
  4704.                             );
  4705.                         }
  4706.                         else {
  4707.                             sqlQueryObject.addWhereCondition("sa.RISPEDIZIONE<=?");
  4708.                         }
  4709.                        
  4710.                         sqlQueryObject.addWhereCondition(false, "sa.LOCK_CONSEGNA is null", "sa.LOCK_CONSEGNA < ?");
  4711.                        
  4712.                         sqlQueryObject.setANDLogicOperator(true);
  4713.                        
  4714.                         queryString = sqlQueryObject.createSQLQuery();
  4715.                     }
  4716.                    
  4717.                     pstmt = connectionDB.prepareStatement(queryString);
  4718.                     int index = 1;
  4719.                     List<Object> params = new ArrayList<>();
  4720.                    
  4721.                     if(secondiAnzianitaPerIniziareSpedireNuovoMessaggio!=null && secondiAnzianitaPerIniziareSpedireNuovoMessaggio>0) {
  4722.                         if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  4723.                            
  4724.                             // se è una data futura rispetto al now la prendo in considerazione essendo il problema dell'ora
  4725.                             long nowMillis = dataAttualeVerificaNow.getTime(); // uso il now calcolato per la variabile isMinutiMancantiPassaggioOraLegaleVersoOraSolare
  4726.                            
  4727.                             // controllo che non sia nell'intervallo tra now e i precedenti x secondi (ORA_REGISTRAZIONE<=?)
  4728.                             Timestamp anzianita = new Timestamp(nowMillis-(1000*secondiAnzianitaPerIniziareSpedireNuovoMessaggio.intValue()));
  4729.                             pstmt.setTimestamp(index++, anzianita);
  4730.                             params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(anzianita));
  4731.                            
  4732.                             // se è una data futura rispetto al now la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera (ORA_REGISTRAZIONE>? AND ORA_REGISTRAZIONE<?)
  4733.                             Timestamp futuro = new Timestamp(nowMillis);
  4734.                             pstmt.setTimestamp(index++, futuro);
  4735.                             params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(futuro));
  4736.                            
  4737.                             Timestamp futuroPlusHour = new Timestamp(nowMillis+
  4738.                                     (1000*60*60)+ // un'ora
  4739.                                     (1000*60+5)); // aggiungo altri 5 minuti
  4740.                             pstmt.setTimestamp(index++, futuroPlusHour);
  4741.                             params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(futuroPlusHour));

  4742.                         }
  4743.                         else {
  4744.                             long nowMillis = DateManager.getTimeMillis();
  4745.                             // controllo che non sia nell'intervallo tra now e i precedenti x secondi
  4746.                             Timestamp anzianita = new Timestamp(nowMillis-(1000*secondiAnzianitaPerIniziareSpedireNuovoMessaggio.intValue()));
  4747.                             pstmt.setTimestamp(index++, anzianita);
  4748.                             params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(anzianita));
  4749.                         }
  4750.                     }
  4751.                    
  4752.                     pstmt.setString(index++,tipo); params.add(tipo);
  4753.                     pstmt.setString(index++,ConsegnaContenutiApplicativi.ID_MODULO); params.add(ConsegnaContenutiApplicativi.ID_MODULO);
  4754.                     pstmt.setString(index++,GestoreMessaggi.CONSEGNA_TRAMITE_CONNETTORE); params.add(GestoreMessaggi.CONSEGNA_TRAMITE_CONNETTORE);
  4755.                     pstmt.setInt(index++,CostantiDB.FALSE); params.add(CostantiDB.FALSE);
  4756.                     pstmt.setString(index++,coda); params.add(coda);
  4757.                    
  4758.                     if(serviziApplicativiPrioritari!=null && serviziApplicativiPrioritari.length>0) {
  4759.                         if(serviziApplicativiPrioritari.length==1) {
  4760.                             pstmt.setString(index++,serviziApplicativiPrioritari[0]);
  4761.                             params.add(serviziApplicativiPrioritari[0]);
  4762.                         }
  4763.                     }
  4764.                     else if(priorita!=null) {
  4765.                         pstmt.setString(index++,priorita);
  4766.                         params.add(priorita);
  4767.                     }
  4768.                    
  4769.                     if(!verificaPresenzaMessaggiDaRispedire_consideraAncheNuoviMessaggi) {
  4770.                         // per non intralciare con la "prima" consegna
  4771.                         pstmt.setString(index++, TimerConsegnaContenutiApplicativiThread.ID_MODULO);
  4772.                         params.add(TimerConsegnaContenutiApplicativiThread.ID_MODULO);
  4773.                     }
  4774.                    
  4775.                     // riconsegna
  4776.                     pstmt.setTimestamp(index++,new Timestamp(riconsegna.getTime()));
  4777.                     params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(riconsegna));
  4778.                     if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  4779.                         Timestamp futuroPlusHour = new Timestamp(riconsegna.getTime()+
  4780.                                 (1000*60*60)+ // un'ora
  4781.                                 (1000*60+5)); // aggiungo altri 5 minuti
  4782.                         pstmt.setTimestamp(index++,new Timestamp(futuroPlusHour.getTime()));
  4783.                         params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(futuroPlusHour));
  4784.                     }
  4785.                    
  4786.                     pstmt.setTimestamp(index++, new Timestamp(dataRilascioLock.getTime()));
  4787.                     params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(dataRilascioLock));

  4788.                     long startDateSQLCommand = DateManager.getTimeMillis();
  4789.                     String comandoSql = null;
  4790.                     if(debug) {
  4791.                         comandoSql = DBUtils.formatSQLString(queryString, params.toArray());
  4792.                         loggerSql.debug("[QUERY] (Messaggi.daRispedire.computeMinDate) ["+comandoSql+"] ...");
  4793.                     }
  4794.                     rs = pstmt.executeQuery();
  4795.                     long endDateSQLCommand = DateManager.getTimeMillis();
  4796.                     long diffSQLCommand = endDateSQLCommand - startDateSQLCommand;
  4797.                     if(debug) {
  4798.                         loggerSql.debug("[QUERY] (Messaggi.daRispedire.computeMinDate) ["+comandoSql+"] effettuata in "+Utilities.convertSystemTimeIntoStringMillisecondi(diffSQLCommand, true));
  4799.                     }
  4800.                    
  4801.                     if(rs.next()){
  4802.                         dataMinima = rs.getTimestamp("minOraMess");
  4803.                     }
  4804.                     rs.close(); rs = null;
  4805.                     pstmt.close(); pstmt=null;
  4806.                    
  4807.                     if(dataMinima==null) {
  4808.                         // non esistono messaggi; e' inutile fare la query successiva
  4809.                         loggerSql.debug("[QUERY] (Messaggi.daRispedire.computeMinDate) ["+comandoSql+"] dataMinima non trovata");
  4810.                         return idMsg;
  4811.                     }
  4812.                    
  4813.                     if(debug) {
  4814.                         loggerSql.debug("[QUERY] (Messaggi.daRispedire.computeMinDate) ["+comandoSql+"] dataMinimaTrovata: "+DateUtils.getSimpleDateFormatMs().format(dataMinima));
  4815.                     }
  4816.                    
  4817.                 } catch(Throwable e) {
  4818.                     String errorMsg = "[GestoreMessaggi.readMessaggiDaRiconsegnareIntoBox] errore durante il calcolo della data minima, queryString["+queryString+"] : "+e.getMessage();
  4819.                     try{
  4820.                         if(rs != null)
  4821.                             rs.close();
  4822.                     } catch(Exception er) {
  4823.                         // close
  4824.                     }
  4825.                     try{
  4826.                         if(pstmt != null)
  4827.                             pstmt.close();
  4828.                     } catch(Exception er) {
  4829.                         // close
  4830.                     }
  4831.                     loggerSql.error(errorMsg,e);
  4832.                     // Vado avanza senza data minima throw new GestoreMessaggiException(errorMsg,e);
  4833.                 }
  4834.             }
  4835.            
  4836.             PreparedStatement pstmtMsgDaSpedire = null;
  4837.             ResultSet rs = null;
  4838.             String queryString = null;
  4839.             try{  
  4840.                
  4841.                 // Query per Ricerca messaggi eliminati (proprietario:EliminatoreMesaggi)
  4842.                 if(Configurazione.getSqlQueryObjectType()==null){
  4843.                     StringBuilder query = new StringBuilder();
  4844.                     query.append("SELECT "+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO as idmess, ");
  4845.                     query.append(" "+GestoreMessaggi.MESSAGGI+".id_transazione as idtransazione, ");
  4846.                     query.append(" "+GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE as oramess, ");
  4847.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SERVIZIO_APPLICATIVO as sa, ");
  4848.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SBUSTAMENTO_SOAP as sbSoap, ");
  4849.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SBUSTAMENTO_INFO_PROTOCOL as sbProtocol ");
  4850.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".NOME_PORTA as nomePorta ");
  4851.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".LOCK_CONSEGNA as saLock "); // non usare lock e' una parola riservata di oracle
  4852.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".CLUSTER_ID as saCluster "); // non usare cluster e' una parola riservata di oracle
  4853.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ATTESA_ESITO as attesa ");
  4854.                    
  4855.                     query.append(" FROM ");
  4856.                     query.append(GestoreMessaggi.MESSAGGI);
  4857.                     query.append(",");
  4858.                     query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  4859.                    
  4860.                     query.append(" WHERE ");
  4861.                    
  4862.                     // Ottimizzazione per partizionamento
  4863.                     if(verificaPresenzaMessaggiDaRispedire) {
  4864.                         if(dataMinima!=null) {
  4865.                             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ORA_REGISTRAZIONE>=? ").append(" AND ");
  4866.                             query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE>=? ").append(" AND ");
  4867.                         }
  4868.                     }
  4869.                     else {
  4870.                         query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ORA_REGISTRAZIONE>=? ").append(" AND ");
  4871.                         query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE>=? ").append(" AND ");
  4872.                     }
  4873.                    
  4874.                     if(secondiAnzianitaPerIniziareSpedireNuovoMessaggio!=null && secondiAnzianitaPerIniziareSpedireNuovoMessaggio>0) {
  4875.                         // Per non prendere immediatamente i messaggi in carico ed evitare problemi di serializzazione con le tracce, se ancora non è stata scritta
  4876.                         if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  4877.                             query.append("(");
  4878.                            
  4879.                             // controllo che non sia nell'intervallo tra now e i precedenti x secondi
  4880.                             query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE<=? ");
  4881.                            
  4882.                             query.append(" OR ");
  4883.                            
  4884.                             // se è una data futura rispetto al now la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera
  4885.                             query.append("(");
  4886.                             query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE>? ");
  4887.                             query.append(" AND ");
  4888.                             query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE<? ");
  4889.                             query.append(")");
  4890.                            
  4891.                             query.append(")");
  4892.                            
  4893.                             query.append(" AND ");
  4894.                         }
  4895.                         else {
  4896.                             query.append(GestoreMessaggi.MESSAGGI).append(".ORA_REGISTRAZIONE<=? ").append(" AND ");
  4897.                         }
  4898.                     }
  4899.                    
  4900.                     // join
  4901.                     query.append(" ");
  4902.                     query.append(GestoreMessaggi.MESSAGGI);
  4903.                     query.append(".ID_MESSAGGIO=");
  4904.                     query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  4905.                     query.append(".ID_MESSAGGIO AND ");
  4906.                    
  4907.                     query.append(" ").append(GestoreMessaggi.MESSAGGI).append(".TIPO=? AND ").
  4908.                           append(GestoreMessaggi.MESSAGGI).append(".PROPRIETARIO=? ");
  4909.                     query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".TIPO_CONSEGNA=? ");
  4910.                     query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ATTESA_ESITO=? ");
  4911.                     query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".CODA=? ");
  4912.                     if(serviziApplicativiPrioritari!=null && serviziApplicativiPrioritari.length>0) {
  4913.                         query.append(" AND (");
  4914.                         if(serviziApplicativiPrioritari.length==1) {
  4915.                             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".SERVIZIO_APPLICATIVO=?");
  4916.                         }
  4917.                         else {
  4918.                             query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".SERVIZIO_APPLICATIVO IN (");
  4919.                             for (int i = 0; i < serviziApplicativiPrioritari.length; i++) {
  4920.                                 if(i>0) {
  4921.                                     query.append(",");
  4922.                                 }
  4923.                                 query.append(serviziApplicativiPrioritari[i]);
  4924.                             }
  4925.                             query.append(") ");
  4926.                         }
  4927.                         query.append(")");
  4928.                     }
  4929.                     else if(priorita!=null) {
  4930.                         query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".PRIORITA=? ");
  4931.                     }
  4932.                     if(verificaPresenzaMessaggiDaRispedire) {
  4933.                         // per non intralciare con la "prima" registrazione (forse e' un controllo inutile)
  4934.                         query.append(" AND ").
  4935.                             append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ERRORE_PROCESSAMENTO_COMPACT is not null ");
  4936.                         if(!verificaPresenzaMessaggiDaRispedire_consideraAncheNuoviMessaggi) {
  4937.                             // per non intralciare con la "prima" consegna
  4938.                             query.append(" AND ").
  4939.                                 append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ERRORE_PROCESSAMENTO_COMPACT <> ? ");
  4940.                         }
  4941.                     }
  4942.                     else {
  4943.                         query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ERRORE_PROCESSAMENTO_COMPACT = ? "); // prima consegna
  4944.                     }
  4945.                    
  4946.                     if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  4947.                         query.append(" AND (");
  4948.                        
  4949.                         // data di rispedizione precedente ad adesso
  4950.                         query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".RISPEDIZIONE<=? ");
  4951.                        
  4952.                         // data futura che combacia con l'ora di registrazione, la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera
  4953.                         query.append(" OR (");
  4954.                         query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".RISPEDIZIONE=").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".ORA_REGISTRAZIONE");
  4955.                         query.append(" AND ");
  4956.                         query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".RISPEDIZIONE<=? ");
  4957.                         query.append(") ");
  4958.                        
  4959.                         query.append(") ");
  4960.                     }
  4961.                     else {
  4962.                         query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".RISPEDIZIONE<=? ");
  4963.                     }
  4964.                    
  4965.                     query.append(" AND (").
  4966.                         append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".LOCK_CONSEGNA is null ").
  4967.                         append(" OR ").
  4968.                         append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".LOCK_CONSEGNA < ? ").
  4969.                         append(")");
  4970.                    
  4971.                     queryString = query.toString();
  4972.                 }else{

  4973.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  4974.                     sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI,"m");
  4975.                     sqlQueryObject.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,"sa");
  4976.                    
  4977.                     sqlQueryObject.addSelectAliasField("m", "ID_MESSAGGIO", "idmess");
  4978.                     sqlQueryObject.addSelectAliasField("m", "id_transazione", "idtransazione");
  4979.                     sqlQueryObject.addSelectAliasField("m", "ORA_REGISTRAZIONE", "oramess");
  4980.                     sqlQueryObject.addSelectAliasField("sa", "SERVIZIO_APPLICATIVO", "sa");
  4981.                     sqlQueryObject.addSelectAliasField("sa", "SBUSTAMENTO_SOAP", "sbSoap");
  4982.                     sqlQueryObject.addSelectAliasField("sa", "SBUSTAMENTO_INFO_PROTOCOL", "sbProtocol");
  4983.                     sqlQueryObject.addSelectAliasField("sa", "NOME_PORTA", "nomePorta");
  4984.                     sqlQueryObject.addSelectAliasField("sa", "LOCK_CONSEGNA", "saLock"); // non usare lock e' una parola riservata di oracle
  4985.                     sqlQueryObject.addSelectAliasField("sa", "CLUSTER_ID", "saCluster"); // non usare cluster e' una parola riservata di oracle
  4986.                     sqlQueryObject.addSelectAliasField("sa", "ATTESA_ESITO", "attesa");
  4987.                     sqlQueryObject.addSelectAliasField("sa", "ID_MESSAGGIO", "saidmess");
  4988.                     sqlQueryObject.addSelectAliasField("sa", "TIPO_CONSEGNA", "satipocons");
  4989.                     sqlQueryObject.addSelectAliasField("sa", "ERRORE_PROCESSAMENTO_COMPACT", "saerrproccom");
  4990.                     sqlQueryObject.addSelectAliasField("sa", "RISPEDIZIONE", "sarisp");
  4991.                     sqlQueryObject.addSelectAliasField("sa", "CODA", "sacoda");
  4992.                     sqlQueryObject.addSelectAliasField("sa", "PRIORITA", "saprio");
  4993.                     sqlQueryObject.addSelectAliasField("m","ORA_REGISTRAZIONE", "oramsg");
  4994.                     sqlQueryObject.addSelectAliasField("m","PROPRIETARIO", "propmsg");
  4995.                     sqlQueryObject.addSelectAliasField("m","TIPO" , "tipomsg");
  4996.                    
  4997.                     // Ottimizzazione per partizionamento
  4998.                     if(verificaPresenzaMessaggiDaRispedire) {
  4999.                         if(dataMinima!=null) {
  5000.                             sqlQueryObject.addWhereCondition("m.ORA_REGISTRAZIONE>=?");
  5001.                             sqlQueryObject.addWhereCondition("sa.ORA_REGISTRAZIONE>=?");
  5002.                         }
  5003.                     }
  5004.                     else {
  5005.                         sqlQueryObject.addWhereCondition("m.ORA_REGISTRAZIONE>=?");
  5006.                         sqlQueryObject.addWhereCondition("sa.ORA_REGISTRAZIONE>=?");
  5007.                     }
  5008.                    
  5009.                     if(secondiAnzianitaPerIniziareSpedireNuovoMessaggio!=null && secondiAnzianitaPerIniziareSpedireNuovoMessaggio>0) {
  5010.                         // Per non prendere immediatamente i messaggi in carico ed evitare problemi di serializzazione con le tracce, se ancora non è stata scritta
  5011.                         if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  5012.                             sqlQueryObject.addWhereCondition(false,
  5013.                                     "m.ORA_REGISTRAZIONE<=?", // controllo che non sia nell'intervallo tra now e i precedenti x secondi
  5014.                                     "(m.ORA_REGISTRAZIONE>? AND m.ORA_REGISTRAZIONE<?)" // se è una data futura rispetto al now la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera
  5015.                                     );
  5016.                         }
  5017.                         else {
  5018.                             sqlQueryObject.addWhereCondition("m.ORA_REGISTRAZIONE<=?");
  5019.                         }
  5020.                     }
  5021.                    
  5022.                     // join
  5023.                     sqlQueryObject.addWhereCondition("m.ID_MESSAGGIO=sa.ID_MESSAGGIO");
  5024.                    
  5025.                     sqlQueryObject.addWhereCondition("m.TIPO=?");
  5026.                     sqlQueryObject.addWhereCondition("m.PROPRIETARIO=?");
  5027.                     sqlQueryObject.addWhereCondition("sa.TIPO_CONSEGNA=?");
  5028.                     sqlQueryObject.addWhereCondition("sa.ATTESA_ESITO=?");
  5029.                     sqlQueryObject.addWhereCondition("sa.CODA=?");
  5030.                     if(serviziApplicativiPrioritari!=null && serviziApplicativiPrioritari.length>0) {
  5031.                         if(serviziApplicativiPrioritari.length==1) {
  5032.                             sqlQueryObject.addWhereCondition("sa.SERVIZIO_APPLICATIVO=?");
  5033.                         }
  5034.                         else {
  5035.                             sqlQueryObject.addWhereINCondition("sa.SERVIZIO_APPLICATIVO", true, serviziApplicativiPrioritari);
  5036.                         }
  5037.                     }
  5038.                     else if(priorita!=null) {
  5039.                         sqlQueryObject.addWhereCondition("sa.PRIORITA=?");
  5040.                     }
  5041.                     if(verificaPresenzaMessaggiDaRispedire) {
  5042.                         // per non intralciare con la "prima" registrazione (forse e' un controllo inutile)
  5043.                         sqlQueryObject.addWhereCondition("sa.ERRORE_PROCESSAMENTO_COMPACT is not null");
  5044.                         if(!verificaPresenzaMessaggiDaRispedire_consideraAncheNuoviMessaggi) {
  5045.                             // per non intralciare con la "prima" consegna
  5046.                             sqlQueryObject.addWhereCondition("sa.ERRORE_PROCESSAMENTO_COMPACT <> ?");
  5047.                         }
  5048.                     }
  5049.                     else {
  5050.                         sqlQueryObject.addWhereCondition("sa.ERRORE_PROCESSAMENTO_COMPACT = ?"); // "prima" consegna
  5051.                     }
  5052.                    
  5053.                     if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  5054.                         sqlQueryObject.addWhereCondition(false,
  5055.                                 // data di rispedizione precedente ad adesso
  5056.                                 "sa.RISPEDIZIONE<=?",
  5057.                                 // data futura che combacia con l'ora di registrazione, la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera
  5058.                                 "(sa.RISPEDIZIONE=sa.ORA_REGISTRAZIONE  AND sa.RISPEDIZIONE<=?)"
  5059.                         );
  5060.                     }
  5061.                     else {
  5062.                         sqlQueryObject.addWhereCondition("sa.RISPEDIZIONE<=?");
  5063.                     }
  5064.                    
  5065.                     sqlQueryObject.addWhereCondition(false, "sa.LOCK_CONSEGNA is null", "sa.LOCK_CONSEGNA < ?");
  5066.                    
  5067.                     sqlQueryObject.setANDLogicOperator(true);
  5068.                     sqlQueryObject.addOrderBy("oramsg");
  5069.                     sqlQueryObject.setSortType(true);
  5070.                    
  5071.                     sqlQueryObject.setLimit(limit);
  5072.                     queryString = sqlQueryObject.createSQLQuery();
  5073.                 }
  5074.                 //System.out.println("QUERY MESSAGGI ELIMINATI IS: ["+queryString+"]  1["+idModuloCleaner+"]  2["+tipo+"]");

  5075.                 //log.debug("Query: "+query);
  5076.                 pstmtMsgDaSpedire = connectionDB.prepareStatement(queryString);
  5077.                 int index = 1;
  5078.                 List<Object> params = new ArrayList<>();
  5079.                
  5080.                 // Ottimizzazione per partizionamento
  5081.                 if(verificaPresenzaMessaggiDaRispedire) {
  5082.                     if(dataMinima!=null) {
  5083.                         pstmtMsgDaSpedire.setTimestamp(index++, dataMinima);
  5084.                         pstmtMsgDaSpedire.setTimestamp(index++, dataMinima);
  5085.                         params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(dataMinima));
  5086.                         params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(dataMinima));
  5087.                     }
  5088.                 }
  5089.                 else {
  5090.                     Timestamp now = new Timestamp(DateManager.getTimeMillis()-(1000*60*60*24)); // i messaggi presi in carico possono rimanere al massimo indietro di un giorno, senno rientrano in quelli da rispedire
  5091.                     pstmtMsgDaSpedire.setTimestamp(index++, now);
  5092.                     pstmtMsgDaSpedire.setTimestamp(index++, now);
  5093.                     params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(now));
  5094.                     params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(now));
  5095.                 }
  5096.                
  5097.                 if(secondiAnzianitaPerIniziareSpedireNuovoMessaggio!=null && secondiAnzianitaPerIniziareSpedireNuovoMessaggio>0) {
  5098.                     if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  5099.                        
  5100.                         // se è una data futura rispetto al now la prendo in considerazione essendo il problema dell'ora
  5101.                         long nowMillis = dataAttualeVerificaNow.getTime(); // uso il now calcolato per la variabile isMinutiMancantiPassaggioOraLegaleVersoOraSolare
  5102.                        
  5103.                         // controllo che non sia nell'intervallo tra now e i precedenti x secondi (ORA_REGISTRAZIONE<=?)
  5104.                         Timestamp anzianita = new Timestamp(nowMillis-(1000*secondiAnzianitaPerIniziareSpedireNuovoMessaggio.intValue()));
  5105.                         pstmtMsgDaSpedire.setTimestamp(index++, anzianita);
  5106.                         params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(anzianita));
  5107.                        
  5108.                         // se è una data futura rispetto al now la prendo in considerazione essendo il problema dell'ora, comunque sempre nella solita partizione giornaliera (ORA_REGISTRAZIONE>? AND ORA_REGISTRAZIONE<?)
  5109.                         Timestamp futuro = new Timestamp(nowMillis);
  5110.                         pstmtMsgDaSpedire.setTimestamp(index++, futuro);
  5111.                         params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(futuro));
  5112.                        
  5113.                         Timestamp futuroPlusHour = new Timestamp(nowMillis+
  5114.                                 (1000*60*60)+ // un'ora
  5115.                                 (1000*60+5)); // aggiungo altri 5 minuti
  5116.                         pstmtMsgDaSpedire.setTimestamp(index++, futuroPlusHour);
  5117.                         params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(futuroPlusHour));

  5118.                     }
  5119.                     else {
  5120.                         Timestamp anzianita = new Timestamp(DateManager.getTimeMillis()-(1000*secondiAnzianitaPerIniziareSpedireNuovoMessaggio.intValue()));
  5121.                         pstmtMsgDaSpedire.setTimestamp(index++, anzianita);
  5122.                         params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(anzianita));
  5123.                     }
  5124.                 }
  5125.                
  5126.                 pstmtMsgDaSpedire.setString(index++,tipo); params.add(tipo);
  5127.                 pstmtMsgDaSpedire.setString(index++,ConsegnaContenutiApplicativi.ID_MODULO); params.add(ConsegnaContenutiApplicativi.ID_MODULO);
  5128.                 pstmtMsgDaSpedire.setString(index++,GestoreMessaggi.CONSEGNA_TRAMITE_CONNETTORE); params.add(GestoreMessaggi.CONSEGNA_TRAMITE_CONNETTORE);
  5129.                 pstmtMsgDaSpedire.setInt(index++,CostantiDB.FALSE); params.add(CostantiDB.FALSE);
  5130.                 pstmtMsgDaSpedire.setString(index++,coda); params.add(coda);
  5131.                
  5132.                 if(serviziApplicativiPrioritari!=null && serviziApplicativiPrioritari.length>0) {
  5133.                     if(serviziApplicativiPrioritari.length==1) {
  5134.                         pstmtMsgDaSpedire.setString(index++,serviziApplicativiPrioritari[0]);
  5135.                         params.add(serviziApplicativiPrioritari[0]);
  5136.                     }
  5137.                 }
  5138.                 else if(priorita!=null) {
  5139.                     pstmtMsgDaSpedire.setString(index++,priorita);
  5140.                     params.add(priorita);
  5141.                 }
  5142.                
  5143.                 if(verificaPresenzaMessaggiDaRispedire) {
  5144.                     if(!verificaPresenzaMessaggiDaRispedire_consideraAncheNuoviMessaggi) {
  5145.                         // per non intralciare con la "prima" consegna
  5146.                         pstmtMsgDaSpedire.setString(index++, TimerConsegnaContenutiApplicativiThread.ID_MODULO);
  5147.                         params.add(TimerConsegnaContenutiApplicativiThread.ID_MODULO);
  5148.                     }
  5149.                 }
  5150.                 else {
  5151.                     pstmtMsgDaSpedire.setString(index++, TimerConsegnaContenutiApplicativiThread.ID_MODULO);
  5152.                     params.add(TimerConsegnaContenutiApplicativiThread.ID_MODULO);
  5153.                 }
  5154.                
  5155.                 pstmtMsgDaSpedire.setTimestamp(index++,new Timestamp(riconsegna.getTime()));
  5156.                 params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(riconsegna));
  5157.                 if(isMinutiMancantiPassaggioOraLegaleVersoOraSolare) {
  5158.                     Timestamp futuroPlusHour = new Timestamp(riconsegna.getTime()+
  5159.                             (1000*60*60)+ // un'ora
  5160.                             (1000*60+5)); // aggiungo altri 5 minuti
  5161.                     pstmtMsgDaSpedire.setTimestamp(index++,new Timestamp(futuroPlusHour.getTime()));
  5162.                     params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(futuroPlusHour));
  5163.                 }
  5164.                
  5165.                 pstmtMsgDaSpedire.setTimestamp(index++, new Timestamp(dataRilascioLock.getTime()));
  5166.                 params.add(org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(dataRilascioLock));

  5167.                 long startDateSQLCommand = DateManager.getTimeMillis();
  5168.                 String comandoSql = null;
  5169.                 if(debug) {
  5170.                     comandoSql = DBUtils.formatSQLString(queryString, params.toArray());
  5171.                     loggerSql.debug("[QUERY] (Messaggi.daRispedire) ["+comandoSql+"] ...");
  5172.                 }
  5173.                 rs = pstmtMsgDaSpedire.executeQuery();
  5174.                 long endDateSQLCommand = DateManager.getTimeMillis();
  5175.                 long diffSQLCommand = endDateSQLCommand - startDateSQLCommand;
  5176.                 if(debug) {
  5177.                     loggerSql.debug("[QUERY] (Messaggi.daRispedire) ["+comandoSql+"] effettuata in "+Utilities.convertSystemTimeIntoStringMillisecondi(diffSQLCommand, true));
  5178.                 }
  5179.                
  5180.                 int countLimit = 0;
  5181.                 while(rs.next()){
  5182.                     MessaggioServizioApplicativo msg = new MessaggioServizioApplicativo();
  5183.                     msg.setIdTransazione(rs.getString("idtransazione"));
  5184.                     msg.setIdMessaggio(rs.getString("idmess"));
  5185.                     msg.setServizioApplicativo(rs.getString("sa"));
  5186.                     int sbSoap = rs.getInt("sbSoap");
  5187.                     msg.setSbustamentoSoap(sbSoap==CostantiDB.TRUE);
  5188.                     int sbInfoProt = rs.getInt("sbProtocol");
  5189.                     msg.setSbustamentoInformazioniProtocollo(sbInfoProt==CostantiDB.TRUE);
  5190.                     msg.setNomePorta(rs.getString("nomePorta"));
  5191.                    
  5192.                     Timestamp oraRegistrazione = rs.getTimestamp("oramess");
  5193.                     msg.setOraRegistrazione(oraRegistrazione);
  5194.                    
  5195.                     Timestamp dataPresaInConsegna = rs.getTimestamp("saLock");
  5196.                     msg.setDataPresaInConsegna(dataPresaInConsegna);
  5197.                     msg.setClusterIdPresaInConsegna(rs.getString("saCluster"));
  5198.                     int attesaTransazioneCapostipite = rs.getInt("attesa");
  5199.                     msg.setAttesaEsitoTransazioneCapostipite(attesaTransazioneCapostipite==CostantiDB.TRUE);
  5200.                    
  5201.                     idMsg.add(msg);
  5202.                     // LIMIT Applicativo
  5203.                     if(Configurazione.getSqlQueryObjectType()==null){
  5204.                         countLimit++;
  5205.                         if(countLimit==limit)
  5206.                             break;
  5207.                     }
  5208.                    
  5209.                     //System.out.println("CHECK verificaPresenzaMessaggiDaRispedire="+verificaPresenzaMessaggiDaRispedire+" TROVATO ["+msg.getIdMessaggio()+"]");
  5210.                 }
  5211.                 rs.close(); rs = null;
  5212.                 pstmtMsgDaSpedire.close(); pstmtMsgDaSpedire=null;

  5213.                 if(debug) {
  5214.                     loggerSql.debug("[QUERY] (Messaggi.daRispedire) ["+comandoSql+"] trovati risultati: "+idMsg.size());
  5215.                 }
  5216.                                
  5217.                 return idMsg;

  5218.             } catch(Exception e) {
  5219.                 String errorMsg = "[GestoreMessaggi.readMessaggiDaRiconsegnareIntoBox] errore, queryString["+queryString+"]: "+e.getMessage();
  5220.                 try{
  5221.                     if(rs != null)
  5222.                         rs.close();
  5223.                 } catch(Exception er) {
  5224.                     // close
  5225.                 }
  5226.                 try{
  5227.                     if(pstmtMsgDaSpedire != null)
  5228.                         pstmtMsgDaSpedire.close();
  5229.                 } catch(Exception er) {
  5230.                     // close
  5231.                 }
  5232.                 loggerSql.error(errorMsg,e);
  5233.                 throw new GestoreMessaggiException(errorMsg,e);
  5234.             }
  5235.             // else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  5236.             // NOP stateful only
  5237.         }else{
  5238.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  5239.         }

  5240.     }
  5241.     public static boolean isMinutiMancantiPassaggioOraLegaleVersoOraSolare(boolean debug, RunnableLogger loggerSql, Date data, int minutes) {
  5242.         try {
  5243.             String format = DaylightSavingUtils.getOffsetFormat();
  5244.             String dataString = DateUtils.getSimpleDateFormat(format).format(data);
  5245.             TimeTransitionType type = DaylightSavingUtils.getTimeChangePendingTodayWithoutOffset(dataString, format);
  5246.             if(type!=null && TimeTransitionType.FROM_DAYLIGHT_SAVING_TO_STANDARD_TIME.equals(type)) {
  5247.                 long m = DaylightSavingUtils.minutesUntilNextTransitionWithoutOffset(dataString, format);
  5248.                 boolean result = m>-1 && m<=minutes; // va bene anche 0 perchè rappresenta l'ultimo minuto
  5249.                 if(debug) {
  5250.                     loggerSql.debug("(Messaggi.daRispedire) verifico data ["+dataString+"] minutes: "+m+"   Risultato: "+result);
  5251.                 }
  5252.                 return result;
  5253.             }
  5254.             return false;
  5255.         }catch(Throwable t) {
  5256.             loggerSql.error("Calcolo 'isMinutiMancantiPassaggioOraLegaleVersoOraSolare' fallito: "+t.getMessage(),t);
  5257.         }
  5258.         return false;
  5259.     }
  5260.    
  5261.     public MessaggioServizioApplicativo readInfoDestinatario(String applicativo, boolean debug, Logger log)throws GestoreMessaggiException{
  5262.         List<MessaggioServizioApplicativo> l = _readInfoDestinatari(debug, log, applicativo);
  5263.         if(l!=null && !l.isEmpty()) {
  5264.             if(l.size()==1) {
  5265.                 return l.get(0);
  5266.             }
  5267.             else {
  5268.                 throw new GestoreMessaggiException("More than one result ("+l.size()+")");
  5269.             }
  5270.         }
  5271.         return null;
  5272.     }
  5273.     public List<MessaggioServizioApplicativo> readInfoDestinatari(boolean debug, Logger log)throws GestoreMessaggiException{
  5274.         return _readInfoDestinatari(debug, log, null);
  5275.     }
  5276.     private List<MessaggioServizioApplicativo> _readInfoDestinatari(boolean debug, Logger log, String applicativo)throws GestoreMessaggiException{

  5277.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  5278.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  5279.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  5280.             Connection connectionDB = stateful.getConnectionDB();

  5281.             List<MessaggioServizioApplicativo> idMsg = new ArrayList<MessaggioServizioApplicativo>();

  5282.             PreparedStatement pstmtMsg = null;
  5283.             ResultSet rs = null;
  5284.             String queryString = null;
  5285.             String tipo = null;
  5286.             try{  
  5287.                 // tipo
  5288.                 tipo = Costanti.INBOX;

  5289.                 // Query per Ricerca messaggi eliminati (proprietario:EliminatoreMesaggi)
  5290.                 if(Configurazione.getSqlQueryObjectType()==null){
  5291.                     StringBuilder query = new StringBuilder();
  5292.                     query.append("SELECT "+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO as idmess, ");
  5293.                     query.append(" "+GestoreMessaggi.MESSAGGI+".id_transazione as idtransazione, ");
  5294.                     query.append(" "+GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE as oramess, ");
  5295.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SERVIZIO_APPLICATIVO as sa, ");
  5296.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SBUSTAMENTO_SOAP as sbSoap, ");
  5297.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SBUSTAMENTO_INFO_PROTOCOL as sbProtocol ");
  5298.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".NOME_PORTA as nomePorta ");
  5299.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".LOCK_CONSEGNA as lock ");
  5300.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".CLUSTER_ID as cluster ");
  5301.                     query.append(" "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ATTESA_ESITO as attesa ");
  5302.                    
  5303.                     query.append(" FROM ");
  5304.                     query.append(GestoreMessaggi.MESSAGGI);
  5305.                     query.append(",");
  5306.                     query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  5307.                    
  5308.                     query.append(" WHERE ");
  5309.                    
  5310.                     // join
  5311.                     query.append(" ");
  5312.                     query.append(GestoreMessaggi.MESSAGGI);
  5313.                     query.append(".ID_MESSAGGIO=");
  5314.                     query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  5315.                     query.append(".ID_MESSAGGIO AND ");
  5316.                    
  5317.                     query.append(" ").append(GestoreMessaggi.MESSAGGI).append(".ID_MESSAGGIO=? AND ");
  5318.                     query.append(" ").append(GestoreMessaggi.MESSAGGI).append(".TIPO=?");
  5319.                     if(applicativo!=null) {
  5320.                         query.append(" AND ").append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI).append(".SERVIZIO_APPLICATIVO=?");
  5321.                     }

  5322.                     queryString = query.toString();
  5323.                 }else{

  5324.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  5325.                     sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI,"m");
  5326.                     sqlQueryObject.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,"sa");
  5327.                    
  5328.                     sqlQueryObject.addSelectAliasField("m", "ID_MESSAGGIO", "idmess");
  5329.                     sqlQueryObject.addSelectAliasField("m", "ORA_REGISTRAZIONE", "oramess");
  5330.                     sqlQueryObject.addSelectAliasField("m", "id_transazione", "idtransazione");
  5331.                     sqlQueryObject.addSelectAliasField("sa", "SERVIZIO_APPLICATIVO", "sa");
  5332.                     sqlQueryObject.addSelectAliasField("sa", "SBUSTAMENTO_SOAP", "sbSoap");
  5333.                     sqlQueryObject.addSelectAliasField("sa", "SBUSTAMENTO_INFO_PROTOCOL", "sbProtocol");
  5334.                     sqlQueryObject.addSelectAliasField("sa", "NOME_PORTA", "nomePorta");
  5335.                     sqlQueryObject.addSelectAliasField("sa", "LOCK_CONSEGNA", "lock");
  5336.                     sqlQueryObject.addSelectAliasField("sa", "CLUSTER_ID", "cluster");
  5337.                     sqlQueryObject.addSelectAliasField("sa", "ATTESA_ESITO", "attesa");
  5338.                     sqlQueryObject.addSelectField("m","ORA_REGISTRAZIONE");
  5339.                     sqlQueryObject.addSelectField("m","PROPRIETARIO");
  5340.                     sqlQueryObject.addSelectField("m","TIPO");
  5341.                    
  5342.                     // join
  5343.                     sqlQueryObject.addWhereCondition("m.ID_MESSAGGIO=sa.ID_MESSAGGIO");
  5344.                    
  5345.                     sqlQueryObject.addWhereCondition("m.ID_MESSAGGIO=?");
  5346.                     sqlQueryObject.addWhereCondition("m.TIPO=?");
  5347.                     if(applicativo!=null) {
  5348.                         sqlQueryObject.addWhereCondition("sa.SERVIZIO_APPLICATIVO=?");
  5349.                     }
  5350.                    
  5351.                     sqlQueryObject.setANDLogicOperator(true);
  5352.                    
  5353.                     queryString = sqlQueryObject.createSQLQuery();
  5354.                 }
  5355.                 //System.out.println("QUERY MESSAGGI ELIMINATI IS: ["+queryString+"]  1["+idModuloCleaner+"]  2["+tipo+"]");

  5356.                 //log.debug("Query: "+query);
  5357.                 pstmtMsg = connectionDB.prepareStatement(queryString);
  5358.                 int index = 1;
  5359.                 pstmtMsg.setString(index++,this.idBusta);
  5360.                 pstmtMsg.setString(index++,tipo);
  5361.                 if(applicativo!=null) {
  5362.                     pstmtMsg.setString(index++,applicativo);
  5363.                 }
  5364.                
  5365.                 String terzoArgomento = "";
  5366.                 if(applicativo!=null) {
  5367.                     terzoArgomento = " 3["+applicativo+"]";
  5368.                 }
  5369.                
  5370.                 long startDateSQLCommand = DateManager.getTimeMillis();
  5371.                 if(debug)
  5372.                     log.debug("[QUERY] (Messaggi.readDestinatari) ["+queryString+"] 1["+this.idBusta+"] 2["+tipo+"]"+terzoArgomento+" ...");
  5373.                 rs = pstmtMsg.executeQuery();
  5374.                 long endDateSQLCommand = DateManager.getTimeMillis();
  5375.                 long diffSQLCommand = endDateSQLCommand - startDateSQLCommand;
  5376.                 if(debug)
  5377.                     log.debug("[QUERY] (Messaggi.readDestinatari) ["+queryString+"] 1["+this.idBusta+"] 2["+tipo+"]"+terzoArgomento+" effettuata in "+Utilities.convertSystemTimeIntoStringMillisecondi(diffSQLCommand, true));

  5378.                 while(rs.next()){
  5379.                     MessaggioServizioApplicativo msg = new MessaggioServizioApplicativo();
  5380.                     msg.setIdTransazione(rs.getString("idtransazione"));
  5381.                     msg.setIdMessaggio(rs.getString("idmess"));
  5382.                     msg.setServizioApplicativo(rs.getString("sa"));
  5383.                     int sbSoap = rs.getInt("sbSoap");
  5384.                     msg.setSbustamentoSoap(sbSoap==CostantiDB.TRUE);
  5385.                     int sbInfoProt = rs.getInt("sbProtocol");
  5386.                     msg.setSbustamentoInformazioniProtocollo(sbInfoProt==CostantiDB.TRUE);
  5387.                     msg.setNomePorta(rs.getString("nomePorta"));
  5388.                    
  5389.                     Timestamp oraRegistrazione = rs.getTimestamp("oramess");
  5390.                     msg.setOraRegistrazione(oraRegistrazione);
  5391.                    
  5392.                     Timestamp dataPresaInConsegna = rs.getTimestamp("lock");
  5393.                     msg.setDataPresaInConsegna(dataPresaInConsegna);
  5394.                     msg.setClusterIdPresaInConsegna(rs.getString("cluster"));
  5395.                     int attesaTransazioneCapostipite = rs.getInt("attesa");
  5396.                     msg.setAttesaEsitoTransazioneCapostipite(attesaTransazioneCapostipite==CostantiDB.TRUE);
  5397.                    
  5398.                     idMsg.add(msg);

  5399.                 }
  5400.                 rs.close();
  5401.                 pstmtMsg.close();

  5402.                 return idMsg;

  5403.             } catch(Exception e) {
  5404.                 String errorMsg = "[GestoreMessaggi.readDestinatari] errore, queryString["+queryString+"]: "+e.getMessage();
  5405.                 try{
  5406.                     if(rs != null)
  5407.                         rs.close();
  5408.                 } catch(Exception er) {
  5409.                     // close
  5410.                 }
  5411.                 try{
  5412.                     if(pstmtMsg != null)
  5413.                         pstmtMsg.close();
  5414.                 } catch(Exception er) {
  5415.                     // close
  5416.                 }
  5417.                 log.error(errorMsg,e);
  5418.                 throw new GestoreMessaggiException(errorMsg,e);
  5419.             }
  5420.             // else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  5421.             // NOP stateful only
  5422.         }else{
  5423.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  5424.         }

  5425.     }

  5426.     public void updateMessaggioPresaInCosegna(String servizioApplicativo, String clusterId,
  5427.             boolean debug, RunnableLogger loggerSql) throws GestoreMessaggiException {
  5428.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  5429.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  5430.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  5431.             Connection connectionDB = stateMSG.getConnectionDB();

  5432.             PreparedStatement pstmt = null;
  5433.             try{

  5434.                 Timestamp now = DateManager.getTimestamp();
  5435.                
  5436.                
  5437.                 // Costruzione Query Update
  5438.                 String query = "UPDATE "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" SET LOCK_CONSEGNA=?, CLUSTER_ID=? WHERE ID_MESSAGGIO=? AND SERVIZIO_APPLICATIVO=?";
  5439.                 //log.debug("Query: "+query);
  5440.                 pstmt= connectionDB.prepareStatement(query);
  5441.                 int index = 1;
  5442.                 pstmt.setTimestamp(index++,now);
  5443.                 pstmt.setString(index++,clusterId);
  5444.                 pstmt.setString(index++,this.idBusta);
  5445.                 pstmt.setString(index++,servizioApplicativo);

  5446.                 int row = pstmt.executeUpdate();
  5447.                 if(debug) {
  5448.                     loggerSql.debug("(rows update: "+row+") UPDATE MSG_SERVIZI_APPLICATIVI SET LOCK_CONSEGNA='"+DateUtils.getSimpleDateFormatMs().format(now)+"', CLUSTER_ID='"+cluster_id+"' WHERE ID_MESSAGGIO='"+this.idBusta+"' AND SERVIZIO_APPLICATIVO='"+servizioApplicativo+"'");
  5449.                 }
  5450.                
  5451.                 pstmt.close();

  5452.             } catch(Exception e) {
  5453.                 try{
  5454.                     if( pstmt != null  )
  5455.                         pstmt.close();
  5456.                 } catch(Exception er) {
  5457.                     // close
  5458.                 }
  5459.                 String msgError = "ERROR updateMessaggioPresaInCosegna: "+e.getMessage();
  5460.                 loggerSql.error(msgError,e);
  5461.                 throw new GestoreMessaggiException(msgError,e);
  5462.             }

  5463.         }else{
  5464.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  5465.         }
  5466.     }
  5467.    
  5468.     public void releaseMessaggioPresaInCosegna(String servizioApplicativo, String clusterId,
  5469.             boolean debug, RunnableLogger loggerSql) throws GestoreMessaggiException {
  5470.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  5471.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  5472.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  5473.             Connection connectionDB = stateMSG.getConnectionDB();

  5474.             PreparedStatement pstmt = null;
  5475.             try{

  5476.                 // Costruzione Query Update
  5477.                 String query = "UPDATE "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" SET LOCK_CONSEGNA=?, CLUSTER_ID=? WHERE ID_MESSAGGIO=? AND SERVIZIO_APPLICATIVO=?";
  5478.                 //log.debug("Query: "+query);
  5479.                 pstmt= connectionDB.prepareStatement(query);
  5480.                 int index = 1;
  5481.                 pstmt.setTimestamp(index++,null);
  5482.                 pstmt.setString(index++,null);
  5483.                 pstmt.setString(index++,this.idBusta);
  5484.                 pstmt.setString(index++,servizioApplicativo);

  5485.                 int row = pstmt.executeUpdate();
  5486.                 if(debug) {
  5487.                     loggerSql.debug("(rows update: "+row+") UPDATE MSG_SERVIZI_APPLICATIVI SET LOCK_CONSEGNA=null, CLUSTER_ID=null WHERE ID_MESSAGGIO='"+this.idBusta+"' AND SERVIZIO_APPLICATIVO='"+servizioApplicativo+"'");
  5488.                 }
  5489.                
  5490.                 pstmt.close();

  5491.             } catch(Exception e) {
  5492.                 try{
  5493.                     if( pstmt != null  )
  5494.                         pstmt.close();
  5495.                 } catch(Exception er) {
  5496.                     // close
  5497.                 }
  5498.                 String msgError = "ERROR releaseMessaggioPresaInCosegna: "+e.getMessage();
  5499.                 loggerSql.error(msgError,e);
  5500.                 throw new GestoreMessaggiException(msgError,e);
  5501.             }

  5502.         }else{
  5503.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  5504.         }
  5505.     }
  5506.    
  5507.     public void releaseMessaggiPresaInCosegna(String queue, String clusterId,
  5508.             boolean debug, RunnableLogger loggerSql) throws GestoreMessaggiException {
  5509.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  5510.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  5511.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  5512.             Connection connectionDB = stateMSG.getConnectionDB();

  5513.             PreparedStatement pstmt = null;
  5514.             try{

  5515.                 // Costruzione Query Update
  5516.                 String condition = (clusterId==null || "".equals(clusterId)) ? "CLUSTER_ID is null" : " CLUSTER_ID=?";
  5517.                 String query = "UPDATE "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" SET LOCK_CONSEGNA=?, CLUSTER_ID=? WHERE "+condition+" AND CODA=? AND LOCK_CONSEGNA is not null AND LOCK_CONSEGNA<?";
  5518.                 //log.debug("Query: "+query);
  5519.                 pstmt= connectionDB.prepareStatement(query);
  5520.                 int index = 1;
  5521.                 pstmt.setTimestamp(index++,null);
  5522.                 pstmt.setString(index++,null);
  5523.                 if((clusterId!=null && !"".equals(clusterId))) {
  5524.                     pstmt.setString(index++,clusterId);
  5525.                 }
  5526.                 pstmt.setString(index++,queue);
  5527.                 pstmt.setTimestamp(index++, TimerConsegnaContenutiApplicativiThread.LOCK_CONSEGNA_FUTURA);

  5528.                 int row = pstmt.executeUpdate();
  5529.                 if(debug) {
  5530.                     loggerSql.debug("(rows update: "+row+") (clusterID: "+clusterId+") UPDATE MSG_SERVIZI_APPLICATIVI SET LOCK_CONSEGNA=null, CLUSTER_ID=null WHERE "+
  5531.                             condition+" AND CODA="+queue+" AND LOCK_CONSEGNA is not null AND LOCK_CONSEGNA<"+
  5532.                             DateUtils.getSimpleDateFormatMs().format(TimerConsegnaContenutiApplicativiThread.LOCK_CONSEGNA_FUTURA));
  5533.                 }
  5534.                
  5535.                 pstmt.close();

  5536.             } catch(Exception e) {
  5537.                 try{
  5538.                     if( pstmt != null  )
  5539.                         pstmt.close();
  5540.                 } catch(Exception er) {
  5541.                     // close
  5542.                 }
  5543.                 String msgError = "ERROR releaseMessaggioPresaInCosegna: "+e.getMessage();
  5544.                 loggerSql.error(msgError,e);
  5545.                 throw new GestoreMessaggiException(msgError,e);
  5546.             }

  5547.         }else{
  5548.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  5549.         }
  5550.     }

  5551.     public void releaseAttesaEsiti(boolean debug, Logger log) throws GestoreMessaggiException {
  5552.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  5553.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  5554.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  5555.             Connection connectionDB = stateMSG.getConnectionDB();

  5556.             PreparedStatement pstmt = null;
  5557.             try{

  5558.                 // Costruzione Query Update
  5559.                 String query = "UPDATE "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" SET ATTESA_ESITO=? WHERE ID_MESSAGGIO=?";
  5560.                 //log.debug("Query: "+query);
  5561.                 pstmt= connectionDB.prepareStatement(query);
  5562.                 int index = 1;
  5563.                 pstmt.setInt(index++,CostantiDB.FALSE);
  5564.                 pstmt.setString(index++,this.idBusta);

  5565.                 int row = pstmt.executeUpdate();
  5566.                 if(debug) {
  5567.                     log.debug("(rows update: "+row+") UPDATE MSG_SERVIZI_APPLICATIVI SET ATTESA_ESITO="+CostantiDB.FALSE+" WHERE ID_MESSAGGIO='"+this.idBusta+"'");
  5568.                 }
  5569.                
  5570.                 pstmt.close();

  5571.             } catch(Exception e) {
  5572.                 try{
  5573.                     if( pstmt != null  )
  5574.                         pstmt.close();
  5575.                 } catch(Exception er) {
  5576.                     // close
  5577.                 }
  5578.                 String msgError = "ERROR releaseMessaggioPresaInCosegna: "+e.getMessage();
  5579.                 log.error(msgError,e);
  5580.                 throw new GestoreMessaggiException(msgError,e);
  5581.             }

  5582.         }else{
  5583.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  5584.         }
  5585.     }
  5586.    



  5587.    
  5588.    
  5589.     /* ------------- UTILITY PER LETTURA MESSAGGI DA ELIMINARE -------------- */
  5590.    
  5591.     public static Date getOraRegistrazioneMassima(Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws GestoreMessaggiException{
  5592.         return _getOraRegistrazione(false, connectionDB , tipoDatabase, logQuery, logger);
  5593.     }
  5594.     public static Date getOraRegistrazioneMinima(Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws GestoreMessaggiException{
  5595.         return _getOraRegistrazione(true, connectionDB , tipoDatabase, logQuery, logger);
  5596.     }
  5597.     private static Date _getOraRegistrazione(boolean min, Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws GestoreMessaggiException{
  5598.    
  5599.         PreparedStatement pstmt = null;
  5600.         ResultSet rs = null;
  5601.         String queryString = null;
  5602.         try{    
  5603.        
  5604.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  5605.             if(min) {
  5606.                 sqlQueryObject.addSelectMinField(MESSAGGI_COLUMN_ORA_REGISTRAZIONE, "check_data");
  5607.             }
  5608.             else {
  5609.                 sqlQueryObject.addSelectMaxField(MESSAGGI_COLUMN_ORA_REGISTRAZIONE, "check_data");
  5610.             }
  5611.             sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  5612.             sqlQueryObject.setANDLogicOperator(true);
  5613.             queryString = sqlQueryObject.createSQLQuery();
  5614.             if(logQuery) {
  5615.                 logger.debug("Esecuzione query ["+queryString+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  5616.             }
  5617.            
  5618.             pstmt = connectionDB.prepareStatement(queryString);
  5619.             rs = pstmt.executeQuery();
  5620.            
  5621.             if(logQuery) {
  5622.                 logger.debug("Esecuzione query ["+queryString+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata");
  5623.             }
  5624.            
  5625.             if(rs.next()) {
  5626.                 return rs.getTimestamp("check_data");
  5627.             }
  5628.             return null;
  5629.        
  5630.         } catch(Exception e) {
  5631.             String errorMsg = "[GestoreMessaggi.getOraRegistrazione] errore, queryString["+queryString+"]: "+e.getMessage();
  5632.             throw new GestoreMessaggiException(errorMsg,e);
  5633.         }
  5634.         finally {
  5635.             try{
  5636.                 if(rs != null)
  5637.                     rs.close();
  5638.             } catch(Exception er) {
  5639.                 // close
  5640.             }
  5641.             try{
  5642.                 if(pstmt != null)
  5643.                     pstmt.close();
  5644.             } catch(Exception er) {
  5645.                 // close
  5646.             }
  5647.         }
  5648.     }
  5649.    
  5650.     public static int countMessaggiInutiliIntoInBox(Connection connectionDB , String tipoDatabase,
  5651.             boolean logQuery, Logger logger,
  5652.             Date leftDate, Date rightDate) throws GestoreMessaggiException{
  5653.         return _countMessaggiIntoBox(true, connectionDB, tipoDatabase, logQuery, logger, leftDate, rightDate, null);
  5654.     }
  5655.     public static int countMessaggiInutiliIntoOutBox(Connection connectionDB , String tipoDatabase,
  5656.             boolean logQuery, Logger logger,
  5657.             Date leftDate, Date rightDate) throws GestoreMessaggiException{
  5658.         return _countMessaggiIntoBox(false, connectionDB, tipoDatabase, logQuery, logger, leftDate, rightDate, null);
  5659.     }
  5660.     public static int countMessaggiScadutiIntoInBox(Connection connectionDB , String tipoDatabase,
  5661.             boolean logQuery, Logger logger,
  5662.             Date leftDate, Date rightDate,
  5663.             long scadenzaMsg) throws GestoreMessaggiException{
  5664.         return _countMessaggiIntoBox(true, connectionDB, tipoDatabase, logQuery, logger, leftDate, rightDate, scadenzaMsg);
  5665.     }
  5666.     public static int countMessaggiScadutiIntoOutBox(Connection connectionDB , String tipoDatabase,
  5667.             boolean logQuery, Logger logger,
  5668.             Date leftDate, Date rightDate,
  5669.             long scadenzaMsg) throws GestoreMessaggiException{
  5670.         return _countMessaggiIntoBox(false, connectionDB, tipoDatabase, logQuery, logger, leftDate, rightDate, scadenzaMsg);
  5671.     }
  5672.     private static int _countMessaggiIntoBox(boolean searchIntoInbox, Connection connectionDB , String tipoDatabase,
  5673.             boolean logQuery, Logger logger,
  5674.             Date leftDate, Date rightDate,
  5675.             Long scadenzaMsg) throws GestoreMessaggiException{
  5676.        
  5677.         String tipo = null;
  5678.         if(searchIntoInbox)
  5679.             tipo = Costanti.INBOX;
  5680.         else
  5681.             tipo = Costanti.OUTBOX;
  5682.        
  5683.         String idModuloCleaner = TimerGestoreMessaggi.ID_MODULO;
  5684.        
  5685.         PreparedStatement pstmt = null;
  5686.         ResultSet rs = null;
  5687.         String queryString = null;
  5688.         try{    
  5689.        
  5690.             // Query per Ricerca messaggi scaduti
  5691.             // Algoritmo:
  5692.             //    if( (now-timeout) > oraRegistrazione )
  5693.             //       msgScaduto
  5694.             java.sql.Timestamp scandenzaT = null;
  5695.             if(scadenzaMsg!=null) {
  5696.                 long scadenza = DateManager.getTimeMillis() - (scadenzaMsg * 60 * 1000);
  5697.                 scandenzaT = new java.sql.Timestamp(scadenza);
  5698.             }
  5699.            
  5700.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  5701.             sqlQueryObject.addSelectCountField("totale_msg");
  5702.             sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  5703.             if(leftDate!=null) {
  5704.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_ORA_REGISTRAZIONE+">=?");
  5705.             }
  5706.             if(rightDate!=null) {
  5707.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_ORA_REGISTRAZIONE+"<=?");
  5708.             }
  5709.             if(scadenzaMsg!=null) {
  5710.                 sqlQueryObject.addWhereCondition("? > "+MESSAGGI_COLUMN_ORA_REGISTRAZIONE);
  5711.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  5712.             }
  5713.             else {
  5714.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  5715.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_PROPRIETARIO+"=?");
  5716.             }
  5717.             sqlQueryObject.setANDLogicOperator(true);
  5718.             queryString = sqlQueryObject.createSQLQuery();

  5719.             pstmt = connectionDB.prepareStatement(queryString);
  5720.             int index = 1;
  5721.             List<Object> objects = new ArrayList<>();
  5722.             if(leftDate!=null) {
  5723.                 java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  5724.                 pstmt.setTimestamp(index++, leftDateT);
  5725.                 if(logQuery) {
  5726.                     objects.add(DateUtils.getSimpleDateFormatMs().format(leftDateT));
  5727.                 }
  5728.             }
  5729.             if(rightDate!=null) {
  5730.                 java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  5731.                 pstmt.setTimestamp(index++, rightDateT);
  5732.                 if(logQuery) {
  5733.                     objects.add(DateUtils.getSimpleDateFormatMs().format(rightDateT));
  5734.                 }
  5735.             }
  5736.             if(scadenzaMsg!=null) {
  5737.                 pstmt.setTimestamp(index++,scandenzaT);
  5738.                 if(logQuery) {
  5739.                     objects.add(DateUtils.getSimpleDateFormatMs().format(scandenzaT));
  5740.                 }
  5741.                
  5742.                 pstmt.setString(index++,tipo);
  5743.                 if(logQuery) {
  5744.                     objects.add(tipo);
  5745.                 }
  5746.             }
  5747.             else {
  5748.                 pstmt.setString(index++,tipo);
  5749.                 if(logQuery) {
  5750.                     objects.add(tipo);
  5751.                 }
  5752.                 pstmt.setString(index++,idModuloCleaner);
  5753.                 if(logQuery) {
  5754.                     objects.add(idModuloCleaner);
  5755.                 }
  5756.             }
  5757.            
  5758.             String query = null;
  5759.             if(logQuery) {
  5760.                 query = DBUtils.formatSQLString(queryString, objects.toArray());
  5761.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  5762.             }
  5763.             rs = pstmt.executeQuery();
  5764.            
  5765.             int res = 0;
  5766.             if(rs.next()) {
  5767.                 res = rs.getInt("totale_msg");
  5768.             }
  5769.            
  5770.             if(logQuery) {
  5771.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; trovati "+res+" risultati");
  5772.             }
  5773.            
  5774.             return res;
  5775.        
  5776.         } catch(Exception e) {
  5777.             String errorMsg = "[GestoreMessaggi.countMessaggiIntoBox] errore, queryString["+queryString+"]: "+e.getMessage();
  5778.             throw new GestoreMessaggiException(errorMsg,e);
  5779.         }
  5780.         finally {
  5781.             try{
  5782.                 if(rs != null)
  5783.                     rs.close();
  5784.             } catch(Exception er) {
  5785.                 // close
  5786.             }
  5787.             try{
  5788.                 if(pstmt != null)
  5789.                     pstmt.close();
  5790.             } catch(Exception er) {
  5791.                 // close
  5792.             }
  5793.         }
  5794.     }
  5795.    
  5796.     public static SortedMap<Integer> deleteMessaggiInutiliIntoInBox(Connection connectionDB , String tipoDatabase,
  5797.             boolean logQuery, Logger logger,
  5798.             Date leftDate, Date rightDate, IGestoreRepository repository) throws GestoreMessaggiException{
  5799.         return _deleteMessaggiIntoBox(true, connectionDB, tipoDatabase, logQuery, logger, leftDate, rightDate, null, repository);
  5800.     }
  5801.     public static SortedMap<Integer> deleteMessaggiInutiliIntoOutBox(Connection connectionDB , String tipoDatabase,
  5802.             boolean logQuery, Logger logger,
  5803.             Date leftDate, Date rightDate, IGestoreRepository repository) throws GestoreMessaggiException{
  5804.         return _deleteMessaggiIntoBox(false, connectionDB, tipoDatabase, logQuery, logger, leftDate, rightDate, null, repository);
  5805.     }
  5806.     public static SortedMap<Integer> deleteMessaggiScadutiIntoInBox(Connection connectionDB , String tipoDatabase,
  5807.             boolean logQuery, Logger logger,
  5808.             Date leftDate, Date rightDate,
  5809.             long scadenzaMsg, IGestoreRepository repository) throws GestoreMessaggiException{
  5810.         return _deleteMessaggiIntoBox(true, connectionDB, tipoDatabase, logQuery, logger, leftDate, rightDate, scadenzaMsg, repository);
  5811.     }
  5812.     public static SortedMap<Integer> deleteMessaggiScadutiIntoOutBox(Connection connectionDB , String tipoDatabase,
  5813.             boolean logQuery, Logger logger,
  5814.             Date leftDate, Date rightDate,
  5815.             long scadenzaMsg, IGestoreRepository repository) throws GestoreMessaggiException{
  5816.         return _deleteMessaggiIntoBox(false, connectionDB, tipoDatabase, logQuery, logger, leftDate, rightDate, scadenzaMsg, repository);
  5817.     }
  5818.     private static SortedMap<Integer> _deleteMessaggiIntoBox(boolean searchIntoInbox, Connection connectionDB , String tipoDatabase,
  5819.             boolean logQuery, Logger logger,
  5820.             Date leftDate, Date rightDate,
  5821.             Long scadenzaMsg, IGestoreRepository repository) throws GestoreMessaggiException{
  5822.        
  5823.         SortedMap<Integer> mapTabelleRigheEliminate = new SortedMap<Integer>();
  5824.        
  5825.         String tipo = null;
  5826.         if(searchIntoInbox)
  5827.             tipo = Costanti.INBOX;
  5828.         else
  5829.             tipo = Costanti.OUTBOX;
  5830.        
  5831.         String idModuloCleaner = TimerGestoreMessaggi.ID_MODULO;
  5832.        
  5833.         PreparedStatement pstmt = null;
  5834.         String deleteString = null;
  5835.         try{    
  5836.        
  5837.             // Query per Ricerca messaggi scaduti
  5838.             // Algoritmo:
  5839.             //    if( (now-timeout) > oraRegistrazione )
  5840.             //       msgScaduto
  5841.             java.sql.Timestamp scandenzaT = null;
  5842.             if(scadenzaMsg!=null) {
  5843.                 long scadenza = DateManager.getTimeMillis() - (scadenzaMsg * 60 * 1000);
  5844.                 scandenzaT = new java.sql.Timestamp(scadenza);
  5845.             }
  5846.            
  5847.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  5848.             sqlQueryObject.addSelectField(MESSAGGI_COLUMN_ID_MESSAGGIO);
  5849.             sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  5850.             if(leftDate!=null) {
  5851.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_ORA_REGISTRAZIONE+">=?");
  5852.             }
  5853.             if(rightDate!=null) {
  5854.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_ORA_REGISTRAZIONE+"<=?");
  5855.             }
  5856.             if(scadenzaMsg!=null) {
  5857.                 sqlQueryObject.addWhereCondition("? > "+MESSAGGI_COLUMN_ORA_REGISTRAZIONE);
  5858.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  5859.             }
  5860.             else {
  5861.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  5862.                 sqlQueryObject.addWhereCondition(MESSAGGI_COLUMN_PROPRIETARIO+"=?");
  5863.             }
  5864.             sqlQueryObject.setANDLogicOperator(true);
  5865.            
  5866.            
  5867.             // **** Prima prova ad eliminare eventuali SIL rimasti appesi al messaggio, se il messaggio e' di tipo INBOX ****
  5868.             if(searchIntoInbox){
  5869.                
  5870.                 ISQLQueryObject sqlQueryObjectMsgServiziApplicativi = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  5871.                 sqlQueryObjectMsgServiziApplicativi.addDeleteTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  5872.                 sqlQueryObjectMsgServiziApplicativi.addWhereINSelectSQLCondition(false, MSG_SERVIZI_APPLICATIVI_COLUMN_ID_MESSAGGIO, sqlQueryObject);
  5873.                 sqlQueryObjectMsgServiziApplicativi.setANDLogicOperator(true);
  5874.                
  5875.                 deleteString = sqlQueryObjectMsgServiziApplicativi.createSQLDelete();
  5876.                 pstmt = connectionDB.prepareStatement(deleteString);
  5877.                 int index = 1;
  5878.                 List<Object> objects = new ArrayList<>();
  5879.                 if(leftDate!=null) {
  5880.                     java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  5881.                     pstmt.setTimestamp(index++, leftDateT);
  5882.                     if(logQuery) {
  5883.                         objects.add(DateUtils.getSimpleDateFormatMs().format(leftDate));
  5884.                     }
  5885.                 }
  5886.                 if(rightDate!=null) {
  5887.                     java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  5888.                     pstmt.setTimestamp(index++, rightDateT);
  5889.                     if(logQuery) {
  5890.                         objects.add(DateUtils.getSimpleDateFormatMs().format(rightDate));
  5891.                     }
  5892.                 }
  5893.                 if(scadenzaMsg!=null) {
  5894.                     pstmt.setTimestamp(index++,scandenzaT);
  5895.                     if(logQuery) {
  5896.                         objects.add(DateUtils.getSimpleDateFormatMs().format(scandenzaT));
  5897.                     }
  5898.                    
  5899.                     pstmt.setString(index++,tipo);
  5900.                     if(logQuery) {
  5901.                         objects.add(tipo);
  5902.                     }
  5903.                 }
  5904.                 else {
  5905.                     pstmt.setString(index++,tipo);
  5906.                     if(logQuery) {
  5907.                         objects.add(tipo);
  5908.                     }
  5909.                     pstmt.setString(index++,idModuloCleaner);
  5910.                     if(logQuery) {
  5911.                         objects.add(idModuloCleaner);
  5912.                     }
  5913.                 }
  5914.                
  5915.                 String query = null;
  5916.                 if(logQuery) {
  5917.                     query = DBUtils.formatSQLString(deleteString, objects.toArray());
  5918.                     logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  5919.                 }
  5920.                 int result = pstmt.executeUpdate();
  5921.                 pstmt.close();
  5922.                 pstmt = null;
  5923.                
  5924.                 if(logQuery) {
  5925.                     logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; "+result+" righe eliminate");
  5926.                 }
  5927.                 mapTabelleRigheEliminate.add(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI, result);
  5928.             }
  5929.            
  5930.            
  5931.             // **** Prova poi ad eliminare il messaggio su DB ****
  5932.            
  5933.             ISQLQueryObject sqlQueryObjectDefinizioneMessaggi = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  5934.             sqlQueryObjectDefinizioneMessaggi.addDeleteTable(GestoreMessaggi.DEFINIZIONE_MESSAGGI);
  5935.             sqlQueryObjectDefinizioneMessaggi.addWhereCondition(DEFINIZIONE_MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  5936.             sqlQueryObjectDefinizioneMessaggi.addWhereINSelectSQLCondition(false, DEFINIZIONE_MESSAGGI_COLUMN_ID_MESSAGGIO, sqlQueryObject);
  5937.             sqlQueryObjectDefinizioneMessaggi.setANDLogicOperator(true);
  5938.            
  5939.             deleteString = sqlQueryObjectDefinizioneMessaggi.createSQLDelete();
  5940.             pstmt = connectionDB.prepareStatement(deleteString);
  5941.             int index = 1;
  5942.             List<Object> objects = new ArrayList<>();
  5943.             pstmt.setString(index++,tipo);
  5944.             if(logQuery) {
  5945.                 objects.add(tipo);
  5946.             }
  5947.             if(leftDate!=null) {
  5948.                 java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  5949.                 pstmt.setTimestamp(index++, leftDateT);
  5950.                 if(logQuery) {
  5951.                     objects.add(DateUtils.getSimpleDateFormatMs().format(leftDate));
  5952.                 }
  5953.             }
  5954.             if(rightDate!=null) {
  5955.                 java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  5956.                 pstmt.setTimestamp(index++, rightDateT);
  5957.                 if(logQuery) {
  5958.                     objects.add(DateUtils.getSimpleDateFormatMs().format(rightDate));
  5959.                 }
  5960.             }
  5961.             if(scadenzaMsg!=null) {
  5962.                 pstmt.setTimestamp(index++,scandenzaT);
  5963.                 if(logQuery) {
  5964.                     objects.add(DateUtils.getSimpleDateFormatMs().format(scandenzaT));
  5965.                 }
  5966.                
  5967.                 pstmt.setString(index++,tipo);
  5968.                 if(logQuery) {
  5969.                     objects.add(tipo);
  5970.                 }
  5971.             }
  5972.             else {
  5973.                 pstmt.setString(index++,tipo);
  5974.                 if(logQuery) {
  5975.                     objects.add(tipo);
  5976.                 }
  5977.                 pstmt.setString(index++,idModuloCleaner);
  5978.                 if(logQuery) {
  5979.                     objects.add(idModuloCleaner);
  5980.                 }
  5981.             }
  5982.            
  5983.             String query = null;
  5984.             if(logQuery) {
  5985.                 query = DBUtils.formatSQLString(deleteString, objects.toArray());
  5986.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  5987.             }
  5988.             int result = pstmt.executeUpdate();
  5989.             pstmt.close();
  5990.             pstmt = null;
  5991.            
  5992.             if(logQuery) {
  5993.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; "+result+" righe eliminate");
  5994.             }
  5995.             mapTabelleRigheEliminate.add(GestoreMessaggi.DEFINIZIONE_MESSAGGI, result);
  5996.            
  5997.            
  5998.            
  5999.             if(repository!=null) {
  6000.                
  6001.                 // **** Eliminazione buste (non possiedono l'accesso da history o l'accesso da profilo) ****
  6002.                
  6003.                
  6004.                 // lista
  6005.                 ISQLQueryObject sqlQueryObjectRepositoryBusteJoin = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  6006.                 sqlQueryObjectRepositoryBusteJoin.addSelectField(org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY_COLUMN_ID_MESSAGGIO);
  6007.                 sqlQueryObjectRepositoryBusteJoin.addFromTable(org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY);
  6008.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition(org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY_COLUMN_TIPO_MESSAGGIO+"=?");
  6009.                 sqlQueryObjectRepositoryBusteJoin.addWhereINSelectSQLCondition(false, org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY_COLUMN_ID_MESSAGGIO, sqlQueryObject);
  6010.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition(false, repository.createSQLCondition_enableOnlyPdd(), repository.createSQLCondition_disabledAll());
  6011.                 sqlQueryObjectRepositoryBusteJoin.setANDLogicOperator(true);
  6012.                
  6013.                 _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  6014.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_RISCONTRI,
  6015.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_RISCONTRI_COLUMN_TIPO_MESSAGGIO,
  6016.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_RISCONTRI_COLUMN_ID_MESSAGGIO,
  6017.                         tipo, leftDate, rightDate, scandenzaT, idModuloCleaner, sqlQueryObjectRepositoryBusteJoin,
  6018.                         mapTabelleRigheEliminate);
  6019.                
  6020.                 _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  6021.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_TRASMISSIONI,
  6022.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_TRASMISSIONI_COLUMN_TIPO_MESSAGGIO,
  6023.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_TRASMISSIONI_COLUMN_ID_MESSAGGIO,
  6024.                         tipo, leftDate, rightDate, scandenzaT, idModuloCleaner, sqlQueryObjectRepositoryBusteJoin,
  6025.                         mapTabelleRigheEliminate);
  6026.                
  6027.                 _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  6028.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_ECCEZIONI,
  6029.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_ECCEZIONI_COLUMN_TIPO_MESSAGGIO,
  6030.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_ECCEZIONI_COLUMN_ID_MESSAGGIO,
  6031.                         tipo, leftDate, rightDate, scandenzaT, idModuloCleaner, sqlQueryObjectRepositoryBusteJoin,
  6032.                         mapTabelleRigheEliminate);
  6033.                
  6034.                 _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  6035.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_EXT_INFO,
  6036.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_EXT_INFO_COLUMN_TIPO_MESSAGGIO,
  6037.                         org.openspcoop2.protocol.engine.constants.Costanti.LISTA_EXT_INFO_COLUMN_ID_MESSAGGIO,
  6038.                         tipo, leftDate, rightDate, scandenzaT, idModuloCleaner, sqlQueryObjectRepositoryBusteJoin,
  6039.                         mapTabelleRigheEliminate);
  6040.                
  6041.                 _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  6042.                         org.openspcoop2.protocol.engine.constants.Costanti.PROFILO_ASINCRONO,
  6043.                         org.openspcoop2.protocol.engine.constants.Costanti.PROFILO_ASINCRONO_COLUMN_TIPO_MESSAGGIO,
  6044.                         org.openspcoop2.protocol.engine.constants.Costanti.PROFILO_ASINCRONO_COLUMN_ID_MESSAGGIO,
  6045.                         tipo, leftDate, rightDate, scandenzaT, idModuloCleaner, sqlQueryObjectRepositoryBusteJoin,
  6046.                         mapTabelleRigheEliminate);
  6047.                
  6048.                 if(!searchIntoInbox){
  6049.                     _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  6050.                             org.openspcoop2.protocol.engine.constants.Costanti.RISCONTRI_DA_RICEVERE,
  6051.                             null,
  6052.                             org.openspcoop2.protocol.engine.constants.Costanti.RISCONTRI_COLUMN_ID_MESSAGGIO,
  6053.                             tipo, leftDate, rightDate, scandenzaT, idModuloCleaner, sqlQueryObjectRepositoryBusteJoin,
  6054.                             mapTabelleRigheEliminate);
  6055.                 }
  6056.                
  6057.                
  6058.                 // Eliminazione busta reale
  6059.                
  6060.                 ISQLQueryObject sqlQueryObjectRepositoryBuste = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  6061.                 sqlQueryObjectRepositoryBuste.addDeleteTable(org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY);
  6062.                 sqlQueryObjectRepositoryBuste.addWhereCondition(org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY_COLUMN_TIPO_MESSAGGIO+"=?");
  6063.                 sqlQueryObjectRepositoryBuste.addWhereINSelectSQLCondition(false, org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY_COLUMN_ID_MESSAGGIO, sqlQueryObject);
  6064.                 sqlQueryObjectRepositoryBuste.addWhereCondition(false, repository.createSQLCondition_enableOnlyPdd(), repository.createSQLCondition_disabledAll());
  6065.                 sqlQueryObjectRepositoryBuste.setANDLogicOperator(true);
  6066.                
  6067.                 deleteString = sqlQueryObjectRepositoryBuste.createSQLDelete();
  6068.                 pstmt = connectionDB.prepareStatement(deleteString);
  6069.                 index = 1;
  6070.                 objects = new ArrayList<>();
  6071.                 pstmt.setString(index++,tipo);
  6072.                 if(logQuery) {
  6073.                     objects.add(tipo);
  6074.                 }
  6075.                 if(leftDate!=null) {
  6076.                     java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  6077.                     pstmt.setTimestamp(index++, leftDateT);
  6078.                     if(logQuery) {
  6079.                         objects.add(DateUtils.getSimpleDateFormatMs().format(leftDate));
  6080.                     }
  6081.                 }
  6082.                 if(rightDate!=null) {
  6083.                     java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  6084.                     pstmt.setTimestamp(index++, rightDateT);
  6085.                     if(logQuery) {
  6086.                         objects.add(DateUtils.getSimpleDateFormatMs().format(rightDate));
  6087.                     }
  6088.                 }
  6089.                 if(scadenzaMsg!=null) {
  6090.                     pstmt.setTimestamp(index++,scandenzaT);
  6091.                     if(logQuery) {
  6092.                         objects.add(DateUtils.getSimpleDateFormatMs().format(scandenzaT));
  6093.                     }
  6094.                    
  6095.                     pstmt.setString(index++,tipo);
  6096.                     if(logQuery) {
  6097.                         objects.add(tipo);
  6098.                     }
  6099.                 }
  6100.                 else {
  6101.                     pstmt.setString(index++,tipo);
  6102.                     if(logQuery) {
  6103.                         objects.add(tipo);
  6104.                     }
  6105.                     pstmt.setString(index++,idModuloCleaner);
  6106.                     if(logQuery) {
  6107.                         objects.add(idModuloCleaner);
  6108.                     }
  6109.                 }
  6110.                
  6111.                 query = null;
  6112.                 if(logQuery) {
  6113.                     query = DBUtils.formatSQLString(deleteString, objects.toArray());
  6114.                     logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  6115.                 }
  6116.                 result = pstmt.executeUpdate();
  6117.                 pstmt.close();
  6118.                 pstmt = null;
  6119.                
  6120.                 if(logQuery) {
  6121.                     logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; "+result+" righe eliminate");
  6122.                 }
  6123.                 mapTabelleRigheEliminate.add(org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY, result);
  6124.             }
  6125.            
  6126.            
  6127.            
  6128.            
  6129.             // **** Eliminazione finale ****
  6130.            
  6131.             ISQLQueryObject sqlQueryObjectMessaggi = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  6132.             sqlQueryObjectMessaggi.addDeleteTable(GestoreMessaggi.MESSAGGI);
  6133.             if(leftDate!=null) {
  6134.                 sqlQueryObjectMessaggi.addWhereCondition(MESSAGGI_COLUMN_ORA_REGISTRAZIONE+">=?");
  6135.             }
  6136.             if(rightDate!=null) {
  6137.                 sqlQueryObjectMessaggi.addWhereCondition(MESSAGGI_COLUMN_ORA_REGISTRAZIONE+"<=?");
  6138.             }
  6139.             if(scadenzaMsg!=null) {
  6140.                 sqlQueryObjectMessaggi.addWhereCondition("? > "+MESSAGGI_COLUMN_ORA_REGISTRAZIONE);
  6141.                 sqlQueryObjectMessaggi.addWhereCondition(MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  6142.             }
  6143.             else {
  6144.                 sqlQueryObjectMessaggi.addWhereCondition(MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  6145.                 sqlQueryObjectMessaggi.addWhereCondition(MESSAGGI_COLUMN_PROPRIETARIO+"=?");
  6146.             }
  6147.             sqlQueryObjectMessaggi.setANDLogicOperator(true);
  6148.            
  6149.             deleteString = sqlQueryObjectMessaggi.createSQLDelete();
  6150.             pstmt = connectionDB.prepareStatement(deleteString);
  6151.             index = 1;
  6152.             objects = new ArrayList<>();
  6153.             if(leftDate!=null) {
  6154.                 java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  6155.                 pstmt.setTimestamp(index++, leftDateT);
  6156.                 if(logQuery) {
  6157.                     objects.add(DateUtils.getSimpleDateFormatMs().format(leftDate));
  6158.                 }
  6159.             }
  6160.             if(rightDate!=null) {
  6161.                 java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  6162.                 pstmt.setTimestamp(index++, rightDateT);
  6163.                 if(logQuery) {
  6164.                     objects.add(DateUtils.getSimpleDateFormatMs().format(rightDate));
  6165.                 }
  6166.             }
  6167.             if(scadenzaMsg!=null) {
  6168.                 pstmt.setTimestamp(index++,scandenzaT);
  6169.                 if(logQuery) {
  6170.                     objects.add(DateUtils.getSimpleDateFormatMs().format(scandenzaT));
  6171.                 }
  6172.                
  6173.                 pstmt.setString(index++,tipo);
  6174.                 if(logQuery) {
  6175.                     objects.add(tipo);
  6176.                 }
  6177.             }
  6178.             else {
  6179.                 pstmt.setString(index++,tipo);
  6180.                 if(logQuery) {
  6181.                     objects.add(tipo);
  6182.                 }
  6183.                 pstmt.setString(index++,idModuloCleaner);
  6184.                 if(logQuery) {
  6185.                     objects.add(idModuloCleaner);
  6186.                 }
  6187.             }
  6188.            
  6189.             query = null;
  6190.             if(logQuery) {
  6191.                 query = DBUtils.formatSQLString(deleteString, objects.toArray());
  6192.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  6193.             }
  6194.             result = pstmt.executeUpdate();
  6195.             pstmt.close();
  6196.             pstmt = null;
  6197.            
  6198.             if(logQuery) {
  6199.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; "+result+" righe eliminate");
  6200.             }
  6201.             mapTabelleRigheEliminate.add(GestoreMessaggi.MESSAGGI, result);
  6202.            
  6203.            
  6204.            
  6205.             return mapTabelleRigheEliminate;
  6206.        
  6207.         } catch(Exception e) {
  6208.             String errorMsg = "[GestoreMessaggi.deleteMessaggiIntoBox] errore, deleteString["+deleteString+"]: "+e.getMessage();
  6209.             throw new GestoreMessaggiException(errorMsg,e);
  6210.         } finally {
  6211.             try{
  6212.                 if(pstmt != null)
  6213.                     pstmt.close();
  6214.             } catch(Exception er) {
  6215.                 // close
  6216.             }
  6217.         }
  6218.     }
  6219.    
  6220.    
  6221.     private static void _deleteListaRepositoryBuste(String tipoDatabase, Connection connectionDB, boolean logQuery, Logger logger,
  6222.             String nomeTabella, String nomeColonnaTipoMessaggio, String nomeColonnaIdMessaggio,
  6223.             String tipo, Date leftDate, Date rightDate, Timestamp scandenzaT, String idModuloCleaner, ISQLQueryObject sqlQueryObjectRepositoryBusteJoin,
  6224.             SortedMap<Integer> mapTabelleRigheEliminate) throws Exception {
  6225.        
  6226.         // Eliminazione busta reale
  6227.        
  6228.         ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  6229.         sqlQueryObject.addDeleteTable(nomeTabella);
  6230.         if(nomeColonnaTipoMessaggio!=null) {
  6231.             sqlQueryObject.addWhereCondition(nomeColonnaTipoMessaggio+"=?");
  6232.         }
  6233.         sqlQueryObject.addWhereINSelectSQLCondition(false, nomeColonnaIdMessaggio, sqlQueryObjectRepositoryBusteJoin);
  6234.         sqlQueryObject.setANDLogicOperator(true);
  6235.        
  6236.         String deleteString = sqlQueryObject.createSQLDelete();
  6237.         PreparedStatement pstmt = null;
  6238.         try{    
  6239.             pstmt = connectionDB.prepareStatement(deleteString);
  6240.             int index = 1;
  6241.             List<Object> objects = new ArrayList<>();
  6242.             if(nomeColonnaTipoMessaggio!=null) {
  6243.                 pstmt.setString(index++,tipo);
  6244.                 if(logQuery) {
  6245.                     objects.add(tipo);
  6246.                 }
  6247.             }
  6248.             pstmt.setString(index++,tipo); // due volte per via della ricerca ciclica
  6249.             if(logQuery) {
  6250.                 objects.add(tipo);
  6251.             }
  6252.             if(leftDate!=null) {
  6253.                 java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  6254.                 pstmt.setTimestamp(index++, leftDateT);
  6255.                 if(logQuery) {
  6256.                     objects.add(DateUtils.getSimpleDateFormatMs().format(leftDate));
  6257.                 }
  6258.             }
  6259.             if(rightDate!=null) {
  6260.                 java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  6261.                 pstmt.setTimestamp(index++, rightDateT);
  6262.                 if(logQuery) {
  6263.                     objects.add(DateUtils.getSimpleDateFormatMs().format(rightDate));
  6264.                 }
  6265.             }
  6266.             if(scandenzaT!=null) {
  6267.                 pstmt.setTimestamp(index++,scandenzaT);
  6268.                 if(logQuery) {
  6269.                     objects.add(DateUtils.getSimpleDateFormatMs().format(scandenzaT));
  6270.                 }
  6271.                
  6272.                 pstmt.setString(index++,tipo);
  6273.                 if(logQuery) {
  6274.                     objects.add(tipo);
  6275.                 }
  6276.             }
  6277.             else {
  6278.                 pstmt.setString(index++,tipo);
  6279.                 if(logQuery) {
  6280.                     objects.add(tipo);
  6281.                 }
  6282.                 pstmt.setString(index++,idModuloCleaner);
  6283.                 if(logQuery) {
  6284.                     objects.add(idModuloCleaner);
  6285.                 }
  6286.             }
  6287.            
  6288.             String query = null;
  6289.             if(logQuery) {
  6290.                 query = DBUtils.formatSQLString(deleteString, objects.toArray());
  6291.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  6292.             }
  6293.             int result = pstmt.executeUpdate();
  6294.             pstmt.close();
  6295.             pstmt = null;
  6296.            
  6297.             if(logQuery) {
  6298.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; "+result+" righe eliminate");
  6299.             }
  6300.             mapTabelleRigheEliminate.add(nomeTabella, result);
  6301.         } finally {
  6302.             try{
  6303.                 if(pstmt != null)
  6304.                     pstmt.close();
  6305.             } catch(Exception er) {
  6306.                 // close
  6307.             }
  6308.         }
  6309.     }
  6310.    
  6311.    
  6312.    



  6313.     /* ------------- LETTURA MESSAGGI DA ELIMINARE -------------- */

  6314.     /**
  6315.      * Cerca nella tabella MESSAGGI le entry che possiedono come proprietario l'ID del modulo utilizzato per l'eliminazione.
  6316.      * Ritorna un array di Stringhe contenenti l'ID di messaggi presenti nella cartella INBOX
  6317.      * che possiedono come proprietario l'ID
  6318.      * del modulo utilizzato per l'eliminazione (parametro idModuloCleaner)
  6319.      *
  6320.      * @param idModuloCleaner ID del modulo utilizzato per l'eliminazione
  6321.      * @return Nel caso l'operazione ha successo ritorna un List di stringhe, altrimenti null
  6322.      *
  6323.      */
  6324.     public List<String> readMessaggiInutiliIntoInbox(String idModuloCleaner,int limit,boolean logQuery, boolean orderBy,
  6325.             Date data)throws GestoreMessaggiException{
  6326.         return this.readMessaggiInutiliIntoBox(true,idModuloCleaner,limit,logQuery,orderBy,data);
  6327.     }
  6328.     /**
  6329.      * Cerca nella tabella MESSAGGI le entry che possiedono come proprietario l'ID del modulo utilizzato per l'eliminazione.
  6330.      * Ritorna un array di Stringhe contenenti l'ID di messaggi presenti nella cartella OUTBOX
  6331.      * che possiedono come proprietario l'ID
  6332.      * del modulo utilizzato per l'eliminazione (parametro idModuloCleaner)
  6333.      *
  6334.      * @param idModuloCleaner ID del modulo utilizzato per l'eliminazione
  6335.      * @return Nel caso l'operazione ha successo ritorna un List di stringhe, altrimenti null
  6336.      *
  6337.      */
  6338.     public List<String> readMessaggiInutiliIntoOutbox(String idModuloCleaner,int limit,boolean logQuery, boolean orderBy,
  6339.             Date data)throws GestoreMessaggiException{
  6340.         return this.readMessaggiInutiliIntoBox(false,idModuloCleaner,limit,logQuery,orderBy,data);
  6341.     }

  6342.     /**
  6343.      * Cerca nella tabella MESSAGGI le entry che possiedono come proprietario l'ID del modulo utilizzato per l'eliminazione.
  6344.      * Ritorna un array di Stringhe contenenti l'ID di messaggi presenti nella cartella INBOX (se searchIntoInbox=true)
  6345.      * o nella cartella OUTBOX (se searchIntoInbox=false) che possiedono come proprietario l'ID
  6346.      * del modulo utilizzato per l'eliminazione (parametro idModuloCleaner)
  6347.      *
  6348.      * @param searchIntoInbox Cerca nella cartella INBOX (se true) o nella cartella OUTBOX (se false)
  6349.      * @param idModuloCleaner ID del modulo utilizzato per l'eliminazione
  6350.      * @return Nel caso l'operazione ha successo ritorna un List di stringhe, altrimenti null
  6351.      *
  6352.      */
  6353.     private List<String> readMessaggiInutiliIntoBox(boolean searchIntoInbox,
  6354.             String idModuloCleaner,int limit,boolean logQuery, boolean orderBy,
  6355.             Date data)throws GestoreMessaggiException{
  6356.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  6357.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  6358.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;          
  6359.             Connection connectionDB = stateful.getConnectionDB();

  6360.             List<String> idMsg = new ArrayList<>();

  6361.             PreparedStatement pstmtMsgEliminati = null;
  6362.             ResultSet rs = null;
  6363.             String queryString = null;
  6364.             try{    
  6365.                 // tipo
  6366.                 String tipo = null;
  6367.                 if(searchIntoInbox)
  6368.                     tipo = Costanti.INBOX;
  6369.                 else
  6370.                     tipo = Costanti.OUTBOX;

  6371.                 // Query per Ricerca messaggi eliminati (proprietario:EliminatoreMesaggi)
  6372.                 if(Configurazione.getSqlQueryObjectType()==null){
  6373.                     StringBuilder query = new StringBuilder();
  6374.                     query.append("SELECT ").append(GestoreMessaggi.MESSAGGI_COLUMN_ID_MESSAGGIO).append(" FROM ");
  6375.                     query.append(GestoreMessaggi.MESSAGGI);
  6376.                     query.append(" WHERE ").append(GestoreMessaggi.MESSAGGI_COLUMN_TIPO_MESSAGGIO).append("=? AND ").append(GestoreMessaggi.MESSAGGI_COLUMN_PROPRIETARIO).append("=? ");
  6377.                     if(data!=null) {
  6378.                         query.append(" AND ").append(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE).append("<=?");
  6379.                     }
  6380.                     queryString = query.toString();
  6381.                 }else{
  6382.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  6383.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI_COLUMN_ID_MESSAGGIO);
  6384.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE);
  6385.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI_COLUMN_PROPRIETARIO);
  6386.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI_COLUMN_TIPO_MESSAGGIO);
  6387.                     sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  6388.                     sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  6389.                     sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI_COLUMN_PROPRIETARIO+"=?");
  6390.                     if(data!=null) {
  6391.                         sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE+"<=?");
  6392.                     }
  6393.                     sqlQueryObject.setANDLogicOperator(true);
  6394.                     if(orderBy){
  6395.                         sqlQueryObject.addOrderBy(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE);
  6396.                         sqlQueryObject.setSortType(true);
  6397.                     }
  6398.                     sqlQueryObject.setLimit(limit);
  6399.                     queryString = sqlQueryObject.createSQLQuery();
  6400.                 }
  6401.                 //System.out.println("QUERY MESSAGGI ELIMINATI IS: ["+queryString+"]  1["+idModuloCleaner+"]  2["+tipo+"]");

  6402.                 //log.debug("Query: "+query);
  6403.                 pstmtMsgEliminati = connectionDB.prepareStatement(queryString);
  6404.                 pstmtMsgEliminati.setString(1,tipo);
  6405.                 pstmtMsgEliminati.setString(2,idModuloCleaner);
  6406.                 java.sql.Timestamp nowT = null;
  6407.                 if(data!=null) {
  6408.                     nowT = new java.sql.Timestamp(data.getTime());
  6409.                     pstmtMsgEliminati.setTimestamp(3,nowT);
  6410.                 }

  6411.                 long startDateSQLCommand = DateManager.getTimeMillis();
  6412.                 if(logQuery)
  6413.                     this.log.debug("[QUERY] (Messaggi.eliminatiLogicamente) ["+queryString+"] 1["+tipo+"] 2["+idModuloCleaner+"] 3["+nowT+"] ...");
  6414.                 rs = pstmtMsgEliminati.executeQuery();
  6415.                 long endDateSQLCommand = DateManager.getTimeMillis();
  6416.                 long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  6417.                 if(logQuery)
  6418.                     this.log.debug("[QUERY] (Messaggi.eliminatiLogicamente) ["+queryString+"] 1["+tipo+"] 2["+idModuloCleaner+"] 3["+nowT+"] effettuata in "+secondSQLCommand+" secondi");

  6419.                 int countLimit = 0;
  6420.                 while(rs.next()){
  6421.                     idMsg.add(rs.getString("ID_MESSAGGIO"));
  6422.                     // LIMIT Applicativo
  6423.                     if(Configurazione.getSqlQueryObjectType()==null){
  6424.                         countLimit++;
  6425.                         if(countLimit==limit)
  6426.                             break;
  6427.                     }
  6428.                 }
  6429.                 rs.close();
  6430.                 pstmtMsgEliminati.close();

  6431.                 return idMsg;

  6432.             } catch(Exception e) {
  6433.                 String errorMsg = "[GestoreMessaggi.readMessaggiInutiliIntoBox] errore, queryString["+queryString+"]: "+e.getMessage();
  6434.                 try{
  6435.                     if(rs != null)
  6436.                         rs.close();
  6437.                 } catch(Exception er) {
  6438.                     // close
  6439.                 }
  6440.                 try{
  6441.                     if(pstmtMsgEliminati != null)
  6442.                         pstmtMsgEliminati.close();
  6443.                 } catch(Exception er) {
  6444.                     // close
  6445.                 }
  6446.                 this.log.error(errorMsg,e);
  6447.                 throw new GestoreMessaggiException(errorMsg,e);
  6448.             }
  6449.             // else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  6450.             // NOP stateful only
  6451.         }else{
  6452.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  6453.         }
  6454.     }






  6455.     /**
  6456.      * Cerca nella tabella MESSAGGI i messaggi che sono nelle cartelle da un intervallo di tempo definito da: <var>timeout<var>
  6457.      *
  6458.      * @param scadenzaMsg Intervallo di scadenza dei messaggi
  6459.      * @return Nel caso l'operazione ha successo ritorna un List di stringhe, altrimenti null
  6460.      *
  6461.      */
  6462.     public List<String> readMessaggiScadutiIntoInbox(long scadenzaMsg,int limit,boolean logQuery, boolean orderBy, Date data)throws GestoreMessaggiException{
  6463.         return this.readMessaggiScadutiIntoBox(true,scadenzaMsg,limit,logQuery,orderBy,data);
  6464.     }
  6465.     /**
  6466.      * Cerca nella tabella MESSAGGI i messaggi che sono nelle cartelle da un intervallo di tempo definito da: <var>timeout<var>
  6467.      *
  6468.      * @param scadenzaMsg Intervallo di scadenza dei messaggi
  6469.      * @return Nel caso l'operazione ha successo ritorna un List di stringhe, altrimenti null
  6470.      *
  6471.      */
  6472.     public List<String> readMessaggiScadutiIntoOutbox(long scadenzaMsg,int limit,boolean logQuery, boolean orderBy, Date data)throws GestoreMessaggiException{
  6473.         return this.readMessaggiScadutiIntoBox(false,scadenzaMsg,limit,logQuery,orderBy,data);
  6474.     }

  6475.     /**
  6476.      * Cerca nella tabella MESSAGGI i messaggi che sono nelle cartelle da un intervallo di tempo definito da: <var>timeout<var>
  6477.      *
  6478.      * @param searchIntoInbox Cerca nella cartella INBOX (se true) o nella cartella OUTBOX (se false)
  6479.      * @param scadenzaMsg Intervallo di scadenza dei messaggi
  6480.      * @return Nel caso l'operazione ha successo ritorna un List di stringhe, altrimenti null
  6481.      *
  6482.      */
  6483.     private List<String> readMessaggiScadutiIntoBox(boolean searchIntoInbox,long scadenzaMsg,int limit,boolean logQuery, boolean orderBy, Date data)throws GestoreMessaggiException{
  6484.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  6485.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  6486.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  6487.             Connection connectionDB = stateful.getConnectionDB();
  6488.             List<String> idMsg = new ArrayList<>();

  6489.             PreparedStatement pstmtMsgScaduti = null;
  6490.             ResultSet rs = null;
  6491.             String queryString = null;
  6492.             try{    
  6493.                 // tipo
  6494.                 String tipo = null;
  6495.                 if(searchIntoInbox)
  6496.                     tipo = Costanti.INBOX;
  6497.                 else
  6498.                     tipo = Costanti.OUTBOX;

  6499.                 // Query per Ricerca messaggi scaduti
  6500.                 // Algoritmo:
  6501.                 //    if( (now-timeout) > oraRegistrazione )
  6502.                 //       msgScaduto
  6503.                 long scadenza = DateManager.getTimeMillis() - (scadenzaMsg * 60 * 1000);
  6504.                 java.sql.Timestamp scandenzaT = new java.sql.Timestamp(scadenza);

  6505.                 // Query per Ricerca messaggi eliminati (proprietario:EliminatoreMesaggi)
  6506.                 if(Configurazione.getSqlQueryObjectType()==null){
  6507.                     StringBuilder query = new StringBuilder();
  6508.                     query.append("SELECT ").append(GestoreMessaggi.MESSAGGI_COLUMN_ID_MESSAGGIO).append(" FROM ");
  6509.                     query.append(GestoreMessaggi.MESSAGGI);
  6510.                     query.append(" WHERE ? > ").append(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE).append(" AND ").append(GestoreMessaggi.MESSAGGI_COLUMN_TIPO_MESSAGGIO).append("=?");
  6511.                     if(data!=null) {
  6512.                         query.append(" AND ").append(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE).append("<=?");
  6513.                     }
  6514.                     queryString = query.toString();
  6515.                 }else{
  6516.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  6517.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI_COLUMN_ID_MESSAGGIO);
  6518.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE);
  6519.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI_COLUMN_TIPO_MESSAGGIO);
  6520.                     sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  6521.                     sqlQueryObject.addWhereCondition("? > "+GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE);
  6522.                     sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?");
  6523.                     if(data!=null) {
  6524.                         sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE+"<=?");
  6525.                     }
  6526.                     sqlQueryObject.setANDLogicOperator(true);
  6527.                     if(orderBy){
  6528.                         sqlQueryObject.addOrderBy(GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE);
  6529.                         sqlQueryObject.setSortType(true);
  6530.                     }
  6531.                     sqlQueryObject.setLimit(limit);
  6532.                     queryString = sqlQueryObject.createSQLQuery();
  6533.                 }
  6534.                 //System.out.println("QUERY MESSAGGI SCADUTI IS: ["+queryString+"] ["+scandenzaT+"] ["+tipo+"]");

  6535.                 pstmtMsgScaduti = connectionDB.prepareStatement(queryString);
  6536.                 pstmtMsgScaduti.setTimestamp(1,scandenzaT);
  6537.                 pstmtMsgScaduti.setString(2,tipo);
  6538.                 java.sql.Timestamp nowT = null;
  6539.                 if(data!=null) {
  6540.                     nowT = new java.sql.Timestamp(data.getTime());
  6541.                     pstmtMsgScaduti.setTimestamp(3,nowT);
  6542.                 }

  6543.                 long startDateSQLCommand = DateManager.getTimeMillis();
  6544.                 if(logQuery)
  6545.                     this.log.debug("[QUERY] (Messaggi.scaduti) ["+queryString+"] 1["+scandenzaT+"] 2["+tipo+"] 3["+nowT+"]...");
  6546.                 rs = pstmtMsgScaduti.executeQuery();
  6547.                 long endDateSQLCommand = DateManager.getTimeMillis();
  6548.                 long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  6549.                 if(logQuery)
  6550.                     this.log.debug("[QUERY] (Messaggi.scaduti) ["+queryString+"] 1["+scandenzaT+"] 2["+tipo+"] 3["+nowT+"] effettuata in "+secondSQLCommand+" secondi");

  6551.                 int countLimit = 0;
  6552.                 while(rs.next()){
  6553.                     idMsg.add(rs.getString("ID_MESSAGGIO"));
  6554.                     // LIMIT Applicativo
  6555.                     if(Configurazione.getSqlQueryObjectType()==null){
  6556.                         countLimit++;
  6557.                         if(countLimit==limit)
  6558.                             break;
  6559.                     }
  6560.                 }
  6561.                 rs.close();
  6562.                 pstmtMsgScaduti.close();

  6563.                 return idMsg;

  6564.             } catch(Exception e) {
  6565.                 String errorMsg = "[GestoreMessaggi.readMessaggiScadutiIntoBox] errore, queryString["+queryString+"]: "+e.getMessage();
  6566.                 try{
  6567.                     if(rs != null)
  6568.                         rs.close();
  6569.                 } catch(Exception er) {
  6570.                     // close
  6571.                 }
  6572.                 try{
  6573.                     if(pstmtMsgScaduti != null)
  6574.                         pstmtMsgScaduti.close();
  6575.                 } catch(Exception er) {
  6576.                     // close
  6577.                 }
  6578.                 this.log.error(errorMsg,e);
  6579.                 throw new GestoreMessaggiException(errorMsg,e);
  6580.             }
  6581.         } // else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  6582.         // NOP stateful only
  6583.         else{
  6584.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  6585.         }
  6586.     }








  6587.     public boolean existsServiziApplicativiDestinatariMessaggio()throws GestoreMessaggiException{

  6588.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  6589.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  6590.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  6591.             Connection connectionDB = stateful.getConnectionDB();
  6592.             PreparedStatement pstmtExistsAnotherServiziApplicativi = null;
  6593.             ResultSet rs = null;
  6594.             String queryString = null;
  6595.             try{    
  6596.                 StringBuilder query = new StringBuilder();
  6597.                 query.append("SELECT SERVIZIO_APPLICATIVO FROM ");
  6598.                 query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  6599.                 query.append(" WHERE ID_MESSAGGIO=?");
  6600.                 queryString = query.toString();

  6601.                 pstmtExistsAnotherServiziApplicativi =  connectionDB.prepareStatement(queryString);
  6602.                 pstmtExistsAnotherServiziApplicativi.setString(1,this.idBusta);
  6603.                 rs = pstmtExistsAnotherServiziApplicativi.executeQuery();
  6604.                 boolean risultato = rs.next();
  6605.                 rs.close();
  6606.                 pstmtExistsAnotherServiziApplicativi.close();

  6607.                 return risultato;

  6608.             } catch(Exception e) {
  6609.                 String errorMsg = "[GestoreMessaggi.existsServiziApplicativiDestinatariMessaggio] errore, queryString["+queryString+"]: "+e.getMessage();
  6610.                 try{
  6611.                     if(rs != null)
  6612.                         rs.close();
  6613.                 } catch(Exception er) {
  6614.                     // close
  6615.                 }
  6616.                 try{
  6617.                     if(pstmtExistsAnotherServiziApplicativi != null)
  6618.                         pstmtExistsAnotherServiziApplicativi.close();
  6619.                 } catch(Exception er) {
  6620.                     // close
  6621.                 }
  6622.                 this.log.error(errorMsg,e);
  6623.                 throw new GestoreMessaggiException(errorMsg,e);
  6624.             }  
  6625.         }// else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  6626.         // NOP stateful only
  6627.         else{
  6628.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  6629.         }
  6630.     }

  6631.     /**
  6632.      * Cerca nella tabella MESSAGGI i messaggi destinati al servizio RicezioneContenutiApplicativi che sono stati registrati dopo lo scadere
  6633.      * del timeout per il servizio. Ritorna l'idBusta+'@'+nomeServizioApplicativo dove il servizio applicativo e' di tipo connectionReply
  6634.      *
  6635.      * @param timeout Intervallo di timeout del servizio
  6636.      * @return Nel caso l'operazione ha successo ritorna un List di stringhe, altrimenti null
  6637.      *
  6638.      */
  6639.     public List<String> readMsgForRicezioneContenutiApplicativiNonGestiti(long timeout,int limit,boolean logQuery, boolean orderBy)throws GestoreMessaggiException{
  6640.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  6641.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  6642.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  6643.             Connection connectionDB = stateful.getConnectionDB();

  6644.             List<String> idMsg = new ArrayList<>();

  6645.             PreparedStatement pstmtMsgScaduti = null;
  6646.             ResultSet rs = null;
  6647.             String queryString = null;
  6648.             try{    
  6649.                 // Query per Ricerca messaggi scaduti
  6650.                 // Algoritmo:
  6651.                 //    if( (now-timeout) > oraRegistrazione )
  6652.                 //       msgScaduto
  6653.                 long scadenza = DateManager.getTimeMillis() - (timeout);
  6654.                 java.sql.Timestamp scandenzaT = new java.sql.Timestamp(scadenza);
  6655.                 //System.out.println("TIMEOUT RICEZIONE CONTENUTI APPLICATIVI["+scandenzaT+"]");

  6656.                 // Query per Ricerca messaggi eliminati (proprietario:EliminatoreMesaggi)
  6657.                 if(Configurazione.getSqlQueryObjectType()==null){
  6658.                     StringBuilder query = new StringBuilder();
  6659.                     query.append("SELECT "+GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO as identificativoBusta,"+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".SERVIZIO_APPLICATIVO FROM ");
  6660.                     query.append(GestoreMessaggi.MESSAGGI);
  6661.                     query.append(",");
  6662.                     query.append(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  6663.                     query.append(" WHERE ? > "+GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE AND "
  6664.                             +GestoreMessaggi.MESSAGGI+".RIFERIMENTO_MSG IS NOT NULL AND "
  6665.                             +GestoreMessaggi.MESSAGGI+".TIPO=? AND " +
  6666.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".TIPO_CONSEGNA=? AND "+
  6667.                             GestoreMessaggi.MESSAGGI+".PROPRIETARIO LIKE '"+RicezioneContenutiApplicativi.ID_MODULO+"%' AND "+
  6668.                             GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".INTEGRATION_MANAGER=? AND "+
  6669.                             GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ID_MESSAGGIO ");
  6670.                     queryString = query.toString();
  6671.                 }else{
  6672.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  6673.                     sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  6674.                     sqlQueryObject.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI);
  6675.                     sqlQueryObject.addSelectAliasField(GestoreMessaggi.MESSAGGI,"ID_MESSAGGIO","identificativoBusta");
  6676.                     sqlQueryObject.addSelectField("SERVIZIO_APPLICATIVO");
  6677.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,"ORA_REGISTRAZIONE");
  6678.                     sqlQueryObject.addSelectField("RIFERIMENTO_MSG");
  6679.                     sqlQueryObject.addSelectAliasField(GestoreMessaggi.MESSAGGI,"TIPO","TipoMessaggio");
  6680.                     sqlQueryObject.addSelectField("TIPO_CONSEGNA");
  6681.                     sqlQueryObject.addSelectField("PROPRIETARIO");
  6682.                     sqlQueryObject.addSelectField("INTEGRATION_MANAGER");
  6683.                     sqlQueryObject.addWhereCondition("? > "+GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE");
  6684.                     sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".RIFERIMENTO_MSG IS NOT NULL");
  6685.                     sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".TIPO=?");
  6686.                     sqlQueryObject.addWhereCondition(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".TIPO_CONSEGNA=?");
  6687.                     sqlQueryObject.addWhereLikeCondition(GestoreMessaggi.MESSAGGI+".PROPRIETARIO", RicezioneContenutiApplicativi.ID_MODULO,true,true);
  6688.                     sqlQueryObject.addWhereCondition(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".INTEGRATION_MANAGER=?");
  6689.                     sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+".ID_MESSAGGIO");
  6690.                     sqlQueryObject.setANDLogicOperator(true);
  6691.                     if(orderBy){
  6692.                         sqlQueryObject.addOrderBy(GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE");
  6693.                         sqlQueryObject.setSortType(true);
  6694.                     }
  6695.                     sqlQueryObject.setLimit(limit);
  6696.                     queryString = sqlQueryObject.createSQLQuery();
  6697.                 }
  6698.                 //System.out.println("QUERY MESSAGGI SCADUTI RICEZIONE CONTENUTI APPLICATIVI IS: ["+queryString+"] 1["+scandenzaT+"] 2["+Costanti.INBOX+"] 3["+"ConnectionReply"+"] 4["+0+"]");

  6699.                 pstmtMsgScaduti =  connectionDB.prepareStatement(queryString);
  6700.                 pstmtMsgScaduti.setTimestamp(1,scandenzaT);
  6701.                 pstmtMsgScaduti.setString(2,Costanti.INBOX);
  6702.                 pstmtMsgScaduti.setString(3,"ConnectionReply");
  6703.                 pstmtMsgScaduti.setLong(4,0);

  6704.                 long startDateSQLCommand = DateManager.getTimeMillis();
  6705.                 if(logQuery)
  6706.                     this.log.debug("[QUERY] (Messaggi.scadutiPerRicezioneContenutiApplicativi) ["+queryString+"] 1["+scandenzaT+"] 2["+Costanti.INBOX+"] 3["+"ConnectionReply"+"] 4["+0+"]...");
  6707.                 rs = pstmtMsgScaduti.executeQuery();
  6708.                 long endDateSQLCommand = DateManager.getTimeMillis();
  6709.                 long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  6710.                 if(logQuery)
  6711.                     this.log.debug("[QUERY] Messaggi.scadutiPerRicezioneContenutiApplicativi) ["+queryString+"] 1["+scandenzaT+"] 2["+Costanti.INBOX+"] 3["+"ConnectionReply"+"] 4["+0+"] effettuata in "+secondSQLCommand+" secondi");

  6712.                 int countLimit = 0;
  6713.                 while(rs.next()){
  6714.                     idMsg.add(rs.getString("identificativoBusta")+"@"+rs.getString("SERVIZIO_APPLICATIVO"));
  6715.                     // LIMIT Applicativo
  6716.                     if(Configurazione.getSqlQueryObjectType()==null){
  6717.                         countLimit++;
  6718.                         if(countLimit==limit)
  6719.                             break;
  6720.                     }
  6721.                 }
  6722.                 rs.close();
  6723.                 pstmtMsgScaduti.close();

  6724.                 return idMsg;

  6725.             } catch(Exception e) {
  6726.                 String errorMsg = "[GestoreMessaggi.readMsgForRicezioneContenutiApplicativiNonGestiti] errore, queryString["+queryString+"]: "+e.getMessage();
  6727.                 try{
  6728.                     if(rs != null)
  6729.                         rs.close();
  6730.                 } catch(Exception er) {
  6731.                     // close
  6732.                 }
  6733.                 try{
  6734.                     if(pstmtMsgScaduti != null)
  6735.                         pstmtMsgScaduti.close();
  6736.                 } catch(Exception er) {
  6737.                     // close
  6738.                 }
  6739.                 this.log.error(errorMsg,e);
  6740.                 throw new GestoreMessaggiException(errorMsg,e);
  6741.             }   //else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  6742.             //CHECKME stateful only
  6743.         }else{
  6744.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  6745.         }
  6746.     }

  6747.     /**
  6748.      * Cerca nella tabella MESSAGGI i messaggi destinati al servizio RicezioneBuste che sono stati registrati dopo lo scadere
  6749.      * del timeout per il servizio. Ritorna l'idBusta
  6750.      *
  6751.      * @param timeout Intervallo di timeout del servizio
  6752.      * @return Nel caso l'operazione ha successo ritorna un List di stringhe, altrimenti null
  6753.      *
  6754.      */
  6755.     public List<String> readMsgForRicezioneBusteNonGestiti(long timeout,int limit,boolean logQuery, boolean orderBy)throws GestoreMessaggiException{
  6756.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  6757.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  6758.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  6759.             Connection connectionDB = stateful.getConnectionDB();

  6760.             List<String> idMsg = new ArrayList<>();

  6761.             PreparedStatement pstmtMsgScaduti = null;
  6762.             ResultSet rs = null;
  6763.             String queryString = null;
  6764.             try{    
  6765.                 // Query per Ricerca messaggi scaduti
  6766.                 // Algoritmo:
  6767.                 //    if( (now-timeout) > oraRegistrazione )
  6768.                 //       msgScaduto
  6769.                 long scadenza = DateManager.getTimeMillis() - (timeout);
  6770.                 java.sql.Timestamp scandenzaT = new java.sql.Timestamp(scadenza);
  6771.                 //System.out.println("TIMEOUT RICEZIONE BUSTE["+scandenzaT+"]");

  6772.                 // Query per Ricerca messaggi eliminati
  6773.                 if(Configurazione.getSqlQueryObjectType()==null){
  6774.                     StringBuilder query = new StringBuilder();
  6775.                     query.append("SELECT ID_MESSAGGIO FROM ");
  6776.                     query.append(GestoreMessaggi.MESSAGGI);
  6777.                     query.append(" WHERE ? > ORA_REGISTRAZIONE AND "+
  6778.                             "RIFERIMENTO_MSG IS NOT NULL AND TIPO=? AND PROPRIETARIO LIKE '"+RicezioneBuste.ID_MODULO+"%'" );
  6779.                     queryString = query.toString();
  6780.                 }else{
  6781.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  6782.                     sqlQueryObject.addSelectField("ID_MESSAGGIO");
  6783.                     sqlQueryObject.addSelectField("RIFERIMENTO_MSG");
  6784.                     sqlQueryObject.addSelectField("TIPO");
  6785.                     sqlQueryObject.addSelectField("PROPRIETARIO");
  6786.                     sqlQueryObject.addSelectField("ORA_REGISTRAZIONE");
  6787.                     sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  6788.                     sqlQueryObject.addWhereCondition("? > ORA_REGISTRAZIONE");
  6789.                     sqlQueryObject.addWhereCondition("RIFERIMENTO_MSG IS NOT NULL");
  6790.                     sqlQueryObject.addWhereCondition("TIPO=?");
  6791.                     sqlQueryObject.addWhereLikeCondition("PROPRIETARIO", RicezioneBuste.ID_MODULO,true,true);
  6792.                     sqlQueryObject.setANDLogicOperator(true);
  6793.                     if(orderBy){
  6794.                         sqlQueryObject.addOrderBy("ORA_REGISTRAZIONE");
  6795.                         sqlQueryObject.setSortType(true);
  6796.                     }
  6797.                     sqlQueryObject.setLimit(limit);
  6798.                     queryString = sqlQueryObject.createSQLQuery();
  6799.                 }
  6800.                 //System.out.println("QUERY MESSAGGI SCADUTI RICEZIONE BUSTE IS: ["+queryString+"] 1["+scandenzaT+"] 2["+Costanti.OUTBOX+"]");

  6801.                 pstmtMsgScaduti = connectionDB.prepareStatement(queryString);
  6802.                 pstmtMsgScaduti.setTimestamp(1,scandenzaT);
  6803.                 pstmtMsgScaduti.setString(2,Costanti.OUTBOX);

  6804.                 long startDateSQLCommand = DateManager.getTimeMillis();
  6805.                 if(logQuery)
  6806.                     this.log.debug("[QUERY] (Messaggi.scadutiPerRicezioneBuste) ["+queryString+"] 1["+scandenzaT+"] 2["+Costanti.OUTBOX+"]...");
  6807.                 rs = pstmtMsgScaduti.executeQuery();
  6808.                 long endDateSQLCommand = DateManager.getTimeMillis();
  6809.                 long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  6810.                 if(logQuery)
  6811.                     this.log.debug("[QUERY] Messaggi.scadutiPerRicezioneBuste) ["+queryString+"] 1["+scandenzaT+"] 2["+Costanti.OUTBOX+"] effettuata in "+secondSQLCommand+" secondi");


  6812.                 int countLimit = 0;
  6813.                 while(rs.next()){
  6814.                     idMsg.add(rs.getString("ID_MESSAGGIO"));
  6815.                     // LIMIT Applicativo
  6816.                     if(Configurazione.getSqlQueryObjectType()==null){
  6817.                         countLimit++;
  6818.                         if(countLimit==limit)
  6819.                             break;
  6820.                     }
  6821.                 }
  6822.                 rs.close();
  6823.                 pstmtMsgScaduti.close();

  6824.                 return idMsg;

  6825.             } catch(Exception e) {
  6826.                 String errorMsg = "[GestoreMessaggi.readMsgForRicezioneBusteNonGestiti] errore, queryString["+queryString+"]: "+e.getMessage();
  6827.                 try{
  6828.                     if(rs != null)
  6829.                         rs.close();
  6830.                 } catch(Exception er) {
  6831.                     // close
  6832.                 }
  6833.                 try{
  6834.                     if(pstmtMsgScaduti != null)
  6835.                         pstmtMsgScaduti.close();
  6836.                 } catch(Exception er) {
  6837.                     // close
  6838.                 }
  6839.                 this.log.error(errorMsg,e);
  6840.                 throw new GestoreMessaggiException(errorMsg,e);
  6841.             }  
  6842.         }//else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  6843.         //CHECKME stateful only
  6844.         else{
  6845.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  6846.         }
  6847.     }
















  6848.     /**
  6849.      * Ritorna le buste salvate scadute o inutilizzate (tutti gli accessi uguale a 0) nella INBOX
  6850.      *
  6851.      * @return List di stringhe contenenti gli ID delle buste scadute e/o inutilizzate con il tipo passato come parametro.
  6852.      * @throws GestoreMessaggiException
  6853.      *
  6854.      */
  6855.     public List<String> readBusteNonRiferiteDaMessaggiFromInBox(int limit,boolean logQuery,boolean forceIndex,boolean orderBy) throws ProtocolException, GestoreMessaggiException{
  6856.         return this.readBusteNonRiferiteDaMessaggi(Costanti.INBOX,limit,logQuery,forceIndex,orderBy);
  6857.     }

  6858.     /**
  6859.      * Ritorna le buste salvate scadute o inutilizzate (tutti gli accessi uguale a 0) nella OUTBOX
  6860.      *
  6861.      * @return List di stringhe contenenti gli ID delle buste scadute e/o inutilizzate con il tipo passato come parametro.
  6862.      * @throws GestoreMessaggiException
  6863.      *
  6864.      */
  6865.     public List<String> readBusteNonRiferiteDaMessaggiFromOutBox(int limit,boolean logQuery,boolean forceIndex,boolean orderBy) throws ProtocolException, GestoreMessaggiException{
  6866.         return this.readBusteNonRiferiteDaMessaggi(Costanti.OUTBOX,limit,logQuery,forceIndex,orderBy);
  6867.     }

  6868.     private List<String> readBusteNonRiferiteDaMessaggi(String tipoBusta,int limit,boolean logQuery,boolean forceIndex,boolean orderBy) throws ProtocolException, GestoreMessaggiException{

  6869.         List<String> idBuste = new ArrayList<>();
  6870.         int pdd = 0;
  6871.         int profilo = 0;
  6872.         int pddProfilo = 0;
  6873.         this._engine_ReadBusteNonRiferiteDaMessaggi(tipoBusta, limit, logQuery, forceIndex, orderBy, true, false, idBuste);
  6874.         pdd = idBuste.size();
  6875.         if(idBuste.size()<limit){
  6876.             this._engine_ReadBusteNonRiferiteDaMessaggi(tipoBusta, limit, logQuery, forceIndex, orderBy, false, true, idBuste);
  6877.             profilo = idBuste.size() - pdd;
  6878.         }
  6879.         if(idBuste.size()<limit){
  6880.             this._engine_ReadBusteNonRiferiteDaMessaggi(tipoBusta, limit, logQuery, forceIndex, orderBy, true, true, idBuste);
  6881.             pddProfilo = idBuste.size() - pdd - profilo;
  6882.         }
  6883.         if(logQuery){
  6884.             this.log.debug("["+tipoBusta+"] Trovati messaggi cosi suddivisi pdd["+pdd+"] profilo["+profilo+"] pddAndProfilo["+pddProfilo+"]");
  6885.         }
  6886.         return idBuste;

  6887.     }


  6888.     /**
  6889.      * Ritorna le buste salvate scadute o inutilizzate (tutti gli accessi uguale a 0)
  6890.      *
  6891.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta  
  6892.      * @return List di stringhe contenenti gli ID delle buste scadute e/o inutilizzate con il tipo passato come parametro.
  6893.      * @throws GestoreMessaggiException
  6894.      *
  6895.      */
  6896.     private void _engine_ReadBusteNonRiferiteDaMessaggi(String tipoBusta,int limit,boolean logQuery,boolean forceIndex,boolean orderBy,
  6897.             boolean pdd, boolean profilo,List<String> idBuste) throws ProtocolException, GestoreMessaggiException{
  6898.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  6899.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  6900.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;
  6901.             Connection connectionDB = stateful.getConnectionDB();
  6902.             PreparedStatement pstmt = null;
  6903.             ResultSet rs = null;
  6904.             String queryString = null;
  6905.             try{    

  6906.                 String tipoRovesciato = null;
  6907.                 if(Costanti.INBOX.equals(tipoBusta))
  6908.                     tipoRovesciato = Costanti.OUTBOX;
  6909.                 else
  6910.                     tipoRovesciato = Costanti.INBOX;

  6911.                 IGestoreRepository gestoreRepositoryBuste = Configurazione.getGestoreRepositoryBuste();

  6912.                 // Selezioni i messaggi in RepositoryBuste dove l'idBusta non e' associato
  6913.                 //   -- ad un messaggio con stesso tipo e identificativo
  6914.                 //   -- ad un messaggio che possiede il riferimento msg come l'id della busta e con tipo invertito
  6915.                 // e (dove Pdd=1 o Profilo=1: questo controllo serve per non fare andare in loopback il timer fino a che la busta non e' davvero eliminata
  6916.                 //                            (possiede tutti gli accessi a 0))
  6917.                 // e dove la busta non e' utilizzata per il profilo Asincrono

  6918.                 // Gli identificativi ritornati devono essere utilizzati per effettuare il rollback SOLO di pdd e profilo
  6919.                 // NOTA: non serve fare il rollback dell'history tanto se rimane solo quello, quando la busta e' scaduta viene eliminata.

  6920.                 if(Configurazione.getSqlQueryObjectType()==null){
  6921.                     StringBuilder query = new StringBuilder();
  6922.                     query.append("SELECT ");
  6923.                     if(forceIndex){
  6924.                         query.append("/*+ index("+Costanti.REPOSITORY+" "+Costanti.REPOSITORY_INDEX_TIPO_SEARCH+") */");
  6925.                     }
  6926.                     query.append(" ID_MESSAGGIO FROM ");
  6927.                     query.append(Costanti.REPOSITORY);
  6928.                     query.append(" WHERE ");

  6929.                     // tipo
  6930.                     query.append(" TIPO=? AND ");

  6931.                     // pdd=1 OR profilo=1
  6932.                     if(pdd && profilo){
  6933.                         query.append(gestoreRepositoryBuste.createSQLCondition_enableOnlyPddAndProfilo());
  6934.                     }
  6935.                     else if(pdd){
  6936.                         query.append(gestoreRepositoryBuste.createSQLCondition_enableOnlyPdd());
  6937.                     }
  6938.                     else if(profilo){
  6939.                         query.append(gestoreRepositoryBuste.createSQLCondition_enableOnlyProfilo());
  6940.                     }
  6941.                     else{
  6942.                         throw new Exception("Utilizzo errato del metodo, almeno una indicazione tra pdd e profilo deve essere fornita");
  6943.                     }
  6944.                     query.append(" AND ");

  6945.                     //                  query.append("( ");
  6946.                     //                  query.append(gestoreRepositoryBuste.createSQLCondition_ProfiloCollaborazione(true));
  6947.                     //                  query.append(" OR ");
  6948.                     //                  query.append(gestoreRepositoryBuste.createSQLCondition_PdD(true));
  6949.                     //                  query.append(" ) AND ");

  6950.                     // asincrono non utilizzato per profilo asincrono
  6951.                     query.append("(");
  6952.                     query.append("  NOT EXISTS (");
  6953.                     query.append("  SELECT * FROM ");
  6954.                     query.append(Costanti.PROFILO_ASINCRONO);
  6955.                     query.append("  WHERE ");
  6956.                     query.append("    ( ");
  6957.                     query.append(Costanti.PROFILO_ASINCRONO+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO AND ");
  6958.                     query.append(Costanti.PROFILO_ASINCRONO+".TIPO="+Costanti.REPOSITORY+".TIPO");
  6959.                     query.append("    ) ");
  6960.                     query.append("  )");
  6961.                     query.append(") AND ");

  6962.                     // messaggi
  6963.                     query.append("(");
  6964.                     query.append(" NOT EXISTS (");
  6965.                     query.append(" SELECT * FROM ");
  6966.                     query.append(GestoreMessaggi.MESSAGGI);
  6967.                     query.append(" WHERE ");
  6968.                     query.append("( ");
  6969.                     // Messaggi.idBusta
  6970.                     query.append(GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO AND ");
  6971.                     query.append(GestoreMessaggi.MESSAGGI+".TIPO="+Costanti.REPOSITORY+".TIPO");
  6972.                     query.append(" ) OR ( ");
  6973.                     // RiferimentoMessaggi
  6974.                     query.append(GestoreMessaggi.MESSAGGI+".RIFERIMENTO_MSG="+Costanti.REPOSITORY+".ID_MESSAGGIO AND ");
  6975.                     query.append(GestoreMessaggi.MESSAGGI+".TIPO=?");
  6976.                     query.append(" ) ");
  6977.                     query.append(")");
  6978.                     query.append(")");

  6979.                     queryString = query.toString();
  6980.                 }else{
  6981.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  6982.                     if(forceIndex){
  6983.                         sqlQueryObject.addSelectForceIndex(Costanti.REPOSITORY, Costanti.REPOSITORY_INDEX_TIPO_SEARCH);
  6984.                     }
  6985.                     sqlQueryObject.addSelectField("ID_MESSAGGIO");
  6986.                     sqlQueryObject.addSelectField("TIPO");
  6987.                     sqlQueryObject.addSelectField(gestoreRepositoryBuste.createSQLFields());
  6988.                     sqlQueryObject.addSelectField("ORA_REGISTRAZIONE");
  6989.                     sqlQueryObject.addFromTable(Costanti.REPOSITORY);

  6990.                     // tipo
  6991.                     sqlQueryObject.addWhereCondition("TIPO=?");

  6992.                     // pdd=1 OR profilo=1
  6993.                     if(pdd && profilo){
  6994.                         sqlQueryObject.addWhereCondition(gestoreRepositoryBuste.createSQLCondition_enableOnlyPddAndProfilo());
  6995.                     }
  6996.                     else if(pdd){
  6997.                         sqlQueryObject.addWhereCondition(gestoreRepositoryBuste.createSQLCondition_enableOnlyPdd());
  6998.                     }
  6999.                     else if(profilo){
  7000.                         sqlQueryObject.addWhereCondition(gestoreRepositoryBuste.createSQLCondition_enableOnlyProfilo());
  7001.                     }
  7002.                     else{
  7003.                         throw new Exception("Utilizzo errato del metodo, almeno una indicazione tra pdd e profilo deve essere fornita");
  7004.                     }
  7005.                     //                  sqlQueryObject.addWhereCondition(false,
  7006.                     //                          gestoreRepositoryBuste.createSQLCondition_ProfiloCollaborazione(true),
  7007.                     //                          gestoreRepositoryBuste.createSQLCondition_PdD(true));

  7008.                     // asincrono non utilizzato per profilo asincrono
  7009.                     ISQLQueryObject sqlQueryObjectAsincronoNotExists = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());  
  7010.                     sqlQueryObjectAsincronoNotExists.addFromTable(Costanti.PROFILO_ASINCRONO);
  7011.                     sqlQueryObjectAsincronoNotExists.addWhereCondition(true, Costanti.PROFILO_ASINCRONO+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO",
  7012.                             Costanti.PROFILO_ASINCRONO+".TIPO="+Costanti.REPOSITORY+".TIPO");
  7013.                     sqlQueryObject.addWhereExistsCondition(true, sqlQueryObjectAsincronoNotExists);

  7014.                     // Messaggi
  7015.                     ISQLQueryObject sqlQueryObjectMessaggiNotExists = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());    
  7016.                     sqlQueryObjectMessaggiNotExists.addFromTable(GestoreMessaggi.MESSAGGI);
  7017.                     sqlQueryObjectMessaggiNotExists.addWhereCondition(true, GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO",
  7018.                             GestoreMessaggi.MESSAGGI+".TIPO="+Costanti.REPOSITORY+".TIPO");
  7019.                     sqlQueryObjectMessaggiNotExists.addWhereCondition(true, GestoreMessaggi.MESSAGGI+".RIFERIMENTO_MSG="+Costanti.REPOSITORY+".ID_MESSAGGIO",
  7020.                             GestoreMessaggi.MESSAGGI+".TIPO=?");
  7021.                     sqlQueryObjectMessaggiNotExists.setANDLogicOperator(false);

  7022.                     sqlQueryObject.addWhereExistsCondition(true, sqlQueryObjectMessaggiNotExists);
  7023.                     sqlQueryObject.setANDLogicOperator(true);
  7024.                     if(orderBy){
  7025.                         sqlQueryObject.addOrderBy("ORA_REGISTRAZIONE");
  7026.                         sqlQueryObject.setSortType(true);
  7027.                     }
  7028.                     sqlQueryObject.setLimit(limit);
  7029.                     queryString = sqlQueryObject.createSQLQuery();
  7030.                 }

  7031.                 //System.out.println("STRING QUERY REPOSITORY1 ["+queryString+"] 1["+tipoBusta+"] 2["+tipoRovesciato+"]...");
  7032.                 pstmt = connectionDB.prepareStatement(queryString);
  7033.                 pstmt.setString(1,tipoBusta);
  7034.                 pstmt.setString(2,tipoRovesciato);

  7035.                 long startDateSQLCommand = DateManager.getTimeMillis();
  7036.                 if(logQuery)
  7037.                     this.log.debug("[QUERY] (Messaggi.busteNonRiferite) ["+queryString+"] 1["+tipoBusta+"] 2["+tipoRovesciato+"]...");
  7038.                 rs = pstmt.executeQuery();
  7039.                 long endDateSQLCommand = DateManager.getTimeMillis();
  7040.                 long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  7041.                 if(logQuery)
  7042.                     this.log.debug("[QUERY] (Messaggi.busteNonRiferite) ["+queryString+"] 1["+tipoBusta+"] 2["+tipoRovesciato+"] effettuata in "+secondSQLCommand+" secondi");

  7043.                 int countLimit = 0;
  7044.                 //System.out.println("STRING QUERY REPOSITORY1 ["+queryString+"] 1["+tipoBusta+"] 2["+tipoRovesciato+"] effettuata");
  7045.                 while(rs.next()){
  7046.                     String id = rs.getString("ID_MESSAGGIO");
  7047.                     if(idBuste.contains(id)==false){
  7048.                         idBuste.add(id);
  7049.                         //System.out.println("TROVATO ["+rs.getString("ID_MESSAGGIO")+"]");
  7050.                         // LIMIT Applicativo
  7051.                         if(Configurazione.getSqlQueryObjectType()==null){
  7052.                             countLimit++;
  7053.                             if(countLimit==limit)
  7054.                                 break;
  7055.                         }
  7056.                     }
  7057.                 }
  7058.                 rs.close();
  7059.                 pstmt.close();



  7060.                 // Selezioni i messaggi in RepositoryBuste dove l'idBusta non e' associato
  7061.                 //   -- ad un messaggio con stesso tipo e identificativo
  7062.                 //   -- ad un messaggio che possiede il riferimento msg come l'id della busta e con tipo invertito
  7063.                 // e (dove Pdd=1 o Profilo=1: questo controllo serve per non fare andare in loopback il timer fino a che la busta non e' davvero eliminata
  7064.                 //                            (possiede tutti gli accessi a 0))
  7065.                 // e dove la busta e' utilizzata per il profilo Asincrono con pdd=1 o profilo=1 pero' e' scaduta
  7066.                 // Gli identificativi ritornati devono essere utilizzati per effettuare il rollback SOLO di pdd e profilo
  7067.                 // NOTA: non serve fare il rollback dell'history tanto se rimane solo quello, quando la busta e' scaduta viene eliminata.

  7068.                 if(Configurazione.getSqlQueryObjectType()==null){
  7069.                     StringBuilder query = new StringBuilder();
  7070.                     query.append("SELECT ");
  7071.                     if(forceIndex){
  7072.                         query.append("/*+ index("+Costanti.REPOSITORY+" "+Costanti.REPOSITORY_INDEX_TIPO_SEARCH+") */");
  7073.                     }
  7074.                     query.append(" ID_MESSAGGIO FROM ");
  7075.                     query.append(Costanti.REPOSITORY);
  7076.                     query.append(" WHERE ");

  7077.                     // tipo
  7078.                     query.append(" TIPO=? AND ");

  7079.                     // pdd=1 OR profilo=1
  7080.                     if(pdd && profilo){
  7081.                         query.append(gestoreRepositoryBuste.createSQLCondition_enableOnlyPddAndProfilo());
  7082.                     }
  7083.                     else if(pdd){
  7084.                         query.append(gestoreRepositoryBuste.createSQLCondition_enableOnlyPdd());
  7085.                     }
  7086.                     else if(profilo){
  7087.                         query.append(gestoreRepositoryBuste.createSQLCondition_enableOnlyProfilo());
  7088.                     }
  7089.                     else{
  7090.                         throw new Exception("Utilizzo errato del metodo, almeno una indicazione tra pdd e profilo deve essere fornita");
  7091.                     }
  7092.                     query.append(" AND ");
  7093.                     //                  query.append("( ");
  7094.                     //                  query.append(gestoreRepositoryBuste.createSQLCondition_ProfiloCollaborazione(true));
  7095.                     //                  query.append(" OR ");
  7096.                     //                  query.append(gestoreRepositoryBuste.createSQLCondition_PdD(true));
  7097.                     //                  query.append(" ) AND ");

  7098.                     // asincrono  utilizzato per profilo asincrono ma scaduto
  7099.                     query.append("(");
  7100.                     query.append("  EXISTS (");
  7101.                     query.append("  SELECT * FROM ");
  7102.                     query.append(Costanti.PROFILO_ASINCRONO);
  7103.                     query.append("  WHERE ");
  7104.                     query.append("    ( ");
  7105.                     query.append(Costanti.PROFILO_ASINCRONO+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO AND ");
  7106.                     query.append(Costanti.PROFILO_ASINCRONO+".TIPO="+Costanti.REPOSITORY+".TIPO AND ");
  7107.                     query.append(Costanti.REPOSITORY+".SCADENZA_BUSTA < ?");
  7108.                     query.append("    ) ");
  7109.                     query.append("  )");
  7110.                     query.append(") AND ");

  7111.                     // messaggi
  7112.                     query.append("(");
  7113.                     query.append(" NOT EXISTS (");
  7114.                     query.append(" SELECT * FROM ");
  7115.                     query.append(GestoreMessaggi.MESSAGGI);
  7116.                     query.append(" WHERE ");
  7117.                     query.append("( ");
  7118.                     // Messaggi.idBusta
  7119.                     query.append(GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO AND ");
  7120.                     query.append(GestoreMessaggi.MESSAGGI+".TIPO="+Costanti.REPOSITORY+".TIPO");
  7121.                     query.append(" ) OR ( ");
  7122.                     // RiferimentoMessaggi
  7123.                     query.append(GestoreMessaggi.MESSAGGI+".RIFERIMENTO_MSG="+Costanti.REPOSITORY+".ID_MESSAGGIO AND ");
  7124.                     query.append(GestoreMessaggi.MESSAGGI+".TIPO=?");
  7125.                     query.append(" ) ");
  7126.                     query.append(")");
  7127.                     query.append(")");

  7128.                     queryString = query.toString();
  7129.                 }else{
  7130.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  7131.                     if(forceIndex){
  7132.                         sqlQueryObject.addSelectForceIndex(Costanti.REPOSITORY, Costanti.REPOSITORY_INDEX_TIPO_SEARCH);
  7133.                     }
  7134.                     sqlQueryObject.addSelectField("ID_MESSAGGIO");
  7135.                     sqlQueryObject.addSelectField("TIPO");
  7136.                     sqlQueryObject.addSelectField(gestoreRepositoryBuste.createSQLFields());
  7137.                     sqlQueryObject.addSelectField("ORA_REGISTRAZIONE");
  7138.                     sqlQueryObject.addFromTable(Costanti.REPOSITORY);

  7139.                     // tipo
  7140.                     sqlQueryObject.addWhereCondition("TIPO=?");

  7141.                     // pdd=1 OR profilo=1
  7142.                     if(pdd && profilo){
  7143.                         sqlQueryObject.addWhereCondition(gestoreRepositoryBuste.createSQLCondition_enableOnlyPddAndProfilo());
  7144.                     }
  7145.                     else if(pdd){
  7146.                         sqlQueryObject.addWhereCondition(gestoreRepositoryBuste.createSQLCondition_enableOnlyPdd());
  7147.                     }
  7148.                     else if(profilo){
  7149.                         sqlQueryObject.addWhereCondition(gestoreRepositoryBuste.createSQLCondition_enableOnlyProfilo());
  7150.                     }
  7151.                     else{
  7152.                         throw new Exception("Utilizzo errato del metodo, almeno una indicazione tra pdd e profilo deve essere fornita");
  7153.                     }
  7154.                     //                  sqlQueryObject.addWhereCondition(false,
  7155.                     //                          gestoreRepositoryBuste.createSQLCondition_ProfiloCollaborazione(true),
  7156.                     //                          gestoreRepositoryBuste.createSQLCondition_PdD(true));

  7157.                     // asincrono utilizzato per profilo asincrono ma scaduto
  7158.                     ISQLQueryObject sqlQueryObjectAsincronoExists = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());  
  7159.                     sqlQueryObjectAsincronoExists.addFromTable(Costanti.PROFILO_ASINCRONO);
  7160.                     sqlQueryObjectAsincronoExists.addWhereCondition(Costanti.PROFILO_ASINCRONO+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO");
  7161.                     sqlQueryObjectAsincronoExists.addWhereCondition(Costanti.PROFILO_ASINCRONO+".TIPO="+Costanti.REPOSITORY+".TIPO");
  7162.                     sqlQueryObjectAsincronoExists.addWhereCondition(Costanti.REPOSITORY+".SCADENZA_BUSTA < ?");
  7163.                     sqlQueryObjectAsincronoExists.setANDLogicOperator(true);
  7164.                     sqlQueryObject.addWhereExistsCondition(false, sqlQueryObjectAsincronoExists);

  7165.                     // Messaggi
  7166.                     ISQLQueryObject sqlQueryObjectMessaggiNotExists = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());    
  7167.                     sqlQueryObjectMessaggiNotExists.addFromTable(GestoreMessaggi.MESSAGGI);
  7168.                     sqlQueryObjectMessaggiNotExists.addWhereCondition(true, GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO",
  7169.                             GestoreMessaggi.MESSAGGI+".TIPO="+Costanti.REPOSITORY+".TIPO");
  7170.                     sqlQueryObjectMessaggiNotExists.addWhereCondition(true, GestoreMessaggi.MESSAGGI+".RIFERIMENTO_MSG="+Costanti.REPOSITORY+".ID_MESSAGGIO",
  7171.                             GestoreMessaggi.MESSAGGI+".TIPO=?");
  7172.                     sqlQueryObjectMessaggiNotExists.setANDLogicOperator(false);

  7173.                     sqlQueryObject.addWhereExistsCondition(true, sqlQueryObjectMessaggiNotExists);
  7174.                     sqlQueryObject.setANDLogicOperator(true);
  7175.                     if(orderBy){
  7176.                         sqlQueryObject.addOrderBy("ORA_REGISTRAZIONE");
  7177.                         sqlQueryObject.setSortType(true);
  7178.                     }
  7179.                     sqlQueryObject.setLimit(limit);
  7180.                     queryString = sqlQueryObject.createSQLQuery();
  7181.                 }

  7182.                 Timestamp now = DateManager.getTimestamp();
  7183.                 //System.out.println("STRING QUERY REPOSITORY2 ["+queryString+"] 1["+now+"] 2["+tipoBusta+"] 3["+tipoRovesciato+"] ...");
  7184.                 pstmt = connectionDB.prepareStatement(queryString);
  7185.                 pstmt.setString(1,tipoBusta);
  7186.                 pstmt.setTimestamp(2,now);
  7187.                 pstmt.setString(3,tipoRovesciato);

  7188.                 startDateSQLCommand = DateManager.getTimeMillis();
  7189.                 if(logQuery)
  7190.                     this.log.debug("[QUERY] (Messaggi.busteNonRiferite_asincrono) ["+queryString+"] 1["+tipoBusta+"] 2["+now+"] 3["+tipoRovesciato+"]...");
  7191.                 rs = pstmt.executeQuery();
  7192.                 endDateSQLCommand = DateManager.getTimeMillis();
  7193.                 secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  7194.                 if(logQuery)
  7195.                     this.log.debug("[QUERY] (Messaggi.busteNonRiferite_asincrono) ["+queryString+"] 1["+tipoBusta+"] 2["+now+"] 3["+tipoRovesciato+"] effettuata in "+secondSQLCommand+" secondi");

  7196.                 countLimit = 0;
  7197.                 //System.out.println("STRING QUERY REPOSITORY2 ["+queryString+"] 1["+now+"] 2["+tipoBusta+"] 3["+tipoRovesciato+"] effettuata");
  7198.                 while(rs.next()){
  7199.                     String id = rs.getString("ID_MESSAGGIO");
  7200.                     if(idBuste.contains(id)==false){
  7201.                         idBuste.add(id);
  7202.                         //System.out.println("TROVATO ["+rs.getString("ID_MESSAGGIO")+"]");
  7203.                         // LIMIT Applicativo
  7204.                         if(Configurazione.getSqlQueryObjectType()==null){
  7205.                             countLimit++;
  7206.                             if(countLimit==limit)
  7207.                                 break;
  7208.                         }
  7209.                     }
  7210.                 }
  7211.                 rs.close();
  7212.                 pstmt.close();

  7213.             } catch(Exception e) {
  7214.                 String errorMsg = "[RepositoryBuste.getBusteDaEliminare] errore, queryString["+queryString+"]: "+e.getMessage();
  7215.                 this.log.error(errorMsg,e);
  7216.                 try{
  7217.                     if(rs != null)
  7218.                         rs.close();
  7219.                 } catch(Exception er) {
  7220.                     // Eccezione SQL.
  7221.                 }
  7222.                 try{
  7223.                     if(pstmt != null)
  7224.                         pstmt.close();
  7225.                 } catch(Exception er) {
  7226.                     // Eccezione SQL.
  7227.                 }
  7228.                 throw new ProtocolException(errorMsg,e);
  7229.             }
  7230.         }//else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  7231.         //CHECKME stateful only
  7232.         else{
  7233.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  7234.         }
  7235.     }


















  7236.     /* ------------- ELIMINAZIONE MESSAGGI -------------- */
  7237.     public void logicDeleteMessage()throws GestoreMessaggiException{
  7238.         this.aggiornaProprietarioMessaggio_engine(TimerGestoreMessaggi.ID_MODULO, false, true);
  7239.     }

  7240.     /*
  7241.      * !!! NOTA IL PROBLEMA DESCRITTO DI SEGUITO E' STATO RISOLTO UTILIZZANDO UN ALTRA SOLUZIONE descritta nel metodo deleteMessageByOraRegistrazione !!
  7242.      *
  7243.      * Fix problem:
  7244.      * I servizi RicezioneBuste e RicezioneContenutiApplicativi ed i Moduli InoltroBuste e InoltroRisposte, quando ricevono un messaggio controllano
  7245.      * se tale messaggio risulta gia' presente nella base dati.
  7246.      * In particolare va fatta attenzione quando viene rilevata la presenza di tale messaggio con proprietario 'GestoreMessaggi' che rappresenta l'eliminazione logica.
  7247.      *
  7248.      * Prima della gestione tramite lock poteva succedere che:
  7249.      * - t1 il timer GestoreMessaggi raccoglie le liste dei messaggi da eliminare tra cui l'id ID_A
  7250.      * - t2 il servizio es. RicezioneBuste rileva che l'id ID_A risulta esistente nella base dati con con proprietario 'GestoreMessaggi' e forza l'eliminazione fisica.
  7251.      * - t3 il servizio es. RicezioneBuste continua poi il processamento registrando nuovamente il messaggio con proprietario il modulo successivo, ad es. Sbustamento.
  7252.      * - t4 il servizio es. RicezioneBuste finisce correttamente l'elaborazione del messaggio, magari con presa in carico, avendolo consegnato alla coda ConsegnaContenutiApplicativi.
  7253.      * - t5 il timer GestoreMessaggi al tempo t5 processa effettivamente il messaggio con tale id ID_A e lo elimina. Ma questa eliminazione e' ERRATA poiche il proprietario e' cambiato,
  7254.      *      Tale id era pero' stato identificato al tempo t1.
  7255.      * - t6 Il Modulo ConsegnaContenutiApplicativi viene attivato dal MDB, ma non trovando info su tale ID_A termina subito e quindi non effettua la consegna.
  7256.      *
  7257.      * Con la gestione tramite lock il bug viene superato.
  7258.      *
  7259.      * Il Timer GestoreMessaggi acquisisce il lock prima di identificare i messaggi da eliminare.
  7260.      * Il Servizio puntuale, es. RicezioneBuste, acquisisce il lock quando rileva un msg con proprietario 'GestoreMessaggi' (eliminato logicamente) dovendo effettuare una eliminazione fisica forzata per poter proseguire con l'elaborazione.
  7261.      * In questa maniera:
  7262.      * - se il lock viene preso prima dal Timer, questo lo elimina effettivamente.
  7263.      *   Quando poi il lock viene preso dal servizio puntuale, l'eliminazione non apportera' modifiche effettive sulla basedati (gia eliminato dal timer).
  7264.      *   Pero' poi quando il servizio puntuale ne registra una nuova copia, questo non subira' cancellazioni poiche' il timer ha gia finito l'elaborazione.
  7265.      * - se il lock viene preso prima dal servizio puntuale,  questo lo elimina effettivamente e poi ne creera' eventualmente una nuova versione.
  7266.      *   Quando il lock viene preso dal Timer, tale messaggio non viene rilevato o perche' non esiste proprio sulla base dati o perche' possiede un proprietario diverso da GestoreMessaggi.
  7267.      *
  7268.      * La gestione viene ampliata anche per quanto concerne il repository delle buste.
  7269.      * Il Timer di GestoreRepositoryBuste lo stesso acquisira' il lock prima di esaminare se ci sono buste da eliminare.
  7270.      * Rimane aperta la possibilita' di avere una inconsistenza nei punti (RicezioneBuste,RicezioneContenutiApplicativi)
  7271.      * in cui deve essere registrato il repository delle buste poiche' viene effettuato il seguente codice:
  7272.      * if(busta.exists)
  7273.      *     busta.update
  7274.      * else
  7275.      *         busta.create
  7276.      * Quindi potrebbe succedere in un caso limite che quando si appresta ad effettuare l'update il timer elimina la busta e il mittente ottiene un errore.
  7277.      * Per risolvere questo problema andrebbe messo in lock anche nel codice sopra riportato, pero' questo comporta un blocco su tutto quel punto.
  7278.      * Comunque anche se avviene questo caso limite, non si ha inconsistenze del database ma solo un errore ritornato al mittente.
  7279.      * Il lock viene allora utilizzato SOLO se si ha un errore in update. Viene replicato il codice di update stavolta dentro il lock.
  7280.      *  
  7281.      **/

  7282.     /**
  7283.      * Elimina il messaggio gestito da OpenSPCoop.
  7284.      *
  7285.      * Deprecated: using deleteMessageByOraRegistrazione
  7286.      */
  7287.     @Deprecated
  7288.     public void deleteMessageWithLock(String causa, long attesaAttivaLock, int checkIntervalLock) throws GestoreMessaggiException{
  7289.         _deleteMessageWithLock(causa, attesaAttivaLock, checkIntervalLock);
  7290.     }
  7291.     public void _deleteMessageWithLock(String causa, long attesaAttivaLock, int checkIntervalLock) throws GestoreMessaggiException{
  7292.         Connection connectionDB = null;
  7293.         if( (this.openspcoopstate instanceof OpenSPCoopStateful) || (this.oneWayVersione11)) {
  7294.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  7295.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  7296.             connectionDB = stateMSG.getConnectionDB();
  7297.         }
  7298.        
  7299.         Semaphore semaphoreDB = null;
  7300.         TimerLock timerLock = null;
  7301.         try {
  7302.             timerLock = new TimerLock(TipoLock._getLockGestioneRepositoryMessaggi());
  7303.         }catch(Exception e){
  7304.             throw new GestoreMessaggiException(e.getMessage(),e);
  7305.         }
  7306.         try{
  7307.            
  7308.             try{
  7309.                 semaphoreDB = this.getSemaphoreByInstance(timerLock.getIdLock());
  7310.             }catch(Exception e){
  7311.                 throw new GestoreMessaggiException(e.getMessage(),e);
  7312.             }
  7313.            
  7314.             try{
  7315.                 GestoreMessaggi.acquireLock(semaphoreDB, connectionDB, timerLock,
  7316.                         this.msgDiag, causa, attesaAttivaLock, checkIntervalLock);
  7317.             }
  7318.             catch(Exception e){
  7319.                 throw new GestoreMessaggiException(e.getMessage(),e);
  7320.             }

  7321.             deleteMessage(null);

  7322.         }finally{
  7323.             try{
  7324.                 GestoreMessaggi.releaseLock(semaphoreDB, connectionDB, timerLock,
  7325.                         this.msgDiag, causa);
  7326.             }catch(Exception e){
  7327.                 // ignore
  7328.             }
  7329.         }
  7330.     }
  7331.     /**
  7332.      * Elimina il messaggio gestito da OpenSPCoop.
  7333.      *
  7334.      * Deprecated: using deleteMessageByOraRegistrazione
  7335.      */
  7336.     @Deprecated
  7337.     public void deleteMessageWithoutLock() throws GestoreMessaggiException{
  7338.         _deleteMessageWithoutLock();
  7339.     }
  7340.     public void _deleteMessageWithoutLock() throws GestoreMessaggiException{
  7341.         deleteMessage(null);
  7342.     }
  7343.    
  7344.     /*
  7345.      * Fix problem:
  7346.      * I servizi RicezioneBuste e RicezioneContenutiApplicativi ed i Moduli InoltroBuste e InoltroRisposte, quando ricevono un messaggio controllano
  7347.      * se tale messaggio risulta gia' presente nella base dati.
  7348.      * In particolare va fatta attenzione quando viene rilevata la presenza di tale messaggio con proprietario 'GestoreMessaggi' che rappresenta l'eliminazione logica.
  7349.      *
  7350.      * Prima della gestione tramite lock poteva succedere che:
  7351.      * - t1 il timer GestoreMessaggi raccoglie le liste dei messaggi da eliminare tra cui l'id ID_A
  7352.      * - t2 il servizio es. RicezioneBuste rileva che l'id ID_A risulta esistente nella base dati con con proprietario 'GestoreMessaggi' e forza l'eliminazione fisica.
  7353.      * - t3 il servizio es. RicezioneBuste continua poi il processamento registrando nuovamente il messaggio con proprietario il modulo successivo, ad es. Sbustamento.
  7354.      * - t4 il servizio es. RicezioneBuste finisce correttamente l'elaborazione del messaggio, magari con presa in carico, avendolo consegnato alla coda ConsegnaContenutiApplicativi.
  7355.      * - t5 il timer GestoreMessaggi al tempo t5 processa effettivamente il messaggio con tale id ID_A e lo elimina. Ma questa eliminazione e' ERRATA poiche il proprietario e' cambiato,
  7356.      *      Tale id era pero' stato identificato al tempo t1.
  7357.      * - t6 Il Modulo ConsegnaContenutiApplicativi viene attivato dal MDB, ma non trovando info su tale ID_A termina subito e quindi non effettua la consegna.
  7358.      *
  7359.      * Con la gestione tramite data il bug viene superato.
  7360.      *
  7361.      * Il Timer GestoreMessaggi quando avvia l'esecuzione mantiene la DATA_CHECK e acquisisce i messaggi da eliminare la cui ora di registrazione è inferiore alla DATA_CHECK.
  7362.      * Inoltre ogni delete di un messaggio avviene con le istruzioni su ogni tabella che verificano che l'ora di registrazione sia inferiore a DATA_CHECK.
  7363.      * Il Servizio puntuale, es. RicezioneBuste, quando rileva un msg con proprietario 'GestoreMessaggi' (eliminato logicamente) deve effettuare una eliminazione fisica forzata per poter proseguire con l'elaborazione.
  7364.      * In questa maniera:
  7365.      * - se il messaggio rientra nella lista presa prima dal Timer, questo lo elimina effettivamente.
  7366.      *   Quando poi la "cpu" torna al servizio puntuale, l'eliminazione non apportera' modifiche effettive sulla basedati (gia eliminato dal timer).
  7367.      *   Pero' poi quando il servizio puntuale ne registra una nuova copia, questo non subira' cancellazioni poiche' le eliminazioni del timer verificano che l'ora di registrazione sia inferiore a DATA_CHECK,
  7368.      *   e invece la nuova copia avrà una ora di registrazione successiva.
  7369.      * - se il lock viene preso prima dal servizio puntuale,  questo lo elimina effettivamente e poi ne creera' eventualmente una nuova versione.
  7370.      *   Quando il Timer si attiva, tale messaggio non viene rilevato o perche' non esiste proprio sulla base dati o perche' possiede un proprietario diverso da GestoreMessaggi.
  7371.      *
  7372.      * La gestione viene ampliata anche per quanto concerne il repository delle buste.
  7373.      * Il Timer di GestoreRepositoryBuste lo stesso mantiene una sua DATA_CHECK prima di esaminare se ci sono buste da eliminare.
  7374.      * Inoltre ogni delete di una busta avviene con le istruzioni su ogni tabella che verificano che la data di registrazione sia inferiore a DATA_CHECK.
  7375.      * Rimane aperta la possibilita' di avere una inconsistenza nei punti (RicezioneBuste,RicezioneContenutiApplicativi)
  7376.      * in cui deve essere registrato il repository delle buste poiche' viene effettuato il seguente codice:
  7377.      * if(busta.exists)
  7378.      *     busta.update
  7379.      * else
  7380.      *     busta.create
  7381.      * Quindi potrebbe succedere in un caso limite che quando si appresta ad effettuare l'update il timer elimina la busta e il mittente ottiene un errore.
  7382.      * Per risolvere questo problema andrebbe utilizzata la soluzione con lock deprecata e descritta in deleteMessageWithLock anche nel codice sopra riportato, pero' questo comporta un blocco su tutto quel punto.
  7383.      * Comunque anche se avviene questo caso limite, non si ha inconsistenze del database ma solo un errore ritornato al mittente.
  7384.      *  
  7385.      **/
  7386.     public void deleteMessageByOraRegistrazione(Date data) throws GestoreMessaggiException{
  7387.         deleteMessage(data);
  7388.     }
  7389.     public void deleteMessageByNow() throws GestoreMessaggiException{
  7390.         deleteMessage(DateManager.getDate());
  7391.     }
  7392.    
  7393.     private void deleteMessage(Date data)throws GestoreMessaggiException{
  7394.         if( (this.openspcoopstate instanceof OpenSPCoopStateful) || (this.oneWayVersione11)) {
  7395.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  7396.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  7397.             Connection connectionDB = stateMSG.getConnectionDB();
  7398.             PreparedStatement pstmtDeleteSIL= null;
  7399.             PreparedStatement pstmtDeleteMSG= null;
  7400.             try{

  7401.                 //this.log.debug("DELETE  ID_MESSAGGIO='"+this.idBusta+"' AND TIPO='"+this.tipo+"'");
  7402.                 java.sql.Timestamp nowT = null;
  7403.                 if(data!=null) {
  7404.                     nowT = new java.sql.Timestamp(data.getTime());
  7405.                 }

  7406.                 // Prima prova ad eliminare eventuali SIL rimasti appesi al messaggio, se il messaggio e' di tipo INBOX
  7407.                 if(Costanti.INBOX.equals(this.tipo)){
  7408.                     String query = "DELETE FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI+" WHERE "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ID_MESSAGGIO+"=?";
  7409.                     if(data!=null) {
  7410.                         query = query + " AND "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ORA_REGISTRAZIONE+"<=?";
  7411.                     }
  7412.                     //log.debug("Query: "+query);
  7413.                     pstmtDeleteSIL= connectionDB.prepareStatement(query);
  7414.                     pstmtDeleteSIL.setString(1,this.idBusta);
  7415.                     if(data!=null) {
  7416.                         pstmtDeleteSIL.setTimestamp(2, nowT);
  7417.                     }
  7418.                     pstmtDeleteSIL.execute();
  7419.                     pstmtDeleteSIL.close();
  7420.                 }

  7421.                 // Prova poi ad eliminare il messaggio su FileSystem/DB
  7422.                 SavedMessage msgDelete = new SavedMessage(this.idBusta, this.openspcoopstate ,this.tipo,this.workDir,GestoreMessaggi.adapter,this.log);
  7423.                 msgDelete.delete(this.isRichiesta,this.oneWayVersione11, nowT);

  7424.                 // Elimino il messaggio
  7425.                 String query = "DELETE FROM "+GestoreMessaggi.MESSAGGI+" WHERE "+GestoreMessaggi.MESSAGGI_COLUMN_ID_MESSAGGIO+"=? AND "+GestoreMessaggi.MESSAGGI_COLUMN_TIPO_MESSAGGIO+"=?";
  7426.                 if(data!=null) {
  7427.                     query = query + " AND "+GestoreMessaggi.MESSAGGI_COLUMN_ORA_REGISTRAZIONE+"<=?";
  7428.                 }
  7429.                 //log.debug("Query: "+query);
  7430.                 pstmtDeleteMSG= connectionDB.prepareStatement(query);
  7431.                 pstmtDeleteMSG.setString(1,this.idBusta);
  7432.                 pstmtDeleteMSG.setString(2,this.tipo);
  7433.                 if(data!=null) {
  7434.                     pstmtDeleteMSG.setTimestamp(3, nowT);
  7435.                 }
  7436.                 pstmtDeleteMSG.execute();
  7437.                 pstmtDeleteMSG.close();

  7438.                 // Elimino dalla cache
  7439.                 GestoreMessaggi.deleteFromCache_Proprietario(TimerGestoreMessaggi.ID_MODULO,this.tipo, this.idBusta);

  7440.             } catch(Exception e) {
  7441.                 String errorMsg = "GESTORE_MESSAGGI, error deleteMessage "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  7442.                 try{
  7443.                     if(pstmtDeleteMSG != null)
  7444.                         pstmtDeleteMSG.close();
  7445.                 } catch(Exception er) {
  7446.                     // close
  7447.                 }
  7448.                 try{
  7449.                     if(pstmtDeleteSIL != null)
  7450.                         pstmtDeleteSIL.close();
  7451.                 } catch(Exception er) {
  7452.                     // close
  7453.                 }
  7454.                 this.log.error(errorMsg,e);
  7455.                 throw new GestoreMessaggiException(errorMsg,e);
  7456.             }  
  7457.         }else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  7458.             //CHECKME NOP
  7459.         }else{
  7460.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  7461.         }

  7462.     }

  7463.     /**
  7464.      * Elimina il messaggio gestito da OpenSPCoop dal fileSystem.
  7465.      *
  7466.      *
  7467.      */
  7468.     public void deleteMessageFromFileSystem(){
  7469.         SavedMessage msgDelete = null;
  7470.         try{
  7471.             //this.log.debug("DELETE FILE SYSTEM ID_MESSAGGIO='"+this.idBusta+"' AND TIPO='"+this.tipo+"'");
  7472.             msgDelete = new SavedMessage(this.idBusta, this.openspcoopstate ,this.tipo,this.workDir,GestoreMessaggi.adapter,this.log);
  7473.             msgDelete.deleteMessageFromFileSystem();
  7474.         }catch(Exception e){
  7475.             String errorMsg = "GESTORE_MESSAGGI, error deleteMessage "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  7476.             this.log.error(errorMsg,e);
  7477.         }
  7478.     }


  7479.     /**
  7480.      * Effettua una validazione sui riscontri del messaggio, e dopodiche' lo elimina.
  7481.      *
  7482.      *
  7483.      */
  7484.     public void validateAndDeleteMsgOneWayRiscontrato() throws GestoreMessaggiException,ProtocolException{

  7485.         StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  7486.                 : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  7487.         // Validazione riscontro
  7488.         Riscontri gestoreRiscontri = null;

  7489.         // Commit JDBC
  7490.         try{
  7491.             gestoreRiscontri = new Riscontri(stateMSG);
  7492.             gestoreRiscontri.validazioneRiscontroRicevuto(this.idBusta);

  7493.             // Aggiorno proprietario
  7494.             this.aggiornaProprietarioMessaggio(TimerGestoreMessaggi.ID_MODULO);

  7495.             this.openspcoopstate.commit();

  7496.         }catch (Exception e) {  
  7497.             String errorMsg = "GESTORE_MESSAGGI, error validateAndDeleteMsgRiscontrato "+this.tipo+"/"+this.idBusta+": "+e.getMessage();        
  7498.             this.log.error(errorMsg,e);
  7499.             throw new GestoreMessaggiException(errorMsg,e);
  7500.         }

  7501.         // Aggiornamento cache proprietario messaggio
  7502.         this.addProprietariIntoCache_readFromTable("GestoreMessaggi", "validateAndDeleteMsgOneWayRiscontrato",null,false);
  7503.     }




  7504.     /**
  7505.      * Effettua una validazione di una ricevuta asincrona, e dopodiche' elimina la richiesta.
  7506.      *
  7507.      * @param bustaRicevuta Busta della ricevuta
  7508.      *
  7509.      */
  7510.     public void validateAndDeleteMsgAsincronoRiscontrato(Busta bustaRicevuta) throws GestoreMessaggiException,ProtocolException{

  7511.         StateMessage state = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  7512.                 : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;

  7513.         // Validazione ricevuta
  7514.         ProfiloDiCollaborazione profiloCollaborazione = null;

  7515.         // Commit JDBC
  7516.         try{
  7517.             profiloCollaborazione = new ProfiloDiCollaborazione(state,this.protocolFactory);
  7518.             profiloCollaborazione.asincrono_valdazioneRicevuta(bustaRicevuta);

  7519.             // Aggiorno proprietario
  7520.             this.aggiornaProprietarioMessaggio(TimerGestoreMessaggi.ID_MODULO);

  7521.             this.openspcoopstate.commit();

  7522.         }catch (Exception e) {  
  7523.             String errorMsg = "GESTORE_MESSAGGI, error validateAndDeleteMsgRiscontrato "+this.tipo+"/"+this.idBusta+": "+e.getMessage();        

  7524.             this.log.error(errorMsg,e);
  7525.             throw new GestoreMessaggiException(errorMsg,e);
  7526.         }

  7527.         // Aggiornamento cache proprietario messaggio
  7528.         this.addProprietariIntoCache_readFromTable("GestoreMessaggi", "validateAndDeleteMsgAsincronoRiscontrato",null,false);

  7529.     }







  7530.     /**
  7531.      * Elimina un messaggio dall'engine di OpenSPCoop.
  7532.      *
  7533.      *
  7534.      */
  7535.     public boolean forcedDeleteMessage(RequestInfo requestInfo) throws GestoreMessaggiException{

  7536.         if(this.openspcoopstate instanceof OpenSPCoopStateful) {
  7537.             StatefulMessage stateful = (this.isRichiesta) ? ((StatefulMessage)this.openspcoopstate.getStatoRichiesta())
  7538.                     : ((StatefulMessage)this.openspcoopstate.getStatoRisposta()) ;

  7539.             RollbackRepositoryBuste rollbackMessaggio = null;
  7540.             RollbackRepositoryBuste rollbackRepository = null;
  7541.             try{    
  7542.                 //this.log.debug("FORCED DELETE  ID_MESSAGGIO='"+this.idBusta+"' AND TIPO='"+this.tipo+"'");

  7543.                 if(this.existsMessage_noCache()==false)
  7544.                     return false;
  7545.                 // Clean Rollback + JMS
  7546.                 String rifMsg = this.getRiferimentoMessaggio();
  7547.                 JMSReceiver receiverJMS = null;
  7548.                 if(CostantiConfigurazione.COMUNICAZIONE_INFRASTRUTTURALE_JMS.equals(this.propertiesReader.getNodeReceiver())){
  7549.                     String idT = PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, this.pddContext);
  7550.                     String protocol = null;
  7551.                     if(this.protocolFactory!=null)
  7552.                         protocol = this.protocolFactory.getProtocol();
  7553.                     receiverJMS = new JMSReceiver(this.propertiesReader.getIdentitaPortaDefault(protocol, requestInfo),"ForcedDeleteMessage",this.propertiesReader.singleConnectionNodeReceiver(),this.log,idT);
  7554.                 }
  7555.                 if(Costanti.INBOX.equals(this.tipo)){
  7556.                     //  rollback messaggio (eventuale profilo + accesso_pdd)
  7557.                     rollbackMessaggio = new RollbackRepositoryBuste(this.idBusta, stateful,this.oneWayVersione11);
  7558.                     rollbackMessaggio.rollbackBustaIntoInBox();
  7559.                     if(rifMsg==null){
  7560.                         if(receiverJMS!=null){
  7561.                             // rollback jms receiver
  7562.                             String strMessageSelector = "ID = '"+this.idBusta+"'";
  7563.                             if (receiverJMS.clean(RicezioneBuste.ID_MODULO,strMessageSelector)){
  7564.                                 this.log.info("Trovato messaggio nella coda "+RicezioneBuste.ID_MODULO+" con id ["+this.idBusta+"] non consumato");
  7565.                             }
  7566.                         }
  7567.                     }else{
  7568.                         // rollback repository
  7569.                         rollbackRepository = new RollbackRepositoryBuste(rifMsg,stateful,this.oneWayVersione11);
  7570.                         rollbackRepository.rollbackBustaIntoOutBox(false); // non effettuo il rollback dell'history (riscontro/ricevuta arrivera...)

  7571.                         if(receiverJMS!=null){
  7572.                             // rollback jms receiver
  7573.                             String strMessageSelector = "ID = '"+rifMsg+"'";
  7574.                             if (receiverJMS.clean(RicezioneContenutiApplicativi.ID_MODULO,strMessageSelector)){
  7575.                                 this.log.info("Trovato messaggio (tramite riferimento) nella coda "+RicezioneContenutiApplicativi.ID_MODULO+" con id ["+rifMsg+"] non consumato");
  7576.                             }
  7577.                         }
  7578.                     }
  7579.                 }else{
  7580.                     // rollback messaggio scaduto (eventuale profilo + accesso_pdd)
  7581.                     rollbackMessaggio = new RollbackRepositoryBuste(this.idBusta, stateful,this.oneWayVersione11);
  7582.                     rollbackMessaggio.rollbackBustaIntoOutBox();
  7583.                     if(rifMsg==null){
  7584.                         if(receiverJMS!=null){
  7585.                             //  rollback jms receiver
  7586.                             String strMessageSelector = "ID = '"+this.idBusta+"'";
  7587.                             if (receiverJMS.clean(RicezioneContenutiApplicativi.ID_MODULO,strMessageSelector)){
  7588.                                 this.log.info("Trovato messaggio nella coda "+RicezioneContenutiApplicativi.ID_MODULO+" con id ["+this.idBusta+"] non consumato");
  7589.                             }
  7590.                         }
  7591.                     }else{
  7592.                         // rollback repository
  7593.                         rollbackRepository = new RollbackRepositoryBuste(rifMsg, stateful,this.oneWayVersione11);
  7594.                         rollbackRepository.rollbackBustaIntoInBox(false); // non effettuo il rollback dell'history (busta e' ricevuta)

  7595.                         if(receiverJMS!=null){
  7596.                             //  rollback jms receiver
  7597.                             String strMessageSelector = "ID = '"+rifMsg+"'";
  7598.                             if (receiverJMS.clean(RicezioneBuste.ID_MODULO,strMessageSelector)){
  7599.                                 this.log.info("Trovato messaggio (tramite riferimento) nella coda "+RicezioneBuste.ID_MODULO+" con id ["+rifMsg+"] non consumato");
  7600.                             }
  7601.                         }
  7602.                     }
  7603.                 }
  7604.                 // Update proprietario messaggio
  7605.                 this.aggiornaProprietarioMessaggio(TimerGestoreMessaggi.ID_MODULO);


  7606.                 // esecuzione forced delete
  7607.                 this.openspcoopstate.commit();

  7608.                 //  Aggiornamento cache proprietario messaggio
  7609.                 this.addProprietariIntoCache_readFromTable("GestoreMessaggi", "forcedDeleteMessage",this.getRiferimentoMessaggio(),false);

  7610.                 return true;

  7611.             } catch(Exception e) {
  7612.                 String errorMsg = "GESTORE_MESSAGGI, Errore forcedDeleteMessage "+this.tipo+"/"+this.idBusta+": "+e.getMessage();      
  7613.                 this.log.error(errorMsg,e);

  7614.                 throw new GestoreMessaggiException(errorMsg,e);
  7615.             }
  7616.         } // else if (this.openspcoopstate instanceof OpenSPCoopStateless){
  7617.         // Stateful only    
  7618.         else{
  7619.             throw new GestoreMessaggiException("Metodo invocato con OpenSPCoopState non valido");
  7620.         }

  7621.     }







  7622.     /**
  7623.      * Costruisce un Messaggio conforme all'interfaccia di pubblicazione del RepositoryMessaggi
  7624.      *
  7625.      *
  7626.      */
  7627.     public OpenSPCoop2Message buildRichiestaPubblicazioneMessaggio_RepositoryMessaggi(IDSoggetto soggettoMittente,String tipoServizio,String servizio,String azione) throws GestoreMessaggiException{

  7628.         try{
  7629.             String msg = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
  7630.                     "<soapenv:Body>\n"+
  7631.                     "<pubblicazioneMessaggio xmlns=\"http://gestoreeventi.openspcoop.org\">" +
  7632.                     "<richiesta xmlns:types=\"http://types.gestoreeventi.openspcoop.org\"><types:idMessaggio>"+this.idBusta+"</types:idMessaggio>"+
  7633.                     "<types:soggetto><types:nome>"+soggettoMittente.getNome()+"</types:nome><types:tipo>"+soggettoMittente.getTipo()+"</types:tipo></types:soggetto>"+
  7634.                     "<types:servizio><types:nome>"+servizio+"</types:nome><types:tipo>"+tipoServizio+"</types:tipo></types:servizio>"+
  7635.                     "<types:tipoEvento>"+azione+"</types:tipoEvento>"+
  7636.                     "</richiesta></pubblicazioneMessaggio>\n"+
  7637.                     "</soapenv:Body>\n"+
  7638.                     "</soapenv:Envelope>";
  7639.             OpenSPCoop2MessageParseResult pr = OpenSPCoop2MessageFactory.getDefaultMessageFactory().createMessage(MessageType.SOAP_11, MessageRole.REQUEST,
  7640.                     MessageUtilities.getDefaultContentType(MessageType.SOAP_11),
  7641.                     msg.getBytes());
  7642.             return pr.getMessage_throwParseException();
  7643.         }catch(Exception e){
  7644.             String errorMsg = "GESTORE_MESSAGGI, error buildRichiestaPubblicazioneMessaggio_RepositoryMessaggi: "+e.getMessage();      
  7645.             this.log.error(errorMsg,e);
  7646.             throw new GestoreMessaggiException(errorMsg,e);
  7647.         }

  7648.     }

  7649.     /**
  7650.      * Costruisce un Messaggio conforme all'interfaccia di prelevamento dal RepositoryMessaggi
  7651.      *
  7652.      *
  7653.      */
  7654.     public OpenSPCoop2Message buildRispostaPrelevamentoMessaggio_RepositoryMessaggi(byte[] messaggio, MessageType messageType) throws GestoreMessaggiException{

  7655.         try{
  7656.             String namespace;
  7657.             if(MessageType.SOAP_11.equals(messageType)){
  7658.                 namespace = "http://schemas.xmlsoap.org/soap/envelope/";
  7659.             } else {
  7660.                 namespace = "http://www.w3.org/2003/05/soap-envelope";
  7661.             }
  7662.             String msgUpper = "<soapenv:Envelope xmlns:soapenv=\"" + namespace + "\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
  7663.                     "<soapenv:Body>\n"+
  7664.                     "<prelevaMessaggioResponse xmlns=\"http://gestoreeventi.openspcoop.org\">"+
  7665.                     "<prelevaMessaggioReturn>";
  7666.             String msgDown ="</prelevaMessaggioReturn></prelevaMessaggioResponse>\n"+
  7667.                     "</soapenv:Body>\n"+
  7668.                     "</soapenv:Envelope>";
  7669.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  7670.             bout.write(msgUpper.getBytes());
  7671.             bout.write(Base64Utilities.encode(messaggio));
  7672.             bout.write(msgDown.getBytes());
  7673.             bout.flush();
  7674.             bout.close();
  7675.             OpenSPCoop2MessageParseResult pr = OpenSPCoop2MessageFactory.getDefaultMessageFactory().createMessage(messageType, MessageRole.RESPONSE,
  7676.                     MessageUtilities.getDefaultContentType(messageType),
  7677.                     bout.toByteArray());
  7678.             return pr.getMessage_throwParseException();
  7679.         }catch(Exception e){
  7680.             String errorMsg = "GESTORE_MESSAGGI, error buildRispostaPrelevamentoMessaggio_RepositoryMessaggi: "+e.getMessage();    
  7681.             this.log.error(errorMsg,e);
  7682.             throw new GestoreMessaggiException(errorMsg,e);
  7683.         }

  7684.     }
  7685.     public void setReadyForDrop(boolean readyForDrop) {
  7686.         this.readyForDrop = readyForDrop;
  7687.     }
  7688.     public void setOneWayVersione11(boolean oneWay11) {
  7689.         this.oneWayVersione11 = oneWay11;
  7690.     }
  7691.     public boolean isOneWayVersione11() {
  7692.         return this.oneWayVersione11;
  7693.     }
  7694.     public void setPortaDiTipoStateless(boolean portaDiTipoStateless) {
  7695.         this.portaDiTipoStateless = portaDiTipoStateless;
  7696.     }
  7697.     public void setRoutingStateless(boolean routingStateless) {
  7698.         this.routingStateless = routingStateless;
  7699.     }
  7700.     public boolean isRichiesta() {
  7701.         return this.isRichiesta;
  7702.     }
  7703.     public void setRichiesta(boolean isRichiesta) {
  7704.         this.isRichiesta = isRichiesta;
  7705.     }


















  7706.     /* ------------- LOCK PER GESTIONE DELETE DI MESSAGGI DUPLICATI IN CONCORRENZA CON L'ELIMINAZIONE DEL TIMER -------------- */
  7707.    
  7708.     private Semaphore getSemaphoreByInstance(String idLock) throws UtilsException {
  7709.         if(this.propertiesReader.isTimerLockByDatabase()) {
  7710.             try{
  7711.                 InfoStatistics semaphore_statistics = new InfoStatistics();
  7712.                        
  7713.                 SemaphoreConfiguration config = newSemaphoreConfiguration(this.propertiesReader.getTimerGestoreMessaggiLockMaxLife(),
  7714.                         this.propertiesReader.getTimerGestoreMessaggiLockIdleTime());
  7715.                
  7716.                 TipiDatabase databaseType = TipiDatabase.toEnumConstant(this.propertiesReader.getDatabaseType());
  7717.                 Semaphore semaphoreDB = new Semaphore(semaphore_statistics, SemaphoreMapping.newInstance(idLock),
  7718.                         config, databaseType, this.log);
  7719.                 return semaphoreDB;
  7720.             }catch(Exception e){
  7721.                 throw new UtilsException(e.getMessage(),e);
  7722.             }
  7723.         }
  7724.         return null;
  7725.     }
  7726.     private Connection getConnectionByInstance() {
  7727.         Connection connectionDB = null;
  7728.         if( (this.openspcoopstate instanceof OpenSPCoopStateful) || (this.oneWayVersione11)) {
  7729.             StateMessage stateMSG = (this.isRichiesta) ? ((StateMessage)this.openspcoopstate.getStatoRichiesta())
  7730.                     : ((StateMessage)this.openspcoopstate.getStatoRisposta()) ;
  7731.             connectionDB = stateMSG.getConnectionDB();
  7732.         }
  7733.         return connectionDB;
  7734.     }
  7735.    
  7736.     public static SemaphoreConfiguration newSemaphoreConfiguration(long maxLife,long idleTime) {
  7737.        
  7738.         OpenSPCoop2Properties propertiesReader = OpenSPCoop2Properties.getInstance();
  7739.         Logger logTimers = OpenSPCoop2Logger.getLoggerOpenSPCoopTimers();
  7740.        
  7741.         SemaphoreConfiguration config = new SemaphoreConfiguration();
  7742.         config.setSerializableTimeWaitMs(propertiesReader.getGestioneSerializableDBAttesaAttiva());
  7743.         config.setSerializableNextIntervalTimeMs(propertiesReader.getGestioneSerializableDBCheckInterval());
  7744.         config.setMaxLife(maxLife);
  7745.         config.setMaxIdleTime(idleTime);
  7746.         boolean logEvent = propertiesReader.isTimerLockByDatabaseNotifyLogEnabled();
  7747.         config.setEmitEvent(logEvent);
  7748.         if(logEvent) {
  7749.             config.setEventGenerator(new SemaphoreLogEventGenerator(logTimers));
  7750.         }
  7751.         config.setIdNode(propertiesReader.getClusterId(true));
  7752.         config.setSerializableLevel(false); // in modo da non avere il lock esclusivo sulla tabella, cmq le entries sono inizializzate
  7753.        
  7754.         return config;
  7755.     }
  7756.    
  7757.     private static StringBuilder LOCK = new StringBuilder();
  7758.     private static String LOCK_MODULO = null;

  7759.     // I Metodi sotto riportati commentati funzionavano bene, ma non garantivano il fair dei lock,
  7760.     // Inoltre alla scadenza del while non veniva lanciata una eccezione che indicava il timeout per l'acquisizione del lock
  7761.     // When fairness is set true, the semaphore guarantees that threads invoking any of the acquire methods are selected to obtain permits in the order in which their invocation of those methods was processed (first-in-first-out; FIFO)
  7762.     // NOTA: La sincronizzazione non servirebbe. Serve solo per avere maggiori informazioni diagnostiche
  7763.    
  7764.     // Con l'introduzione di più nodi il problema descritto più sopra nella sezione 'ELIMINAZIONE MESSAGGI'
  7765.     // si poteva ripresentare distribuito su più nodi. Per questo motivo l'implementazione del lock è stata distribuita grazie al semaforo implementato su database.
  7766.     // Tale semaforo e' stato poi implementato anche per gli altri timer che pero' non necessitano di una semaforizzazione nel caso non esistano piu' di una istanza di PdD
  7767.     // Questo comporta che la gestione tramite synchronized con lock viene attuata solamente per il timer di eliminazione messaggi che presentava tale problematica.
  7768.    
  7769.     private static final int LOCK_NUMBER_OF_PERMITS = 1;
  7770.     private static final boolean LOCK_FAIR_FIFO = true;
  7771.     private static java.util.concurrent.Semaphore LOCK_SEMAPHORE = new java.util.concurrent.Semaphore(LOCK_NUMBER_OF_PERMITS, LOCK_FAIR_FIFO);
  7772.     public static void acquireLock(GestoreMessaggi gestoreMessaggi, TimerLock timerLock,
  7773.             MsgDiagnostico msgDiag,String causa,long attesaAttivaLock,int checkIntervalLock) throws UtilsException, TimerLockNotAvailableException{
  7774.         acquireLock(gestoreMessaggi.getSemaphoreByInstance(timerLock.getIdLock()), gestoreMessaggi.getConnectionByInstance(), timerLock,
  7775.                 msgDiag, causa, attesaAttivaLock, checkIntervalLock);
  7776.     }
  7777.     public static void acquireLock(Semaphore semaphoreDB, Connection connectionDB, TimerLock timerLock,
  7778.             MsgDiagnostico msgDiag,String causa,long attesaAttivaLock,int checkIntervalLock) throws UtilsException, TimerLockNotAvailableException{

  7779.         msgDiag.addKeyword(CostantiPdD.KEY_LOCK_CAUSALE, causa);
  7780.         msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneLock.inCorso");

  7781.         if(semaphoreDB!=null) {
  7782.            
  7783.             if(connectionDB==null) {
  7784.                 throw new UtilsException("Gestione Lock su db richiede una connessione");
  7785.             }
  7786.             try {
  7787.                 if(connectionDB.isClosed()) {
  7788.                     throw new UtilsException("Gestione Lock su db richiede una connessione attiva");
  7789.                 }
  7790.             }catch(Exception e) {
  7791.                 throw new UtilsException("Gestione Lock su db richiede una connessione attiva: "+e.getMessage(),e);
  7792.             }
  7793.            
  7794.             // La sleep ci vuole anche prima del primo lock, senno il timer che prende un lock continuera' a prenderlo.
  7795.             Utilities.sleep(checkIntervalLock);
  7796.            
  7797.             boolean lock = semaphoreDB.newLock(connectionDB, causa);
  7798.             int i=0;
  7799.             while(i<attesaAttivaLock && !lock){
  7800.                 Utilities.sleep(checkIntervalLock);
  7801.                 i=i+checkIntervalLock;
  7802.                 lock = semaphoreDB.newLock(connectionDB, causa);
  7803.             }
  7804.             if(!lock) {
  7805.                 String error = "Timeout: lock non disponibile dopo una attesa di "+attesaAttivaLock+"ms";
  7806.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, error);
  7807.                 msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneLock.nonDisponibile");
  7808.                 throw new TimerLockNotAvailableException(error);
  7809.             }

  7810.         }
  7811.         else {
  7812.        
  7813.             if(TipoLock._getLockGestioneRepositoryMessaggi().equals(timerLock.getTipoLock())) {
  7814.            
  7815.                 synchronized (GestoreMessaggi.LOCK) {
  7816.        
  7817.                     // NOTA: puo' comunque succedere che un proprietario non esista, quindi non viene stampato il log con proprietario, pero' due thread in parallelo poi
  7818.                     //       chiamano il tryAcquire e quindi solo uno dei due lo prende. L'altro rimane bloccato senza aver emesso il log con precedente proprietario.          
  7819.                     if(GestoreMessaggi.LOCK.length()>0){
  7820.                         msgDiag.addKeyword(CostantiPdD.KEY_LOCK_CAUSALE, GestoreMessaggi.LOCK.toString());
  7821.                         msgDiag.addKeyword(CostantiPdD.KEY_LOCK_ID_MODULO, GestoreMessaggi.LOCK_MODULO);
  7822.                         msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneLock.wait.existsOldOwner");
  7823.                     }
  7824.                     else{
  7825.                         msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneLock.wait.withoutOwner");
  7826.                     }
  7827.        
  7828.                 }
  7829.        
  7830.                 /*
  7831.                  *  Acquires a permit from this semaphore, if one becomes available within the given waiting time and the current thread has not been interrupted.
  7832.                     Acquires a permit, if one is available and returns immediately/
  7833.        
  7834.                     If no permit is available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:
  7835.                     - Some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit; or
  7836.                     - Some other thread interrupts the current thread; or
  7837.                     - The specified waiting time elapses.
  7838.        
  7839.                     If a permit is acquired then the value true is returned.
  7840.        
  7841.                     If the current thread:
  7842.                     - has its interrupted status set on entry to this method; or
  7843.                     - is interrupted while waiting to acquire a permit,
  7844.                     then InterruptedException is thrown and the current thread's interrupted status is cleared.
  7845.        
  7846.                     If the specified waiting time elapses then the value false is returned. If the time is less than or equal to zero, the method will not wait at all.
  7847.                  */
  7848.                 boolean lockAcquired = false;
  7849.                 try {
  7850.                     lockAcquired = LOCK_SEMAPHORE.tryAcquire(attesaAttivaLock, TimeUnit.MILLISECONDS);
  7851.                 }catch(InterruptedException ie) {
  7852.                     Thread.currentThread().interrupt();
  7853.                     throw new UtilsException("Timeout: lock non disponibile dopo una attesa di "+attesaAttivaLock+"ms (attuale modulo proprietario: "+GestoreMessaggi.LOCK_MODULO+", causa: "+GestoreMessaggi.LOCK.toString()+"): "+ie.getMessage(),ie);
  7854.                 }
  7855.                 if(lockAcquired==false){
  7856.                     throw new UtilsException("Timeout: lock non disponibile dopo una attesa di "+attesaAttivaLock+"ms (attuale modulo proprietario: "+GestoreMessaggi.LOCK_MODULO+", causa: "+GestoreMessaggi.LOCK.toString()+")");
  7857.                 }
  7858.        
  7859.                 GestoreMessaggi.LOCK.append(causa);
  7860.                 GestoreMessaggi.LOCK_MODULO = msgDiag.getFunzione();
  7861.                
  7862.             }
  7863.            
  7864.         }

  7865.         msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneLock.ok");

  7866.     }

  7867.     public static void updateLock(GestoreMessaggi gestoreMessaggi, TimerLock timerLock,
  7868.             MsgDiagnostico msgDiag,String causa) throws UtilsException{
  7869.         updateLock(gestoreMessaggi.getSemaphoreByInstance(timerLock.getIdLock()), gestoreMessaggi.getConnectionByInstance(), timerLock, msgDiag, causa);
  7870.     }
  7871.     public static void updateLock(Semaphore semaphoreDB,  Connection connectionDB, TimerLock timerLock,
  7872.             MsgDiagnostico msgDiag,String causa) throws UtilsException{
  7873.        
  7874.         msgDiag.addKeyword(CostantiPdD.KEY_LOCK_CAUSALE, causa);
  7875.         msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "updateLock.inCorso");

  7876.         if(semaphoreDB!=null) {
  7877.            
  7878.             if(connectionDB==null) {
  7879.                 throw new UtilsException("Gestione Lock su db richiede una connessione");
  7880.             }
  7881.             try {
  7882.                 if(connectionDB.isClosed()) {
  7883.                     throw new UtilsException("Gestione Lock su db richiede una connessione attiva");
  7884.                 }
  7885.             }catch(Exception e) {
  7886.                 throw new UtilsException("Gestione Lock su db richiede una connessione attiva: "+e.getMessage(),e);
  7887.             }
  7888.            
  7889.             boolean unlock = semaphoreDB.updateLock(connectionDB, causa);
  7890.             if(!unlock) {
  7891.                 msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "updateLock.ko");
  7892.                 throw new UtilsException(msgDiag.getMessaggio_replaceKeywords("all", "updateLock.ko"));
  7893.             }
  7894.         }
  7895.         else {
  7896.        
  7897.             // nop
  7898.             //aggiornamento non previsto con implementazione singleton
  7899.            
  7900.         }
  7901.         msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "updateLock.ok");
  7902.        
  7903.     }
  7904.    
  7905.     public static void releaseSafeLock(GestoreMessaggi gestoreMessaggi, TimerLock timerLock,
  7906.             MsgDiagnostico msgDiag,String causa) throws UtilsException{
  7907.         releaseSafeLock(gestoreMessaggi.getSemaphoreByInstance(timerLock.getIdLock()), gestoreMessaggi.getConnectionByInstance(), timerLock, msgDiag, causa);
  7908.     }
  7909.     public static void releaseSafeLock(Semaphore semaphoreDB,  Connection connectionDB, TimerLock timerLock,
  7910.             MsgDiagnostico msgDiag,String causa) throws UtilsException{
  7911.         try{
  7912.             releaseLock(
  7913.                     semaphoreDB, connectionDB, timerLock,
  7914.                     msgDiag, causa);
  7915.         }catch(Exception e){
  7916.             // ignore
  7917.         }
  7918.     }
  7919.    
  7920.     public static void releaseLock(GestoreMessaggi gestoreMessaggi, TimerLock timerLock,
  7921.             MsgDiagnostico msgDiag,String causa) throws UtilsException{
  7922.         releaseLock(gestoreMessaggi.getSemaphoreByInstance(timerLock.getIdLock()), gestoreMessaggi.getConnectionByInstance(), timerLock, msgDiag, causa);
  7923.     }
  7924.     public static void releaseLock(Semaphore semaphoreDB,  Connection connectionDB, TimerLock timerLock,
  7925.             MsgDiagnostico msgDiag,String causa) throws UtilsException{

  7926.         msgDiag.addKeyword(CostantiPdD.KEY_LOCK_CAUSALE, causa);
  7927.         msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneUnlock.inCorso");

  7928.         if(semaphoreDB!=null) {
  7929.            
  7930.             if(connectionDB==null) {
  7931.                 throw new UtilsException("Gestione Lock su db richiede una connessione");
  7932.             }
  7933.             try {
  7934.                 if(connectionDB.isClosed()) {
  7935.                     throw new UtilsException("Gestione Lock su db richiede una connessione attiva");
  7936.                 }
  7937.             }catch(Exception e) {
  7938.                 throw new UtilsException("Gestione Lock su db richiede una connessione attiva: "+e.getMessage(),e);
  7939.             }
  7940.            
  7941.             boolean unlock = semaphoreDB.releaseLock(connectionDB, causa);
  7942.             if(!unlock) {
  7943.                 msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneUnlock.ko");
  7944.                 throw new UtilsException(msgDiag.getMessaggio_replaceKeywords("all", "acquisizioneUnlock.ko"));
  7945.             }
  7946.         }
  7947.         else {
  7948.        
  7949.             if(TipoLock._getLockGestioneRepositoryMessaggi().equals(timerLock.getTipoLock())) {
  7950.            
  7951.                 // Esiste solo un thread attivo, grazie al semaforo
  7952.                 // metto il synchronized per garantire il log consistente sopra
  7953.                
  7954.                 if( ! (GestoreMessaggi.LOCK.length()>0) ){
  7955.                     msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneUnlock.ko");
  7956.                     throw new UtilsException(msgDiag.getMessaggio_replaceKeywords("all", "acquisizioneUnlock.ko"));
  7957.                 }
  7958.        
  7959.                 synchronized (GestoreMessaggi.LOCK) {  
  7960.                     GestoreMessaggi.LOCK.delete(0, GestoreMessaggi.LOCK.length());
  7961.                     GestoreMessaggi.LOCK_MODULO = null;
  7962.                 }
  7963.                 LOCK_SEMAPHORE.release();
  7964.                
  7965.             }
  7966.            
  7967.         }
  7968.         msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_ALL, "acquisizioneUnlock.ok");

  7969.     }

  7970. }