RepositoryBuste.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.protocol.engine.driver;


  21. import java.sql.Connection;
  22. import java.sql.PreparedStatement;
  23. import java.sql.ResultSet;
  24. import java.sql.Timestamp;
  25. import java.util.ArrayList;
  26. import java.util.Date;
  27. import java.util.List;
  28. import java.util.Map;

  29. import org.openspcoop2.core.commons.DBUtils;
  30. import org.openspcoop2.core.id.IDServizio;
  31. import org.openspcoop2.core.id.IDSoggetto;
  32. import org.openspcoop2.protocol.engine.Configurazione;
  33. import org.openspcoop2.protocol.engine.LetturaParametriBusta;
  34. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  35. import org.openspcoop2.protocol.engine.constants.Costanti;
  36. import org.openspcoop2.protocol.engine.driver.repository.IGestoreRepository;
  37. import org.openspcoop2.protocol.sdk.Busta;
  38. import org.openspcoop2.protocol.sdk.Eccezione;
  39. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  40. import org.openspcoop2.protocol.sdk.Integrazione;
  41. import org.openspcoop2.protocol.sdk.ProtocolException;
  42. import org.openspcoop2.protocol.sdk.Riscontro;
  43. import org.openspcoop2.protocol.sdk.Trasmissione;
  44. import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
  45. import org.openspcoop2.protocol.sdk.constants.ContestoCodificaEccezione;
  46. import org.openspcoop2.protocol.sdk.constants.Inoltro;
  47. import org.openspcoop2.protocol.sdk.constants.LivelloRilevanza;
  48. import org.openspcoop2.protocol.sdk.constants.TipoOraRegistrazione;
  49. import org.openspcoop2.protocol.sdk.state.IState;
  50. import org.openspcoop2.protocol.sdk.state.StateMessage;
  51. import org.openspcoop2.protocol.sdk.state.StatefulMessage;
  52. import org.openspcoop2.protocol.sdk.state.StatelessMessage;
  53. import org.openspcoop2.utils.LoggerWrapperFactory;
  54. import org.openspcoop2.utils.SortedMap;
  55. import org.openspcoop2.utils.date.DateManager;
  56. import org.openspcoop2.utils.date.DateUtils;
  57. import org.openspcoop2.utils.sql.ISQLQueryObject;
  58. import org.openspcoop2.utils.sql.SQLObjectFactory;
  59. import org.slf4j.Logger;


  60. /**
  61.  * Sono inclusi i metodi per la gestione delle buste inviate/ricevute.
  62.  *
  63.  *
  64.  * @author Poli Andrea (apoli@link.it)
  65.  * @author Tronci Fabio (tronci@link.it)
  66.  * @author $Author$
  67.  * @version $Rev$, $Date$
  68.  */

  69. public class RepositoryBuste  {

  70.     /** Logger utilizzato per debug. */
  71.     private Logger log = null;

  72.     /** Se IState e' un'istanza di StatefulMessage possiede una Connessione SQL in autoCommit mode su cui effettuare query
  73.      *  Altrimenti, e' un'istanza di StatelessMessage e nn necessita di connessioni
  74.      * */
  75.     private IState state;

  76.     /** Identifica se questo repository lavora su buste di richiesta o risposta */
  77.     private boolean isRichiesta=true;
  78.    
  79.     public boolean isRichiesta() {
  80.         return this.isRichiesta;
  81.     }
  82.     public void setRichiesta(boolean isRichiesta) {
  83.         this.isRichiesta = isRichiesta;
  84.     }


  85.     /** GestoreRepository */
  86.     private IGestoreRepository gestoreRepositoryBuste;

  87.     private IProtocolFactory<?> protocolFactory;

  88.    
  89.     /* ********  C O S T R U T T O R E  ******** */

  90.     //public RepositoryBuste(IState state){
  91.     //  this(state, Configurazione.getLibraryLog(), true,null);
  92.     //}
  93.     public RepositoryBuste(IState state, boolean isRichiesta,IProtocolFactory<?> protocolFactory){
  94.         this(state, Configurazione.getLibraryLog(), isRichiesta,protocolFactory);
  95.     }
  96.     public RepositoryBuste(IState state, Logger alog,IProtocolFactory<?> protocolFactory){
  97.         this(state, alog, true,protocolFactory);
  98.     }
  99.     public RepositoryBuste(IState state,IProtocolFactory<?> protocolFactory){
  100.         this(state, Configurazione.getLibraryLog(), true,protocolFactory);
  101.     }
  102.     /**
  103.      * Costruttore.
  104.      *
  105.      * @param state Oggetto che rappresenta lo stato di una busta
  106.      *
  107.      */
  108.     public RepositoryBuste(IState state, Logger alog, boolean isRichiesta,IProtocolFactory<?> protocolFactory){
  109.         this.state = state;
  110.         this.gestoreRepositoryBuste = Configurazione.getGestoreRepositoryBuste();
  111.         if(alog!=null){
  112.             this.log = alog;
  113.         }else{
  114.             this.log = LoggerWrapperFactory.getLogger(RepositoryBuste.class.getName());
  115.         }
  116.         this.isRichiesta = isRichiesta;
  117.         this.protocolFactory = protocolFactory;
  118.     }
  119.    
  120.    

  121.     /**
  122.      * Imposta lo stato
  123.      *
  124.      * @param state Stato
  125.      *
  126.      */
  127.     public void updateState(IState state){
  128.         this.state = state;
  129.     }




  130.     /* ********  B U S T E     O U T B O X  ******** */
  131.     /**
  132.      * Metodo che si occupa di registrare una busta in uscita.
  133.      *
  134.      * @param busta Contiene le informazioni su di una busta in uscita (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  135.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  136.      *
  137.      */
  138.     public void registraBustaIntoOutBox(Busta busta,long scadenza) throws ProtocolException{
  139.         registraBusta(busta,Costanti.OUTBOX,null,scadenza);
  140.     }
  141.     /**
  142.      * Metodo che si occupa di registrare una busta in uscita con errori.
  143.      *
  144.      * @param busta Contiene le informazioni su di una busta in uscita (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  145.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  146.      * @param errors un oggetto List&lt;{@link org.openspcoop2.protocol.sdk.Eccezione}&gt; se contenente errori di validazione.
  147.      *
  148.      */
  149.     public void registraBustaIntoOutBox(Busta busta,List<Eccezione> errors,long scadenza) throws ProtocolException{
  150.         registraBusta(busta,Costanti.OUTBOX,errors,scadenza);
  151.     }
  152.     /**
  153.      * Metodo che si occupa di registrare una busta in uscita.
  154.      *
  155.      * @param id Identificativo della Richiesta
  156.      * @param soggettoFruitore Soggetto fruitore
  157.      * @param servizio Servizio invocato
  158.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  159.      *
  160.      */
  161.     public void registraBustaIntoOutBox(String id,IDSoggetto soggettoFruitore,IDServizio servizio,long scadenza,
  162.             org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione profiloCollaborazione,boolean confermaRicezione, Inoltro inoltro) throws ProtocolException{
  163.         Busta busta = new Busta(this.protocolFactory.getProtocol());
  164.         busta.setID(id);
  165.         busta.setTipoMittente(soggettoFruitore.getTipo());
  166.         busta.setMittente(soggettoFruitore.getNome());
  167.         busta.setIdentificativoPortaMittente(soggettoFruitore.getCodicePorta());
  168.         busta.setTipoDestinatario(servizio.getSoggettoErogatore().getTipo());
  169.         busta.setDestinatario(servizio.getSoggettoErogatore().getNome());
  170.         busta.setIdentificativoPortaDestinatario(servizio.getSoggettoErogatore().getCodicePorta());
  171.         busta.setTipoServizio(servizio.getTipo());
  172.         busta.setServizio(servizio.getNome());
  173.         busta.setVersioneServizio(servizio.getVersione());
  174.         busta.setAzione(servizio.getAzione());
  175.         busta.setProfiloDiCollaborazione(profiloCollaborazione);
  176.         busta.setConfermaRicezione(confermaRicezione);
  177.         busta.setInoltro(inoltro,this.protocolFactory.createTraduttore().toString(inoltro));
  178.         registraBusta(busta,Costanti.OUTBOX,null,scadenza);
  179.     }

  180.     public void aggiornaProprietaBustaIntoOutBox(Map<String, String> properties, String idBusta)throws ProtocolException{
  181.         this.aggiornaProprietaBusta(properties, idBusta, Costanti.OUTBOX);
  182.     }
  183.    
  184.     /**
  185.      * Aggiorna l'informazione di duplicati della busta.
  186.      *
  187.      * @param id identificativo della busta da ritornare.
  188.      *
  189.      */
  190.     public void aggiornaDuplicatiIntoOutBox(String id)throws ProtocolException{
  191.         this.aggiornaDuplicati(id, Costanti.OUTBOX);
  192.     }

  193.     /**
  194.      * Aggiorna le informazioni di integrazione della busta in uscita.
  195.      *
  196.      * @param id identificativo della busta da ritornare.
  197.      * @param infoIntegrazione Informazioni di integrazione
  198.      *
  199.      */
  200.     public void aggiornaInfoIntegrazioneIntoOutBox(String id,Integrazione infoIntegrazione)throws ProtocolException{
  201.         aggiornaInfoIntegrazione(id,Costanti.OUTBOX,infoIntegrazione);
  202.     }

  203.     /**
  204.      * Aggiorna il servizio applicativo di integrazione nel repositoryBuste della busta in uscita.
  205.      *
  206.      * @param id identificativo della busta da ritornare.
  207.      * @param servizioApplicativo Servizio Applicativo
  208.      *
  209.      */
  210.     public void aggiornaInfoIntegrazioneIntoOutBox_ServizioApplicativo(String id,String servizioApplicativo)throws ProtocolException{
  211.         aggiornaInfoIntegrazione_ServizioApplicativo(id,Costanti.OUTBOX,servizioApplicativo);
  212.     }

  213.     /**
  214.      * Aggiorna lo scenario di integrazione del Msg gestito da OpenSPCoop della busta in uscita.
  215.      *
  216.      * @param id identificativo della busta da ritornare.
  217.      * @param scenario Scenario di integrazione
  218.      *
  219.      */
  220.     public void aggiornaInfoIntegrazioneIntoOutBox_Scenario(String id,String scenario)throws ProtocolException{
  221.         aggiornaInfoIntegrazione_Scenario(id,Costanti.OUTBOX,scenario);
  222.     }

  223.     /**
  224.      * Metodo che si occupa di aggiornare i dati di una busta in uscita precedentemente inviata.
  225.      *
  226.      * @param busta Contiene le informazioni su di una busta in uscita (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  227.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  228.      *
  229.      */
  230.     public void aggiornaBustaIntoOutBox(Busta busta,long scadenza) throws ProtocolException{
  231.         aggiornaBusta(busta,Costanti.OUTBOX,scadenza,null);
  232.     }
  233.     /**
  234.      * Metodo che si occupa di aggiornare i dati di una busta in uscita precedentemente inviata.
  235.      *
  236.      * @param busta Contiene le informazioni su di una busta in entrata (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  237.      * @param errors un oggetto List&lt;{@link org.openspcoop2.protocol.sdk.Eccezione}&gt; se contenente errori di validazione.
  238.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  239.      *
  240.      */
  241.     public void aggiornaBustaIntoOutBox(Busta busta,long scadenza,List<Eccezione> errors) throws ProtocolException{
  242.         aggiornaBusta(busta,Costanti.OUTBOX,scadenza,errors);
  243.     }

  244.     /**
  245.      * Metodo che si occupa di aggiornare una busta in uscita.
  246.      *
  247.      * @param id Identificativo della Richiesta
  248.      * @param soggettoFruitore Soggetto fruitore
  249.      * @param servizio Servizio invocato
  250.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  251.      *
  252.      */
  253.     public void aggiornaBustaIntoOutBox(String id,IDSoggetto soggettoFruitore,IDServizio servizio,long scadenza,
  254.             org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione profiloCollaborazione,boolean confermaRicezione,Inoltro inoltro) throws ProtocolException{
  255.         Busta bustaDaAggiornare = new Busta(this.protocolFactory.getProtocol());
  256.         bustaDaAggiornare.setID(id);
  257.         bustaDaAggiornare.setTipoMittente(soggettoFruitore.getTipo());
  258.         bustaDaAggiornare.setMittente(soggettoFruitore.getNome());
  259.         bustaDaAggiornare.setIdentificativoPortaMittente(soggettoFruitore.getCodicePorta());
  260.         bustaDaAggiornare.setTipoDestinatario(servizio.getSoggettoErogatore().getTipo());
  261.         bustaDaAggiornare.setDestinatario(servizio.getSoggettoErogatore().getNome());
  262.         bustaDaAggiornare.setIdentificativoPortaDestinatario(servizio.getSoggettoErogatore().getCodicePorta());
  263.         bustaDaAggiornare.setTipoServizio(servizio.getTipo());
  264.         bustaDaAggiornare.setServizio(servizio.getNome());
  265.         bustaDaAggiornare.setVersioneServizio(servizio.getVersione());
  266.         bustaDaAggiornare.setAzione(servizio.getAzione());
  267.         bustaDaAggiornare.setProfiloDiCollaborazione(profiloCollaborazione);
  268.         bustaDaAggiornare.setConfermaRicezione(confermaRicezione);
  269.         bustaDaAggiornare.setInoltro(inoltro,this.protocolFactory.createTraduttore().toString(inoltro));
  270.         aggiornaBusta(bustaDaAggiornare,Costanti.OUTBOX, scadenza, null);
  271.     }

  272.     /**
  273.      * Metodo che si occupa di aggiornare la collaborazione di una busta.
  274.      *
  275.      * @param id  Identificativo di una busta
  276.      * @param collaborazione ID di Collaborazione di una busta
  277.      *
  278.      */
  279.     public void aggiornaCollaborazioneIntoOutBox(String id,String collaborazione) throws ProtocolException{
  280.         aggiornaCollaborazione(id,Costanti.OUTBOX,collaborazione);
  281.     }

  282.     /**
  283.      * Metodo che si occupa di aggiornare il numero di sequenza di una busta in uscita.
  284.      *
  285.      * @param id  Identificativo di una busta
  286.      * @param sequenza Numero di sequenza di una busta
  287.      *
  288.      */
  289.     public void aggiornaSequenzaIntoOutBox(String id,long sequenza) throws ProtocolException{
  290.         aggiornaSequenza(id,Costanti.OUTBOX,sequenza);
  291.     }

  292.     /**
  293.      * Ritorna l'informazione se una busta in uscita e' gia stata precedentemente registrata.
  294.      *
  295.      * @param id identificativo della busta da ritornare.
  296.      * @return true se e' presente la busta richiesta.
  297.      *
  298.      */
  299.     public boolean isRegistrataIntoOutBox(String id) throws ProtocolException{
  300.         return isRegistrata(id,Costanti.OUTBOX);
  301.     }

  302.     /**
  303.      * Metodo che si occupa di ritornare un oggetto {@link org.openspcoop2.protocol.sdk.Busta} contenente
  304.      * le informazioni di una busta in uscita, precedentemente salvata,
  305.      * prelevandola dalla tabella delle buste. Alla busta, al momento della registrazione,
  306.      * e' stato associato l'identificativo della busta, quindi attraverso esso sara' possibile trovarlo nella History.
  307.      *
  308.      * @param id identificativo della busta da ritornare.
  309.      * @return un oggetto {@link org.openspcoop2.protocol.sdk.Busta} se e' presente la busta richiesta.
  310.      *
  311.      */
  312.     public Busta getBustaFromOutBox(String id) throws ProtocolException{
  313.         return getBusta(id,Costanti.OUTBOX);
  314.     }

  315.     /**
  316.      * Metodo che si occupa di ritornare un oggetto contenente errori di validazione
  317.      * {@link org.openspcoop2.protocol.sdk.Eccezione} avvenuti durante la validazione di una busta.
  318.      *
  319.      * @param id identificativo della busta da ritornare.
  320.      * @return un oggetto List&lt;{@link org.openspcoop2.protocol.sdk.Eccezione}&gt; se e' presente la busta richiesta.
  321.      *
  322.      */
  323.     public List<Eccezione> getErrorsFromOutBox(String id, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  324.         return getErrors(id, Costanti.OUTBOX);
  325.     }

  326.     /**
  327.      * Ritorna alcuni campi associata alla busta.
  328.      *
  329.      * @param id identificativo della busta.
  330.      * @param parametri Indicazione sul tipo di busta inviata/ricevuta
  331.      * @return alcuni valori della busta
  332.      *
  333.      */
  334.     public Busta getSomeValuesFromOutBox(String id,LetturaParametriBusta parametri) throws ProtocolException{
  335.         return getSomeValues(id, Costanti.OUTBOX, parametri, false, null);
  336.     }
  337.     public Busta getSomeValuesFromOutBox(String id,LetturaParametriBusta parametri,boolean forzaLetturaDatabase) throws ProtocolException{
  338.         return getSomeValues(id, Costanti.OUTBOX, parametri, forzaLetturaDatabase, null);
  339.     }
  340.     public Busta getSomeValuesFromOutBox(String id,LetturaParametriBusta parametri, Date dataRegistrazione) throws ProtocolException{
  341.         return getSomeValues(id, Costanti.OUTBOX, parametri, false, dataRegistrazione);
  342.     }
  343.     public Busta getSomeValuesFromOutBox(String id,LetturaParametriBusta parametri,boolean forzaLetturaDatabase, Date dataRegistrazione) throws ProtocolException{
  344.         return getSomeValues(id, Costanti.OUTBOX, parametri, forzaLetturaDatabase, dataRegistrazione);
  345.     }

  346.     /**
  347.      * Ritorna la collaborazione associata alla busta.
  348.      *
  349.      * @param id identificativo della busta.
  350.      * @return Collaborazione associata alla busta
  351.      *
  352.      */
  353.     public String getCollaborazioneFromOutBox(String id) throws ProtocolException{
  354.         return getCollaborazione(id,Costanti.OUTBOX);
  355.     }

  356.     /**
  357.      * Ritorna il profilo di collaborazione associata alla busta.
  358.      *
  359.      * @param id identificativo della busta.
  360.      * @return Collaborazione associata alla busta
  361.      *
  362.      */
  363.     public org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione getProfiloCollaborazioneFromOutBox(String id) throws ProtocolException{
  364.         return getProfiloCollaborazione(id,Costanti.OUTBOX);
  365.     }
  366.    
  367.     public String getProfiloCollaborazioneValueFromOutBox(String id) throws ProtocolException{
  368.         return getProfiloCollaborazioneValue(id,Costanti.OUTBOX);
  369.     }

  370.     /**
  371.      * Ritorna la sequenza associata alla busta in uscita.
  372.      *
  373.      * @param id identificativo della busta.
  374.      * @return Sequenza associata alla busta
  375.      *
  376.      */
  377.     public long getSequenzaFromOutBox(String id) throws ProtocolException{
  378.         return getSequenza(id,Costanti.OUTBOX);
  379.     }

  380.     /**
  381.      * Ritorna le informazioni di integrazione associate alla busta in uscita.
  382.      *
  383.      * @param id identificativo della busta.
  384.      * @return Informazioni di integrazione associate alla busta
  385.      *
  386.      */
  387.     public Integrazione getInfoIntegrazioneFromOutBox(String id) throws ProtocolException{
  388.         return getInfoIntegrazione(id,Costanti.OUTBOX);
  389.     }

  390.     /**
  391.      * Metodo che si occupa di eliminare l'indicazione di utilizzo della busta dalla PdD
  392.      *
  393.      * @param id identificativo della busta.
  394.      *
  395.      */
  396.     public void eliminaUtilizzoPdDFromOutBox(String id) throws ProtocolException{
  397.         this.eliminaUtilizzoPdD(id,Costanti.OUTBOX,false, null);
  398.     }
  399.     public void eliminaUtilizzoPdDFromOutBox(String id,boolean forzaUpdateDB) throws ProtocolException{
  400.         eliminaUtilizzoPdD(id,Costanti.OUTBOX,forzaUpdateDB, null);
  401.     }
  402.     public void eliminaUtilizzoPdDFromOutBox(String id,boolean forzaUpdateDB,boolean savePreparedStatement) throws ProtocolException{
  403.         eliminaUtilizzoPdD(id,Costanti.OUTBOX,forzaUpdateDB,savePreparedStatement, null);
  404.     }
  405.     public void eliminaUtilizzoPdDFromOutBox(String id, Date dataRegistrazione) throws ProtocolException{
  406.         this.eliminaUtilizzoPdD(id,Costanti.OUTBOX,false, dataRegistrazione);
  407.     }
  408.     public void eliminaUtilizzoPdDFromOutBox(String id,boolean forzaUpdateDB, Date dataRegistrazione) throws ProtocolException{
  409.         eliminaUtilizzoPdD(id,Costanti.OUTBOX,forzaUpdateDB, dataRegistrazione);
  410.     }
  411.     public void eliminaUtilizzoPdDFromOutBox(String id,boolean forzaUpdateDB,boolean savePreparedStatement, Date dataRegistrazione) throws ProtocolException{
  412.         eliminaUtilizzoPdD(id,Costanti.OUTBOX,forzaUpdateDB,savePreparedStatement, dataRegistrazione);
  413.     }
  414.     /**
  415.      * Metodo che si occupa di eliminare una busta precedentemente salvata.
  416.      * Alla busta, al momento della registrazione,
  417.      * e' stato associato l'identificativo della busta, quindi attraverso esso sara' possibile trovarlo nella History.
  418.      *
  419.      * @param id identificativo della busta.
  420.      *
  421.      */
  422.     public void eliminaBustaFromOutBox(String id, Date data) throws ProtocolException{
  423.         eliminaBusta(id,Costanti.OUTBOX, data);
  424.     }

  425.     public void eliminaBustaStatelessFromOutBox(String id) throws ProtocolException{
  426.         eliminaBustaStateless(id,Costanti.OUTBOX, null);
  427.     }
  428.     public void eliminaBustaStatelessFromOutBox(String id, Date dataRegistrazione) throws ProtocolException{
  429.         eliminaBustaStateless(id,Costanti.OUTBOX, dataRegistrazione);
  430.     }

  431.     /**
  432.      * Metodo che si occupa di impostare l'indicazione di utilizzo della busta da parte della PdD
  433.      *
  434.      * @param id identificativo della busta.
  435.      *
  436.      */
  437.     public void impostaUtilizzoPdDIntoOutBox(String id) throws ProtocolException{
  438.         impostaUtilizzoPdD(id,Costanti.OUTBOX);
  439.     }
  440.    
  441.    






  442.     /* ********  B U S T E     R I C E V U T E  ******** */
  443.     /**
  444.      * Metodo che si occupa di registrare una busta in entrata.
  445.      *
  446.      * @param busta Contiene le informazioni su di una busta in entrata (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  447.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  448.      *
  449.      */
  450.     public void registraBustaIntoInBox(Busta busta,long scadenza) throws ProtocolException{
  451.         registraBusta(busta,Costanti.INBOX,null,scadenza);
  452.     }
  453.     public void registraBustaIntoInBox(Busta busta,long scadenza, boolean saveServizioApplicativoFruitore) throws ProtocolException{
  454.         registraBusta(busta,Costanti.INBOX,null,scadenza, saveServizioApplicativoFruitore);
  455.     }
  456.     /**
  457.      * Metodo che si occupa di registrare una busta in uscita con errori.
  458.      *
  459.      * @param busta Contiene le informazioni su di una busta in uscita (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  460.      * @param errors un oggetto List&lt;{@link org.openspcoop2.protocol.sdk.Eccezione}&gt; se contenente errori di validazione.
  461.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  462.      *
  463.      */
  464.     public void registraBustaIntoInBox(Busta busta,List<Eccezione> errors,long scadenza) throws ProtocolException{
  465.         registraBusta(busta,Costanti.INBOX,errors,scadenza);
  466.     }
  467.     /**
  468.      * Metodo che si occupa di registrare una busta in entrata.
  469.      *
  470.      * @param id Identificativo della Richiesta
  471.      * @param soggettoFruitore Soggetto fruitore
  472.      * @param servizio Servizio invocato
  473.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  474.      *
  475.      */
  476.     public void registraBustaIntoInBox(String id,IDSoggetto soggettoFruitore,IDServizio servizio,long scadenza,
  477.             org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione profiloCollaborazione,boolean confermaRicezione,Inoltro inoltro) throws ProtocolException{
  478.         Busta busta = new Busta(this.protocolFactory.getProtocol());
  479.         busta.setID(id);
  480.         busta.setTipoMittente(soggettoFruitore.getTipo());
  481.         busta.setMittente(soggettoFruitore.getNome());
  482.         busta.setIdentificativoPortaMittente(soggettoFruitore.getCodicePorta());
  483.         busta.setTipoDestinatario(servizio.getSoggettoErogatore().getTipo());
  484.         busta.setDestinatario(servizio.getSoggettoErogatore().getNome());
  485.         busta.setIdentificativoPortaDestinatario(servizio.getSoggettoErogatore().getCodicePorta());
  486.         busta.setTipoServizio(servizio.getTipo());
  487.         busta.setServizio(servizio.getNome());
  488.         busta.setVersioneServizio(servizio.getVersione());
  489.         busta.setAzione(servizio.getAzione());
  490.         busta.setProfiloDiCollaborazione(profiloCollaborazione);
  491.         busta.setConfermaRicezione(confermaRicezione);
  492.         busta.setInoltro(inoltro,this.protocolFactory.createTraduttore().toString(inoltro));
  493.         registraBusta(busta,Costanti.INBOX,null,scadenza);
  494.     }

  495.     public void aggiornaProprietaBustaIntoInBox(Map<String, String> properties, String idBusta)throws ProtocolException{
  496.         this.aggiornaProprietaBusta(properties, idBusta, Costanti.INBOX);
  497.     }
  498.    
  499.     /**
  500.      * Aggiorna l'informazione di duplicati della busta.
  501.      *
  502.      * @param id identificativo della busta da ritornare.
  503.      *
  504.      */
  505.     public void aggiornaDuplicatiIntoInBox(String id)throws ProtocolException{
  506.         this.aggiornaDuplicati(id, Costanti.INBOX);
  507.     }

  508.     /**
  509.      * Aggiorna le informazioni di integrazione della busta in entrata.
  510.      *
  511.      * @param id identificativo della busta da ritornare.
  512.      * @param infoIntegrazione Informazioni di integrazione
  513.      *
  514.      */
  515.     public void aggiornaInfoIntegrazioneIntoInBox(String id,Integrazione infoIntegrazione)throws ProtocolException{
  516.         aggiornaInfoIntegrazione(id,Costanti.INBOX,infoIntegrazione);
  517.     }

  518.     /**
  519.      * Aggiorna il servizio applicativo di integrazione nel repositoryBuste della busta in entrata.
  520.      *
  521.      * @param id identificativo della busta da ritornare.
  522.      * @param servizioApplicativo Servizio Applicativo
  523.      *
  524.      */
  525.     public void aggiornaInfoIntegrazioneIntoInBox_ServizioApplicativo(String id,String servizioApplicativo)throws ProtocolException{
  526.         aggiornaInfoIntegrazione_ServizioApplicativo(id,Costanti.INBOX,servizioApplicativo);
  527.     }

  528.     /**
  529.      * Aggiorna lo scenario di integrazione del Msg gestito da OpenSPCoop della busta in entrata.
  530.      *
  531.      * @param id identificativo della busta da ritornare.
  532.      * @param scenario Scenario di integrazione
  533.      *
  534.      */
  535.     public void aggiornaInfoIntegrazioneIntoInBox_Scenario(String id,String scenario)throws ProtocolException{
  536.         aggiornaInfoIntegrazione_Scenario(id,Costanti.INBOX,scenario);
  537.     }

  538.     /**
  539.      * Metodo che si occupa di aggiornare i dati di una busta in entrata precedentemente inviata.
  540.      *
  541.      * @param busta Contiene le informazioni su di una busta in entrata (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  542.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  543.      *
  544.      */
  545.     public void aggiornaBustaIntoInBox(Busta busta,long scadenza) throws ProtocolException{
  546.         aggiornaBusta(busta,Costanti.INBOX,scadenza,null);
  547.     }
  548.     public void aggiornaBustaIntoInBox(Busta busta,long scadenza, boolean saveServizioApplicativoFruitore) throws ProtocolException{
  549.         aggiornaBusta(busta,Costanti.INBOX,scadenza,null,saveServizioApplicativoFruitore);
  550.     }
  551.     /**
  552.      * Metodo che si occupa di aggiornare i dati di una busta in entrata precedentemente inviata.
  553.      *
  554.      * @param busta Contiene le informazioni su di una busta in entrata (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  555.      * @param errors un oggetto List&lt;{@link org.openspcoop2.protocol.sdk.Eccezione}&gt; se contenente errori di validazione.
  556.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  557.      *
  558.      */
  559.     public void aggiornaBustaIntoInBox(Busta busta,long scadenza,List<Eccezione> errors) throws ProtocolException{
  560.         aggiornaBusta(busta,Costanti.INBOX,scadenza,errors);
  561.     }

  562.     /**
  563.      * Metodo che si occupa di aggiornare una busta in entrata.
  564.      *
  565.      * @param id Identificativo della Richiesta
  566.      * @param soggettoFruitore Soggetto fruitore
  567.      * @param servizio Servizio invocato
  568.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  569.      *
  570.      */
  571.     public void aggiornaBustaIntoInBox(String id,IDSoggetto soggettoFruitore,IDServizio servizio,long scadenza,
  572.             org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione profiloCollaborazione,boolean confermaRicezione,Inoltro inoltro) throws ProtocolException{
  573.         Busta bustaDaAggiornare = new Busta(this.protocolFactory.getProtocol());
  574.         bustaDaAggiornare.setID(id);
  575.         bustaDaAggiornare.setTipoMittente(soggettoFruitore.getTipo());
  576.         bustaDaAggiornare.setMittente(soggettoFruitore.getNome());
  577.         bustaDaAggiornare.setIdentificativoPortaMittente(soggettoFruitore.getCodicePorta());
  578.         bustaDaAggiornare.setTipoDestinatario(servizio.getSoggettoErogatore().getTipo());
  579.         bustaDaAggiornare.setDestinatario(servizio.getSoggettoErogatore().getNome());
  580.         bustaDaAggiornare.setIdentificativoPortaDestinatario(servizio.getSoggettoErogatore().getCodicePorta());
  581.         bustaDaAggiornare.setTipoServizio(servizio.getTipo());
  582.         bustaDaAggiornare.setServizio(servizio.getNome());
  583.         bustaDaAggiornare.setVersioneServizio(servizio.getVersione());
  584.         bustaDaAggiornare.setAzione(servizio.getAzione());
  585.         bustaDaAggiornare.setProfiloDiCollaborazione(profiloCollaborazione);
  586.         bustaDaAggiornare.setConfermaRicezione(confermaRicezione);
  587.         bustaDaAggiornare.setInoltro(inoltro,this.protocolFactory.createTraduttore().toString(inoltro));
  588.         aggiornaBusta(bustaDaAggiornare,Costanti.INBOX, scadenza, null);
  589.     }

  590.     /**
  591.      * Metodo che si occupa di aggiornare la collaborazione di una busta.
  592.      *
  593.      * @param id  Identificativo di una busta
  594.      * @param collaborazione ID di Collaborazione di una busta
  595.      *
  596.      */
  597.     public void aggiornaCollaborazioneIntoInBox(String id,String collaborazione) throws ProtocolException{
  598.         aggiornaCollaborazione(id,Costanti.INBOX,collaborazione);
  599.     }

  600.     /**
  601.      * Metodo che si occupa di aggiornare il numero di sequenza di una busta in entrata.
  602.      *
  603.      * @param id  Identificativo di una busta
  604.      * @param sequenza Numero di sequenza di una busta
  605.      *
  606.      */
  607.     public void aggiornaSequenzaIntoInBox(String id,long sequenza) throws ProtocolException{
  608.         aggiornaSequenza(id,Costanti.INBOX,sequenza);
  609.     }

  610.     /**
  611.      * Ritorna l'informazione se una busta in entrata e' gia stata precedentemente registrata.
  612.      *
  613.      * @param id identificativo della busta da ritornare.
  614.      * @return true se e' presente la busta richiesta.
  615.      *
  616.      */
  617.     public boolean isRegistrataIntoInBox(String id) throws ProtocolException{
  618.         return isRegistrata(id,Costanti.INBOX);
  619.     }

  620.     /**
  621.      * Metodo che si occupa di ritornare un oggetto {@link org.openspcoop2.protocol.sdk.Busta} contenente
  622.      * le informazioni di una busta in entrata, precedentemente salvata,
  623.      * prelevandola dalla tabella delle buste. Alla busta, al momento della registrazione,
  624.      * e' stato associato l'identificativo della busta, quindi attraverso esso sara' possibile trovarlo nella History.
  625.      *
  626.      * @param id identificativo della busta da ritornare.
  627.      * @return un oggetto {@link org.openspcoop2.protocol.sdk.Busta} se e' presente la busta richiesta.
  628.      *
  629.      */
  630.     public Busta getBustaFromInBox(String id) throws ProtocolException{
  631.         return getBusta(id,Costanti.INBOX);
  632.     }
  633.     public Busta getBustaFromInBox(String id, boolean readServizioApplicativoFruitore) throws ProtocolException{
  634.         return getBusta(id,Costanti.INBOX, readServizioApplicativoFruitore);
  635.     }

  636.     /**
  637.      * Metodo che si occupa di ritornare un oggetto contenente errori di validazione
  638.      * {@link org.openspcoop2.protocol.sdk.Eccezione} avvenuti durante la validazione di una busta.
  639.      *
  640.      * @param id identificativo della busta da ritornare.
  641.      * @return un oggetto List&lt;{@link org.openspcoop2.protocol.sdk.Eccezione}&gt; se e' presente la busta richiesta.
  642.      *
  643.      */
  644.     public List<Eccezione> getErrorsFromInBox(String id) throws ProtocolException{
  645.         return getErrors(id,Costanti.INBOX);
  646.     }

  647.     /**
  648.      * Ritorna alcuni campi associata alla busta.
  649.      *
  650.      * @param id identificativo della busta.
  651.      * @param parametri Indicazione sul tipo di busta inviata/ricevuta
  652.      * @return alcuni valori della busta
  653.      *
  654.      */
  655.     public Busta getSomeValuesFromInBox(String id,LetturaParametriBusta parametri) throws ProtocolException{
  656.         return getSomeValues(id,Costanti.INBOX,parametri,false, null);
  657.     }
  658.     public Busta getSomeValuesFromInBox(String id,LetturaParametriBusta parametri,boolean forzaLetturaDatabase) throws ProtocolException{
  659.         return getSomeValues(id,Costanti.INBOX,parametri,forzaLetturaDatabase, null);
  660.     }
  661.     public Busta getSomeValuesFromInBox(String id,LetturaParametriBusta parametri, Date dataRegistrazione) throws ProtocolException{
  662.         return getSomeValues(id,Costanti.INBOX,parametri,false,dataRegistrazione);
  663.     }
  664.     public Busta getSomeValuesFromInBox(String id,LetturaParametriBusta parametri,boolean forzaLetturaDatabase, Date dataRegistrazione) throws ProtocolException{
  665.         return getSomeValues(id,Costanti.INBOX,parametri,forzaLetturaDatabase,dataRegistrazione);
  666.     }
  667.    
  668.     /**
  669.      * Ritorna la collaborazione associata alla busta.
  670.      *
  671.      * @param id identificativo della busta.
  672.      * @return Collaborazione associata alla busta
  673.      *
  674.      */
  675.     public String getCollaborazioneFromInBox(String id) throws ProtocolException{
  676.         return getCollaborazione(id,Costanti.INBOX);
  677.     }

  678.     /**
  679.      * Ritorna il profilo di collaborazione associata alla busta.
  680.      *
  681.      * @param id identificativo della busta.
  682.      * @return Collaborazione associata alla busta
  683.      *
  684.      */
  685.     public org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione getProfiloCollaborazioneFromInBox(String id) throws ProtocolException{
  686.         return getProfiloCollaborazione(id,Costanti.INBOX);
  687.     }
  688.    
  689.     public String getProfiloCollaborazioneValueFromInBox(String id) throws ProtocolException{
  690.         return getProfiloCollaborazioneValue(id,Costanti.INBOX);
  691.     }

  692.     /**
  693.      * Ritorna la sequenza associata alla busta in entrata.
  694.      *
  695.      * @param id identificativo della busta.
  696.      * @return Sequenza associata alla busta
  697.      *
  698.      */
  699.     public long getSequenzaFromInBox(String id) throws ProtocolException{
  700.         return getSequenza(id,Costanti.INBOX);
  701.     }

  702.     /**
  703.      * Ritorna le informazioni di integrazione associate alla busta in entrata.
  704.      *
  705.      * @param id identificativo della busta.
  706.      * @return Informazioni di integrazione associate alla busta
  707.      *
  708.      */
  709.     public Integrazione getInfoIntegrazioneFromInBox(String id) throws ProtocolException{
  710.         return getInfoIntegrazione(id,Costanti.INBOX);
  711.     }

  712.     /**
  713.      * Metodo che si occupa di eliminare l'indicazione di utilizzo della busta da parte della PdD
  714.      *
  715.      * @param id identificativo della busta.
  716.      *
  717.      */
  718.     public void eliminaUtilizzoPdDFromInBox(String id) throws ProtocolException{
  719.         this.eliminaUtilizzoPdD(id,Costanti.INBOX,false, null);
  720.     }
  721.     public void eliminaUtilizzoPdDFromInBox(String id,boolean forzaUpdateDB) throws ProtocolException{
  722.         eliminaUtilizzoPdD(id,Costanti.INBOX,forzaUpdateDB, null);
  723.     }
  724.     public void eliminaUtilizzoPdDFromInBox(String id,boolean forzaUpdateDB,boolean savePreparedStatement) throws ProtocolException{
  725.         eliminaUtilizzoPdD(id,Costanti.INBOX,forzaUpdateDB,savePreparedStatement, null);
  726.     }
  727.     public void eliminaUtilizzoPdDFromInBox(String id, Date dataRegistrazione) throws ProtocolException{
  728.         this.eliminaUtilizzoPdD(id,Costanti.INBOX,false, dataRegistrazione);
  729.     }
  730.     public void eliminaUtilizzoPdDFromInBox(String id,boolean forzaUpdateDB, Date dataRegistrazione) throws ProtocolException{
  731.         eliminaUtilizzoPdD(id,Costanti.INBOX,forzaUpdateDB, dataRegistrazione);
  732.     }
  733.     public void eliminaUtilizzoPdDFromInBox(String id,boolean forzaUpdateDB,boolean savePreparedStatement, Date dataRegistrazione) throws ProtocolException{
  734.         eliminaUtilizzoPdD(id,Costanti.INBOX,forzaUpdateDB,savePreparedStatement, dataRegistrazione);
  735.     }

  736.     /**
  737.      * Metodo che si occupa di eliminare una busta precedentemente salvata.
  738.      * Alla busta, al momento della registrazione,
  739.      * e' stato associato l'identificativo della busta, quindi attraverso esso sara' possibile trovarlo nella History.
  740.      *
  741.      * @param id identificativo della busta.
  742.      *
  743.      */
  744.     public void eliminaBustaFromInBox(String id, Date data) throws ProtocolException{
  745.         eliminaBusta(id,Costanti.INBOX, data);
  746.     }

  747.     public void eliminaBustaStatelessFromInBox(String id) throws ProtocolException{
  748.         eliminaBustaStateless(id,Costanti.INBOX, null);
  749.     }
  750.     public void eliminaBustaStatelessFromInBox(String id, Date dataRegistrazione) throws ProtocolException{
  751.         eliminaBustaStateless(id,Costanti.INBOX, dataRegistrazione);
  752.     }

  753.     /**
  754.      * Metodo che si occupa di impostare l'indicazione di utilizzo della busta da parte della PdD
  755.      *
  756.      * @param id identificativo della busta.
  757.      *
  758.      */
  759.     public void impostaUtilizzoPdDIntoInBox(String id) throws ProtocolException{
  760.         impostaUtilizzoPdD(id,Costanti.INBOX);
  761.     }















  762.     /* ********  G E S T I O N E   B U S T E  ******** */
  763.     /**
  764.      * Metodo che si occupa di registrare una busta.
  765.      *
  766.      * @param busta Contiene le informazioni su di una busta  (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  767.      * @param scadenza Scadenza Scadenza in minuti associata ad una busta, se non possiede essa stessa una scadenza
  768.      *
  769.      */
  770.     public void registraBustaIntoInboxForHistory(Busta busta,long scadenza) throws ProtocolException{
  771.        
  772.         StateMessage stateMSG = (StateMessage)this.state;
  773.                
  774.         Connection connectionDB = stateMSG.getConnectionDB();

  775.         PreparedStatement pstmtBusta = null;
  776.        
  777.         try{

  778.             Timestamp dataRegistrazione = DateManager.getTimestamp();
  779.            
  780.             //  Impostazione scadenza
  781.             Date scadenzaBusta = busta.getScadenza();
  782.             if(scadenzaBusta == null){
  783.                 scadenzaBusta = new Date(DateManager.getTimeMillis()+(scadenza*60*1000));
  784.             }
  785.             Timestamp scadenzaT = new Timestamp( scadenzaBusta.getTime()  );


  786.             /* Busta */

  787.             // Registrazione Busta
  788.             StringBuilder query = new StringBuilder();
  789.             query.append("INSERT INTO  ");
  790.             query.append(Costanti.REPOSITORY);
  791.             query.append(" (ID_MESSAGGIO,TIPO,MITTENTE,IDPORTA_MITTENTE,TIPO_MITTENTE,IND_TELEMATICO_MITT,DESTINATARIO,IDPORTA_DESTINATARIO,TIPO_DESTINATARIO,IND_TELEMATICO_DEST");
  792.             query.append(",VERSIONE_SERVIZIO,SERVIZIO,TIPO_SERVIZIO,AZIONE,PROFILO_DI_COLLABORAZIONE,SERVIZIO_CORRELATO,TIPO_SERVIZIO_CORRELATO");
  793.             query.append(",COLLABORAZIONE,SEQUENZA,INOLTRO_SENZA_DUPLICATI,CONFERMA_RICEZIONE,ORA_REGISTRAZIONE,TIPO_ORA_REGISTRAZIONE");
  794.             query.append(",RIFERIMENTO_MESSAGGIO,SCADENZA_BUSTA,DUPLICATI,LOCATION_PD,SERVIZIO_APPLICATIVO,MODULO_IN_ATTESA,SCENARIO,PROTOCOLLO,DATA_REGISTRAZIONE,");
  795.             query.append(this.gestoreRepositoryBuste.createSQLFieldHistory());
  796.             query.append(") ");
  797.             query.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,");
  798.             query.append(this.gestoreRepositoryBuste.getSQLValueHistory(true));
  799.             query.append(")");
  800.            
  801.             pstmtBusta = connectionDB.prepareStatement(query.toString());
  802.             int index = 1;
  803.             pstmtBusta.setString(index++,busta.getID());
  804.             pstmtBusta.setString(index++,Costanti.INBOX);
  805.             pstmtBusta.setString(index++,busta.getMittente());
  806.             pstmtBusta.setString(index++,busta.getIdentificativoPortaMittente());
  807.             pstmtBusta.setString(index++,busta.getTipoMittente());
  808.             pstmtBusta.setString(index++,busta.getIndirizzoMittente());
  809.             pstmtBusta.setString(index++,busta.getDestinatario());
  810.             pstmtBusta.setString(index++,busta.getIdentificativoPortaDestinatario());
  811.             pstmtBusta.setString(index++,busta.getTipoDestinatario());
  812.             pstmtBusta.setString(index++,busta.getIndirizzoDestinatario());
  813.             pstmtBusta.setInt(index++,busta.getVersioneServizio());
  814.             pstmtBusta.setString(index++,busta.getServizio());
  815.             pstmtBusta.setString(index++,busta.getTipoServizio());
  816.             pstmtBusta.setString(index++,busta.getAzione());
  817.             pstmtBusta.setString(index++,busta.getProfiloDiCollaborazione().getEngineValue());
  818.             pstmtBusta.setString(index++,busta.getServizioCorrelato());
  819.             pstmtBusta.setString(index++,busta.getTipoServizioCorrelato());
  820.             pstmtBusta.setString(index++,busta.getCollaborazione());
  821.             pstmtBusta.setLong(index++, busta.getSequenza() );
  822.             if(Inoltro.SENZA_DUPLICATI.equals(busta.getInoltro()))
  823.                 pstmtBusta.setInt(index++,1);
  824.             else
  825.                 pstmtBusta.setInt(index++,0);
  826.             if(busta.isConfermaRicezione())
  827.                 pstmtBusta.setInt(index++,1);
  828.             else
  829.                 pstmtBusta.setInt(index++,0);
  830.             Timestamp oraRec = null;
  831.             TipoOraRegistrazione tipoOraRec = null;
  832.             if(busta.getOraRegistrazione()!=null && busta.getTipoOraRegistrazione()!=null){
  833.                 oraRec = new Timestamp( busta.getOraRegistrazione().getTime() );
  834.                 tipoOraRec = busta.getTipoOraRegistrazione();
  835.             }else{
  836.                 // poi sara' aggiornato.
  837.                 oraRec = dataRegistrazione;
  838.                 tipoOraRec = TipoOraRegistrazione.SINCRONIZZATO;
  839.             }
  840.             pstmtBusta.setTimestamp(index++,oraRec);
  841.             pstmtBusta.setString(index++,tipoOraRec.getEngineValue());
  842.             pstmtBusta.setString(index++,busta.getRiferimentoMessaggio());
  843.             pstmtBusta.setTimestamp(index++,scadenzaT);
  844.             pstmtBusta.setInt(index++,0);
  845.             pstmtBusta.setString(index++,null); // locationPD
  846.             pstmtBusta.setString(index++,null); // servizioApplicativo
  847.             pstmtBusta.setString(index++,null); // moduloInAttesa
  848.             pstmtBusta.setString(index++,null); // scenario
  849.             if(busta.getProtocollo()!=null)
  850.                 pstmtBusta.setString(index++,busta.getProtocollo()); // protocollo
  851.             else if(this.protocolFactory!=null){
  852.                 pstmtBusta.setString(index++,this.protocolFactory.getProtocol()); // protocollo
  853.             }
  854.             else{
  855.                 throw new ProtocolException("Protocol unknow");
  856.             }
  857.             pstmtBusta.setTimestamp(index++,dataRegistrazione);
  858.                

  859.             // Add PreparedStatement
  860.             stateMSG.getPreparedStatement().put("INSERT RegistrazioneBustaForHistoryINBOX_"+busta.getID(),pstmtBusta);

  861.         } catch(Exception e) {
  862.             String id = busta.getID();
  863.             String errorMsg = "REPOSITORY_BUSTE, Errore di registrazione per History INBOX/"+id+": "+e.getMessage();
  864.             this.log.error(errorMsg,e);
  865.             try{
  866.                 if(pstmtBusta != null)
  867.                     pstmtBusta.close();
  868.             } catch(Exception er) {
  869.                 // Eccezione SQL.
  870.             }
  871.             throw new ProtocolException(errorMsg,e);
  872.         }
  873.     }
  874.     /**
  875.      * Metodo che si occupa di registrare una busta.
  876.      *
  877.      * @param busta Contiene le informazioni su di una busta  (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  878.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  879.      * @param errors Eventuali errori di validazione
  880.      * @param scadenza Scadenza Scadenza in minuti associata ad una busta, se non possiede essa stessa una scadenza
  881.      *
  882.      */
  883.     public void registraBusta(Busta busta,String tipoBusta,List<Eccezione> errors,long scadenza) throws ProtocolException{
  884.         registraBusta(busta,tipoBusta,errors,scadenza,false);
  885.     }
  886.     public void registraBusta(Busta busta,String tipoBusta,List<Eccezione> errors,long scadenza, boolean saveServizioApplicativoFruitore) throws ProtocolException{
  887.        
  888.         if (!this.isRichiesta && this.state instanceof StatelessMessage) {
  889.             ((StatelessMessage)this.state).setBusta(busta);
  890.             return;
  891.         }
  892.        
  893.         Timestamp dataRegistrazione = DateManager.getTimestamp();
  894.        
  895.         StateMessage stateMSG = (StateMessage)this.state;
  896.                
  897.         Connection connectionDB = stateMSG.getConnectionDB();

  898.         PreparedStatement pstmtBusta = null;
  899.         PreparedStatement pstmtUpdateAccessoPdD = null;
  900.         PreparedStatement pstmtListaRiscontri = null;
  901.         PreparedStatement pstmtListaTrasmissioni = null;
  902.         PreparedStatement pstmtListaEccezioni = null;
  903.         PreparedStatement pstmtListaEccezioniValidazione = null;
  904.         PreparedStatement pstmtListaExtInfo = null;

  905.         try{

  906.             //  Impostazione scadenza
  907.             Date scadenzaBusta = busta.getScadenza();
  908.             if(scadenzaBusta == null){
  909.                 scadenzaBusta = new Date(DateManager.getTimeMillis()+(scadenza*60*1000));
  910.             }
  911.             Timestamp scadenzaT = new Timestamp( scadenzaBusta.getTime()  );


  912.             /* Busta */

  913.             // Registrazione Busta
  914.             StringBuilder query = new StringBuilder();
  915.             query.append("INSERT INTO  ");
  916.             query.append(Costanti.REPOSITORY);
  917.             query.append(" (ID_MESSAGGIO,TIPO,MITTENTE,IDPORTA_MITTENTE,TIPO_MITTENTE,IND_TELEMATICO_MITT,DESTINATARIO,IDPORTA_DESTINATARIO,TIPO_DESTINATARIO,IND_TELEMATICO_DEST");
  918.             query.append(",VERSIONE_SERVIZIO,SERVIZIO,TIPO_SERVIZIO,AZIONE,PROFILO_DI_COLLABORAZIONE,SERVIZIO_CORRELATO,TIPO_SERVIZIO_CORRELATO");
  919.             query.append(",COLLABORAZIONE,SEQUENZA,INOLTRO_SENZA_DUPLICATI,CONFERMA_RICEZIONE,ORA_REGISTRAZIONE,TIPO_ORA_REGISTRAZIONE");
  920.             query.append(",RIFERIMENTO_MESSAGGIO,SCADENZA_BUSTA,DUPLICATI,LOCATION_PD,SERVIZIO_APPLICATIVO,MODULO_IN_ATTESA,SCENARIO,PROTOCOLLO,DATA_REGISTRAZIONE) ");
  921.             query.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
  922.             pstmtBusta = connectionDB.prepareStatement(query.toString());
  923.             int index = 1;
  924.             pstmtBusta.setString(index++,busta.getID());
  925.             pstmtBusta.setString(index++,tipoBusta);
  926.             pstmtBusta.setString(index++,busta.getMittente());
  927.             pstmtBusta.setString(index++,busta.getIdentificativoPortaMittente());
  928.             pstmtBusta.setString(index++,busta.getTipoMittente());
  929.             pstmtBusta.setString(index++,busta.getIndirizzoMittente());
  930.             pstmtBusta.setString(index++,busta.getDestinatario());
  931.             pstmtBusta.setString(index++,busta.getIdentificativoPortaDestinatario());
  932.             pstmtBusta.setString(index++,busta.getTipoDestinatario());
  933.             pstmtBusta.setString(index++,busta.getIndirizzoDestinatario());
  934.             pstmtBusta.setInt(index++,busta.getVersioneServizio());
  935.             pstmtBusta.setString(index++,busta.getServizio());
  936.             pstmtBusta.setString(index++,busta.getTipoServizio());
  937.             pstmtBusta.setString(index++,busta.getAzione());
  938.             pstmtBusta.setString(index++,busta.getProfiloDiCollaborazione() == null ? null : busta.getProfiloDiCollaborazione().getEngineValue());
  939.             pstmtBusta.setString(index++,busta.getServizioCorrelato());
  940.             pstmtBusta.setString(index++,busta.getTipoServizioCorrelato());
  941.             pstmtBusta.setString(index++,busta.getCollaborazione());
  942.             pstmtBusta.setLong(index++, busta.getSequenza() );
  943.             if(Inoltro.SENZA_DUPLICATI.equals(busta.getInoltro()))
  944.                 pstmtBusta.setInt(index++,1);
  945.             else
  946.                 pstmtBusta.setInt(index++,0);
  947.             if(busta.isConfermaRicezione())
  948.                 pstmtBusta.setInt(index++,1);
  949.             else
  950.                 pstmtBusta.setInt(index++,0);
  951.             Timestamp oraRec = null;
  952.             TipoOraRegistrazione tipoOraRec = null;
  953.             if(busta.getOraRegistrazione()!=null && busta.getTipoOraRegistrazione()!=null){
  954.                 oraRec = new Timestamp( busta.getOraRegistrazione().getTime() );
  955.                 tipoOraRec = busta.getTipoOraRegistrazione();
  956.             }else{
  957.                 // poi sara' aggiornato.
  958.                 oraRec = dataRegistrazione;
  959.                 tipoOraRec = TipoOraRegistrazione.SINCRONIZZATO;
  960.             }
  961.             pstmtBusta.setTimestamp(index++,oraRec);
  962.             pstmtBusta.setString(index++,tipoOraRec.getEngineValue());
  963.             pstmtBusta.setString(index++,busta.getRiferimentoMessaggio());
  964.             pstmtBusta.setTimestamp(index++,scadenzaT);
  965.             pstmtBusta.setInt(index++,0);
  966.             pstmtBusta.setString(index++,null); // locationPD
  967.             if(saveServizioApplicativoFruitore) { // servizioApplicativo
  968.                 pstmtBusta.setString(index++,busta.getServizioApplicativoFruitore());
  969.             }
  970.             else {
  971.                 pstmtBusta.setString(index++,null);
  972.             }
  973.             pstmtBusta.setString(index++,null); // moduloInAttesa
  974.             pstmtBusta.setString(index++,null); // scenario
  975.             if(busta.getProtocollo()!=null)
  976.                 pstmtBusta.setString(index++,busta.getProtocollo()); // protocollo
  977.             else if(this.protocolFactory!=null){
  978.                 pstmtBusta.setString(index++,this.protocolFactory.getProtocol()); // protocollo
  979.             }
  980.             else{
  981.                 throw new ProtocolException("Protocol unknow");
  982.             }
  983.             pstmtBusta.setTimestamp(index++,dataRegistrazione);

  984.             // Add PreparedStatement
  985.             stateMSG.getPreparedStatement().put("INSERT RegistrazioneBusta"+tipoBusta+"_"+busta.getID(),pstmtBusta);

  986.            
  987.             // Update Accesso da Pdd
  988.             query.delete(0,query.length());
  989.             query.append("UPDATE ");
  990.             query.append(Costanti.REPOSITORY);
  991.             query.append(" SET ");
  992.             query.append(this.gestoreRepositoryBuste.createSQLSet_PdD(true));
  993.             query.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  994.             pstmtUpdateAccessoPdD = connectionDB.prepareStatement(query.toString());
  995.             index = 1;
  996.             pstmtUpdateAccessoPdD.setString(index++,busta.getID());
  997.             pstmtUpdateAccessoPdD.setString(index++,tipoBusta);
  998.             // Add PreparedStatement
  999.             //stateMSG.getPreparedStatement().put("UPDATE RegistrazioneBustaAccessoPdD"+tipoBusta+"_"+busta.getID(),pstmtUpdateAccessoPdD);
  1000.             stateMSG.getPreparedStatement().put("INSERT RegistrazioneBusta"+tipoBusta+"_"+busta.getID()+" UPDATE RegistrazioneBustaAccessoPdD",pstmtUpdateAccessoPdD);
  1001.            
  1002.            
  1003.             if (this.state instanceof StatefulMessage ) {


  1004.                 /* Lista Riscontri */
  1005.                 for(int i=0; i<busta.sizeListaRiscontri(); i++){
  1006.                     Riscontro riscontro = busta.getRiscontro(i);
  1007.                     query.delete(0,query.length());
  1008.                     query.append("INSERT INTO  ");
  1009.                     query.append(Costanti.LISTA_RISCONTRI);
  1010.                     query.append(" (ID_MESSAGGIO,TIPO,ID_RISCONTRO,RICEVUTA,ORA_REGISTRAZIONE,TIPO_ORA_REGISTRAZIONE,DATA_REGISTRAZIONE)");
  1011.                     query.append(" VALUES (?,?,?,?,?,?,?)");
  1012.                     pstmtListaRiscontri = connectionDB.prepareStatement(query.toString());
  1013.                     index = 1;
  1014.                     pstmtListaRiscontri.setString(index++,busta.getID());
  1015.                     pstmtListaRiscontri.setString(index++,tipoBusta);
  1016.                     pstmtListaRiscontri.setString(index++,riscontro.getID());
  1017.                     pstmtListaRiscontri.setString(index++,riscontro.getRicevuta());
  1018.                     Timestamp oraRecRiscontro = null;
  1019.                     if(riscontro.getOraRegistrazione()!=null ){
  1020.                         oraRecRiscontro = new Timestamp( riscontro.getOraRegistrazione().getTime() );
  1021.                     }
  1022.                     pstmtListaRiscontri.setTimestamp(index++,oraRecRiscontro);
  1023.                     pstmtListaRiscontri.setString(index++,riscontro.getTipoOraRegistrazione().getEngineValue());
  1024.                     pstmtListaRiscontri.setTimestamp(index++,dataRegistrazione);

  1025.                     // Add PreparedStatement
  1026.                     stateMSG.getPreparedStatement().put("INSERT RegistrazioneListaRiscontri_riscontro["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaRiscontri);
  1027.                 }

  1028.                 /* Lista Trasmissioni */
  1029.                 for(int i=0; i<busta.sizeListaTrasmissioni(); i++){

  1030.                     Trasmissione trasmissione = busta.getTrasmissione(i);
  1031.                     query.delete(0,query.length());
  1032.                     query.append("INSERT INTO  ");
  1033.                     query.append(Costanti.LISTA_TRASMISSIONI);
  1034.                     query.append(" (ID_MESSAGGIO,TIPO,ORIGINE,TIPO_ORIGINE,DESTINAZIONE,TIPO_DESTINAZIONE,ORA_REGISTRAZIONE,TIPO_ORA_REGISTRAZIONE,DATA_REGISTRAZIONE)");
  1035.                     query.append(" VALUES (?,?,?,?,?,?,?,?,?)");
  1036.                     pstmtListaTrasmissioni = connectionDB.prepareStatement(query.toString());
  1037.                     index = 1;
  1038.                     pstmtListaTrasmissioni.setString(index++,busta.getID());
  1039.                     pstmtListaTrasmissioni.setString(index++,tipoBusta);
  1040.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getOrigine());
  1041.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getTipoOrigine());
  1042.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getDestinazione());
  1043.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getTipoDestinazione());
  1044.                     Timestamp oraRecTrasmissione = null;
  1045.                     if( trasmissione.getOraRegistrazione()!=null ){
  1046.                         oraRecTrasmissione = new Timestamp( trasmissione.getOraRegistrazione().getTime()  );
  1047.                     }
  1048.                     pstmtListaTrasmissioni.setTimestamp(index++,oraRecTrasmissione);
  1049.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getTempo().getEngineValue());
  1050.                     pstmtListaTrasmissioni.setTimestamp(index++,dataRegistrazione);

  1051.                     // Add PreparedStatement
  1052.                     stateMSG.getPreparedStatement().put("INSERT RegistrazioneListaTrasmissioni_trasmissione["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaTrasmissioni);
  1053.                 }

  1054.                 /* Lista Eccezioni */
  1055.                 for(int i=0; i<busta.sizeListaEccezioni(); i++){
  1056.                     Eccezione eccezione = busta.getEccezione(i);
  1057.                     query.delete(0,query.length());
  1058.                     query.append("INSERT INTO  ");
  1059.                     query.append(Costanti.LISTA_ECCEZIONI);
  1060.                     query.append(" (ID_MESSAGGIO,TIPO,VALIDAZIONE,CONTESTO,CODICE,RILEVANZA,POSIZIONE,DATA_REGISTRAZIONE)");
  1061.                     query.append(" VALUES (?,?,?,?,?,?,?,?)");
  1062.                     pstmtListaEccezioni = connectionDB.prepareStatement(query.toString());
  1063.                     index = 1;
  1064.                     pstmtListaEccezioni.setString(index++,busta.getID());
  1065.                     pstmtListaEccezioni.setString(index++,tipoBusta);
  1066.                     pstmtListaEccezioni.setInt(index++,0); // eccezione proprietaria delle busta
  1067.                     pstmtListaEccezioni.setString(index++,eccezione.getContestoCodifica().getEngineValue());
  1068.                     pstmtListaEccezioni.setInt(index++,eccezione.getCodiceEccezione().getCodice());
  1069.                     pstmtListaEccezioni.setString(index++,eccezione.getRilevanza().getEngineValue());
  1070.                     pstmtListaEccezioni.setString(index++,eccezione.getDescrizione(this.protocolFactory));
  1071.                     pstmtListaEccezioni.setTimestamp(index++,dataRegistrazione);

  1072.                     // Add PreparedStatement
  1073.                     stateMSG.getPreparedStatement().put("INSERT RegistrazioneListaEccezioni_eccezioneBusta["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaEccezioni);
  1074.                 }

  1075.                 /* Lista Eccezioni Validazione */
  1076.                 if(errors!=null){
  1077.                     for(int i=0; i<errors.size(); i++){
  1078.                         Eccezione eccezione = errors.get(i);
  1079.                         query.delete(0,query.length());
  1080.                         query.append("INSERT INTO  ");
  1081.                         query.append(Costanti.LISTA_ECCEZIONI);
  1082.                         query.append(" (ID_MESSAGGIO,TIPO,VALIDAZIONE,CONTESTO,CODICE,RILEVANZA,POSIZIONE,DATA_REGISTRAZIONE)");
  1083.                         query.append(" VALUES (?,?,?,?,?,?,?,?)");
  1084.                         pstmtListaEccezioniValidazione = connectionDB.prepareStatement(query.toString());
  1085.                         index = 1;
  1086.                         pstmtListaEccezioniValidazione.setString(index++,busta.getID());
  1087.                         pstmtListaEccezioniValidazione.setString(index++,tipoBusta);
  1088.                         pstmtListaEccezioniValidazione.setInt(index++,1); // eccezione arrivata dopo la validazione
  1089.                         pstmtListaEccezioniValidazione.setString(index++,eccezione.getContestoCodifica().getEngineValue());
  1090.                         pstmtListaEccezioniValidazione.setInt(index++,eccezione.getCodiceEccezione().getCodice());
  1091.                         pstmtListaEccezioniValidazione.setString(index++,eccezione.getRilevanza().getEngineValue());
  1092.                         pstmtListaEccezioniValidazione.setString(index++,eccezione.getDescrizione(this.protocolFactory));
  1093.                         pstmtListaEccezioniValidazione.setTimestamp(index++,dataRegistrazione);

  1094.                         // Add PreparedStatement
  1095.                         stateMSG.getPreparedStatement().put("INSERT RegistrazioneListaEccezioni_eccezioneValidazione["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaEccezioniValidazione);
  1096.                     }
  1097.                 }

  1098.                 /* Lista ExtProtocolInfo */
  1099.                 if(busta.sizeProperties()>0){
  1100.                     String[] names = busta.getPropertiesNames();
  1101.                     if(names!=null && names.length>0){
  1102.                         for (int i = 0; i < names.length; i++) {
  1103.                             String name = names[i];
  1104.                             String value = busta.getProperty(name);
  1105.                            
  1106.                             query.delete(0,query.length());
  1107.                             query.append("INSERT INTO  ");
  1108.                             query.append(Costanti.LISTA_EXT_INFO);
  1109.                             query.append(" (ID_MESSAGGIO,TIPO,NOME,VALORE,DATA_REGISTRAZIONE)");
  1110.                             query.append(" VALUES (?,?,?,?,?)");
  1111.                             pstmtListaExtInfo = connectionDB.prepareStatement(query.toString());
  1112.                             index = 1;
  1113.                             pstmtListaExtInfo.setString(index++,busta.getID());
  1114.                             pstmtListaExtInfo.setString(index++,tipoBusta);
  1115.                             pstmtListaExtInfo.setString(index++,name);
  1116.                             pstmtListaExtInfo.setString(index++,value);
  1117.                             pstmtListaExtInfo.setTimestamp(index++,dataRegistrazione);

  1118.                             // Add PreparedStatement
  1119.                             stateMSG.getPreparedStatement().put("INSERT RegistrazioneListaExtInfoProtocol_info["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaExtInfo);
  1120.                         }
  1121.                     }
  1122.                 }
  1123.                
  1124.             }
  1125.         } catch(Exception e) {
  1126.             String id = busta.getID();
  1127.             String errorMsg = "REPOSITORY_BUSTE, Errore di registrazione "+tipoBusta+"/"+id+": "+e.getMessage();
  1128.             this.log.error(errorMsg,e);
  1129.             try{
  1130.                 if(pstmtBusta != null)
  1131.                     pstmtBusta.close();
  1132.             } catch(Exception er) {
  1133.                 // Eccezione SQL.
  1134.             }
  1135.             try{
  1136.                 if(pstmtUpdateAccessoPdD!= null)
  1137.                     pstmtUpdateAccessoPdD.close();
  1138.             } catch(Exception er) {
  1139.                 // Eccezione SQL.
  1140.             }
  1141.             try{
  1142.                 if(pstmtListaRiscontri != null)
  1143.                     pstmtListaRiscontri.close();
  1144.             } catch(Exception er) {
  1145.                 // Eccezione SQL.
  1146.             }
  1147.             try{
  1148.                 if(pstmtListaTrasmissioni != null)
  1149.                     pstmtListaTrasmissioni.close();
  1150.             } catch(Exception er) {
  1151.                 // Eccezione SQL.
  1152.             }
  1153.             try{
  1154.                 if(pstmtListaEccezioni != null)
  1155.                     pstmtListaEccezioni.close();
  1156.             } catch(Exception er) {
  1157.                 // Eccezione SQL.
  1158.             }
  1159.             try{
  1160.                 if(pstmtListaEccezioniValidazione != null)
  1161.                     pstmtListaEccezioniValidazione.close();
  1162.             } catch(Exception er) {
  1163.                 // Eccezione SQL.
  1164.             }
  1165.             try{
  1166.                 if(pstmtListaExtInfo != null)
  1167.                     pstmtListaExtInfo.close();
  1168.             } catch(Exception er) {
  1169.                 // Eccezione SQL.
  1170.             }
  1171.             throw new ProtocolException(errorMsg,e);
  1172.         }

  1173.         // tengo la busta anche nello state message per recuperarla senza passare dal db        
  1174.         if (stateMSG instanceof StatelessMessage) ((StatelessMessage)stateMSG).setBusta(busta);
  1175.     }

  1176.    
  1177.     public void aggiornaProprietaBusta(Map<String, String> properties, String idBusta,String tipoBusta) throws ProtocolException{
  1178.                
  1179.         StateMessage stateMSG = (StateMessage)this.state;
  1180.                
  1181.         Connection connectionDB = stateMSG.getConnectionDB();

  1182.         if(connectionDB==null){
  1183.             return ;
  1184.         }
  1185.        
  1186.         PreparedStatement pstmtDeleteListaExtInfo = null;
  1187.         PreparedStatement pstmtListaExtInfo = null;

  1188.         try{

  1189.             //  elimino lista ext-info
  1190.             StringBuilder queryDelete = new StringBuilder();
  1191.             queryDelete.delete(0,queryDelete.length());
  1192.             queryDelete.append("DELETE FROM ");
  1193.             queryDelete.append(Costanti.LISTA_EXT_INFO);
  1194.             queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  1195.             pstmtDeleteListaExtInfo = connectionDB.prepareStatement(queryDelete.toString());
  1196.             pstmtDeleteListaExtInfo.setString(1,idBusta);
  1197.             pstmtDeleteListaExtInfo.setString(2,tipoBusta);

  1198.             //  Add PreparedStatement
  1199.             stateMSG.getPreparedStatement().put("DELETE(UPDATE) AggiornamentoBusta_listaExtInfo"+tipoBusta+"_"+idBusta,pstmtDeleteListaExtInfo);
  1200.            
  1201.             /* Lista ExtProtocolInfo */
  1202.             if(properties.size()>0){
  1203.                 int index = 0;
  1204.                 for (String name : properties.keySet()) {
  1205.                     String value = properties.get(name);
  1206.                        
  1207.                     StringBuilder query = new StringBuilder();
  1208.                     query.delete(0,query.length());
  1209.                     query.append("INSERT INTO  ");
  1210.                     query.append(Costanti.LISTA_EXT_INFO);
  1211.                     query.append(" (ID_MESSAGGIO,TIPO,NOME,VALORE)");
  1212.                     query.append(" VALUES (?,?,?,?)");
  1213.                     pstmtListaExtInfo = connectionDB.prepareStatement(query.toString());
  1214.                     pstmtListaExtInfo.setString(1,idBusta);
  1215.                     pstmtListaExtInfo.setString(2,tipoBusta);
  1216.                     pstmtListaExtInfo.setString(3,name);
  1217.                     pstmtListaExtInfo.setString(4,value);

  1218.                     // Add PreparedStatement
  1219.                     stateMSG.getPreparedStatement().put("INSERT(UPDATE) RegistrazioneListaExtInfoProtocol_info["+index+"]_"+tipoBusta+"_"+idBusta,pstmtListaExtInfo);
  1220.                    
  1221.                     index++;
  1222.                 }
  1223.             }
  1224.                
  1225.         } catch(Exception e) {
  1226.             String errorMsg = "REPOSITORY_BUSTE, Errore di aggiornamento proprieta' "+tipoBusta+"/"+idBusta+": "+e.getMessage();
  1227.             this.log.error(errorMsg,e);
  1228.             try{
  1229.                 if(pstmtDeleteListaExtInfo != null)
  1230.                     pstmtDeleteListaExtInfo.close();
  1231.             } catch(Exception er) {
  1232.                 // Eccezione SQL.
  1233.             }
  1234.             try{
  1235.                 if(pstmtListaExtInfo != null)
  1236.                     pstmtListaExtInfo.close();
  1237.             } catch(Exception er) {
  1238.                 // Eccezione SQL.
  1239.             }
  1240.             throw new ProtocolException(errorMsg,e);
  1241.         }

  1242.     }
  1243.    
  1244.     /**
  1245.      * Metodo che si occupa di aggiornare i dati di una busta (non aggiorna le liste).
  1246.      *
  1247.      * @param busta Contiene le informazioni su di una busta  (tipo {@link org.openspcoop2.protocol.sdk.Busta})
  1248.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1249.      * @param scadenza Scadenza Scadenza associata ad una busta, se non possiede essa stessa una scadenza
  1250.      * @param errors Eventuali errori di validazione
  1251.      *
  1252.      */
  1253.     public void aggiornaBusta(Busta busta,String tipoBusta,long scadenza,List<Eccezione> errors) throws ProtocolException{
  1254.         aggiornaBusta(busta, tipoBusta, scadenza, errors, false);
  1255.     }
  1256.     public void aggiornaBusta(Busta busta,String tipoBusta,long scadenza,List<Eccezione> errors, boolean saveServizioApplicativoFruitore) throws ProtocolException{
  1257.        
  1258.         if (!this.isRichiesta && this.state instanceof StatelessMessage) {
  1259.             ((StatelessMessage)this.state).setBusta(busta);
  1260.             return;
  1261.         }
  1262.        
  1263.         StateMessage stateMSG = (StateMessage)this.state;
  1264.        
  1265.         Connection connectionDB = stateMSG.getConnectionDB();

  1266.         PreparedStatement pstmtBusta = null;
  1267.         PreparedStatement pstmtDeleteListaRiscontri = null;
  1268.         PreparedStatement pstmtDeleteListaTrasmissioni = null;
  1269.         PreparedStatement pstmtDeleteListaEccezioni = null; // vale sia per validazione che per non...
  1270.         PreparedStatement pstmtDeleteListaExtInfo = null;
  1271.         PreparedStatement pstmtListaRiscontri = null;
  1272.         PreparedStatement pstmtListaTrasmissioni = null;
  1273.         PreparedStatement pstmtListaEccezioni = null;
  1274.         PreparedStatement pstmtListaEccezioniValidazione = null;
  1275.         PreparedStatement pstmtListaExtInfo = null;
  1276.         try{

  1277.             Timestamp dataRegistrazione = DateManager.getTimestamp();
  1278.            
  1279.             // Impostazione scadenza
  1280.             Date scadenzaBusta = busta.getScadenza();
  1281.             if(scadenzaBusta == null){
  1282.                 scadenzaBusta = new Date(DateManager.getTimeMillis()+(scadenza*60*1000));
  1283.             }
  1284.             Timestamp scadenzaT = new Timestamp( scadenzaBusta.getTime()  );

  1285.             /* Busta */

  1286.             // Registrazione Busta
  1287.             StringBuilder query = new StringBuilder();
  1288.             query.append("UPDATE  ");
  1289.             query.append(Costanti.REPOSITORY);
  1290.             query.append(" SET ");
  1291.             query.append("MITTENTE = ? ,");
  1292.             query.append("IDPORTA_MITTENTE = ? ,");
  1293.             query.append("TIPO_MITTENTE = ? ,");
  1294.             query.append("IND_TELEMATICO_MITT = ? ,");
  1295.             query.append("DESTINATARIO = ? ,");
  1296.             query.append("IDPORTA_DESTINATARIO = ? ,");
  1297.             query.append("TIPO_DESTINATARIO = ? ,");
  1298.             query.append("IND_TELEMATICO_DEST = ? ,");
  1299.             query.append("VERSIONE_SERVIZIO = ? ,");
  1300.             query.append("SERVIZIO = ? ,");
  1301.             query.append("TIPO_SERVIZIO = ? ,");
  1302.             query.append("AZIONE = ? ,");
  1303.             query.append("PROFILO_DI_COLLABORAZIONE = ? ,");
  1304.             query.append("SERVIZIO_CORRELATO = ? ,");
  1305.             query.append("TIPO_SERVIZIO_CORRELATO = ? ,");
  1306.             query.append("COLLABORAZIONE = ? ,");
  1307.             query.append("SEQUENZA = ? ,");
  1308.             query.append("INOLTRO_SENZA_DUPLICATI = ? ,");
  1309.             query.append("CONFERMA_RICEZIONE = ? ,");
  1310.             query.append("ORA_REGISTRAZIONE = ? ,");
  1311.             query.append("TIPO_ORA_REGISTRAZIONE = ? ,");
  1312.             query.append("RIFERIMENTO_MESSAGGIO = ? ,");
  1313.             query.append("SCADENZA_BUSTA = ? ,");
  1314.             query.append("DATA_REGISTRAZIONE = ? ");
  1315.             if(saveServizioApplicativoFruitore) {
  1316.                 query.append("SERVIZIO_APPLICATIVO = ? ");
  1317.             }
  1318.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  1319.             pstmtBusta = connectionDB.prepareStatement(query.toString());
  1320.             int index = 1;
  1321.             pstmtBusta.setString(index++,busta.getMittente());
  1322.             pstmtBusta.setString(index++,busta.getIdentificativoPortaMittente());
  1323.             pstmtBusta.setString(index++,busta.getTipoMittente());
  1324.             pstmtBusta.setString(index++,busta.getIndirizzoMittente());
  1325.             pstmtBusta.setString(index++,busta.getDestinatario());
  1326.             pstmtBusta.setString(index++,busta.getIdentificativoPortaDestinatario());
  1327.             pstmtBusta.setString(index++,busta.getTipoDestinatario());
  1328.             pstmtBusta.setString(index++,busta.getIndirizzoDestinatario());
  1329.             pstmtBusta.setInt(index++,busta.getVersioneServizio());
  1330.             pstmtBusta.setString(index++,busta.getServizio());
  1331.             pstmtBusta.setString(index++,busta.getTipoServizio());
  1332.             pstmtBusta.setString(index++,busta.getAzione());
  1333.             pstmtBusta.setString(index++,busta.getProfiloDiCollaborazione() == null ? null : busta.getProfiloDiCollaborazione().getEngineValue());
  1334.             pstmtBusta.setString(index++,busta.getServizioCorrelato());
  1335.             pstmtBusta.setString(index++,busta.getTipoServizioCorrelato());
  1336.             pstmtBusta.setString(index++,busta.getCollaborazione());
  1337.             pstmtBusta.setLong(index++, busta.getSequenza());
  1338.             if(Inoltro.SENZA_DUPLICATI.equals(busta.getInoltro()))
  1339.                 pstmtBusta.setInt(index++,1);
  1340.             else
  1341.                 pstmtBusta.setInt(index++,0);
  1342.             if(busta.isConfermaRicezione())
  1343.                 pstmtBusta.setInt(index++,1);
  1344.             else
  1345.                 pstmtBusta.setInt(index++,0);
  1346.             Timestamp oraRec = null;
  1347.             TipoOraRegistrazione tipoOraRec = null;
  1348.             if(busta.getOraRegistrazione()!=null && busta.getTipoOraRegistrazione()!=null){
  1349.                 oraRec = new Timestamp( busta.getOraRegistrazione().getTime() );
  1350.                 tipoOraRec = busta.getTipoOraRegistrazione();
  1351.             }
  1352.             pstmtBusta.setTimestamp(index++,oraRec);
  1353.             pstmtBusta.setString(index++,tipoOraRec!=null ? tipoOraRec.getEngineValue() : null);
  1354.             pstmtBusta.setString(index++,busta.getRiferimentoMessaggio());
  1355.             pstmtBusta.setTimestamp(index++,scadenzaT);
  1356.             pstmtBusta.setTimestamp(index++,dataRegistrazione);
  1357.             if(saveServizioApplicativoFruitore) {
  1358.                 pstmtBusta.setString(index++,busta.getServizioApplicativoFruitore());
  1359.             }
  1360.            
  1361.             pstmtBusta.setString(index++,busta.getID());
  1362.             pstmtBusta.setString(index++,tipoBusta);

  1363.             // Add PreparedStatement
  1364.             stateMSG.getPreparedStatement().put("UPDATE AggiornamentoBusta"+tipoBusta+"_"+busta.getID(),pstmtBusta);

  1365.             if(errors!=null){

  1366.                 // cancella liste
  1367.                 //  elimino lista trasmiossioni
  1368.                 StringBuilder queryDelete = new StringBuilder();
  1369.                 queryDelete.append("DELETE FROM ");
  1370.                 queryDelete.append(Costanti.LISTA_TRASMISSIONI);
  1371.                 queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  1372.                 pstmtDeleteListaRiscontri = connectionDB.prepareStatement(queryDelete.toString());
  1373.                 index = 1;
  1374.                 pstmtDeleteListaRiscontri.setString(index++,busta.getID());
  1375.                 pstmtDeleteListaRiscontri.setString(index++,tipoBusta);

  1376.                 //  Add PreparedStatement
  1377.                 stateMSG.getPreparedStatement().put("DELETE(UPDATE) AggiornamentoBusta_listaRiscontri"+tipoBusta+"_"+busta.getID(),pstmtDeleteListaRiscontri);

  1378.                 //  elimino lista riscontri
  1379.                 queryDelete.delete(0,queryDelete.length());
  1380.                 queryDelete.append("DELETE FROM ");
  1381.                 queryDelete.append(Costanti.LISTA_RISCONTRI);
  1382.                 queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  1383.                 pstmtDeleteListaTrasmissioni = connectionDB.prepareStatement(queryDelete.toString());
  1384.                 index = 1;
  1385.                 pstmtDeleteListaTrasmissioni.setString(index++,busta.getID());
  1386.                 pstmtDeleteListaTrasmissioni.setString(index++,tipoBusta);

  1387.                 //  Add PreparedStatement
  1388.                 stateMSG.getPreparedStatement().put("DELETE(UPDATE) AggiornamentoBusta_listaTrasmissioni"+tipoBusta+"_"+busta.getID(),pstmtDeleteListaTrasmissioni);

  1389.                 //  elimino lista eccezioni
  1390.                 queryDelete.delete(0,queryDelete.length());
  1391.                 queryDelete.append("DELETE FROM ");
  1392.                 queryDelete.append(Costanti.LISTA_ECCEZIONI);
  1393.                 queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  1394.                 pstmtDeleteListaEccezioni = connectionDB.prepareStatement(queryDelete.toString());
  1395.                 index = 1;
  1396.                 pstmtDeleteListaEccezioni.setString(index++,busta.getID());
  1397.                 pstmtDeleteListaEccezioni.setString(index++,tipoBusta);

  1398.                 //  Add PreparedStatement
  1399.                 stateMSG.getPreparedStatement().put("DELETE(UPDATE) AggiornamentoBusta_listaEccezioni"+tipoBusta+"_"+busta.getID(),pstmtDeleteListaEccezioni);
  1400.                
  1401.                 //  elimino lista ext-info
  1402.                 queryDelete.delete(0,queryDelete.length());
  1403.                 queryDelete.append("DELETE FROM ");
  1404.                 queryDelete.append(Costanti.LISTA_EXT_INFO);
  1405.                 queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  1406.                 pstmtDeleteListaExtInfo = connectionDB.prepareStatement(queryDelete.toString());
  1407.                 index = 1;
  1408.                 pstmtDeleteListaExtInfo.setString(index++,busta.getID());
  1409.                 pstmtDeleteListaExtInfo.setString(index++,tipoBusta);

  1410.                 //  Add PreparedStatement
  1411.                 stateMSG.getPreparedStatement().put("DELETE(UPDATE) AggiornamentoBusta_listaExtInfo"+tipoBusta+"_"+busta.getID(),pstmtDeleteListaExtInfo);
  1412.                

  1413.                 // Inserisco nuove liste

  1414.                 /* Lista Riscontri */
  1415.                 for(int i=0; i<busta.sizeListaRiscontri(); i++){
  1416.                     Riscontro riscontro = busta.getRiscontro(i);
  1417.                     query.delete(0,query.length());
  1418.                     query.append("INSERT INTO  ");
  1419.                     query.append(Costanti.LISTA_RISCONTRI);
  1420.                     query.append(" (ID_MESSAGGIO,TIPO,ID_RISCONTRO,RICEVUTA,ORA_REGISTRAZIONE,TIPO_ORA_REGISTRAZIONE,DATA_REGISTRAZIONE)");
  1421.                     query.append(" VALUES (?,?,?,?,?,?,?)");
  1422.                     pstmtListaRiscontri = connectionDB.prepareStatement(query.toString());
  1423.                     index = 1;
  1424.                     pstmtListaRiscontri.setString(index++,busta.getID());
  1425.                     pstmtListaRiscontri.setString(index++,tipoBusta);
  1426.                     pstmtListaRiscontri.setString(index++,riscontro.getID());
  1427.                     pstmtListaRiscontri.setString(index++,riscontro.getRicevuta());
  1428.                     Timestamp oraRecRiscontro = null;
  1429.                     if(riscontro.getOraRegistrazione()!=null ){
  1430.                         oraRecRiscontro = new Timestamp( riscontro.getOraRegistrazione().getTime() );
  1431.                     }
  1432.                     pstmtListaRiscontri.setTimestamp(index++,oraRecRiscontro);
  1433.                     pstmtListaRiscontri.setString(index++,riscontro.getTipoOraRegistrazione().getEngineValue());
  1434.                     pstmtListaRiscontri.setTimestamp(index++,dataRegistrazione);

  1435.                     // Add PreparedStatement
  1436.                     stateMSG.getPreparedStatement().put("INSERT(UPDATE) RegistrazioneListaRiscontri_riscontro["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaRiscontri);
  1437.                 }

  1438.                 /* Lista Trasmissioni */
  1439.                 for(int i=0; i<busta.sizeListaTrasmissioni(); i++){
  1440.                     Trasmissione trasmissione = busta.getTrasmissione(i);
  1441.                     query.delete(0,query.length());
  1442.                     query.append("INSERT INTO  ");
  1443.                     query.append(Costanti.LISTA_TRASMISSIONI);
  1444.                     query.append(" (ID_MESSAGGIO,TIPO,ORIGINE,TIPO_ORIGINE,DESTINAZIONE,TIPO_DESTINAZIONE,ORA_REGISTRAZIONE,TIPO_ORA_REGISTRAZIONE,DATA_REGISTRAZIONE)");
  1445.                     query.append(" VALUES (?,?,?,?,?,?,?,?,?)");
  1446.                     pstmtListaTrasmissioni = connectionDB.prepareStatement(query.toString());
  1447.                     index = 1;
  1448.                     pstmtListaTrasmissioni.setString(index++,busta.getID());
  1449.                     pstmtListaTrasmissioni.setString(index++,tipoBusta);
  1450.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getOrigine());
  1451.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getTipoOrigine());
  1452.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getDestinazione());
  1453.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getTipoDestinazione());
  1454.                     Timestamp oraRecTrasmissione = null;
  1455.                     if( trasmissione.getOraRegistrazione()!=null ){
  1456.                         oraRecTrasmissione = new Timestamp( trasmissione.getOraRegistrazione().getTime()  );
  1457.                     }
  1458.                     pstmtListaTrasmissioni.setTimestamp(index++,oraRecTrasmissione);
  1459.                     pstmtListaTrasmissioni.setString(index++,trasmissione.getTempo().getEngineValue());
  1460.                     pstmtListaTrasmissioni.setTimestamp(index++,dataRegistrazione);

  1461.                     // Add PreparedStatement
  1462.                     stateMSG.getPreparedStatement().put("INSERT(UPDATE) RegistrazioneListaTrasmissioni_trasmissione["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaTrasmissioni);
  1463.                 }

  1464.                 /* Lista Eccezioni */
  1465.                 for(int i=0; i<busta.sizeListaEccezioni(); i++){
  1466.                     Eccezione eccezione = busta.getEccezione(i);
  1467.                     query.delete(0,query.length());
  1468.                     query.append("INSERT INTO  ");
  1469.                     query.append(Costanti.LISTA_ECCEZIONI);
  1470.                     query.append(" (ID_MESSAGGIO,TIPO,VALIDAZIONE,CONTESTO,CODICE,RILEVANZA,POSIZIONE,DATA_REGISTRAZIONE)");
  1471.                     query.append(" VALUES (?,?,?,?,?,?,?,?)");
  1472.                     pstmtListaEccezioni = connectionDB.prepareStatement(query.toString());
  1473.                     index = 1;
  1474.                     pstmtListaEccezioni.setString(index++,busta.getID());
  1475.                     pstmtListaEccezioni.setString(index++,tipoBusta);
  1476.                     pstmtListaEccezioni.setInt(index++,0); // eccezione proprietaria delle busta
  1477.                     pstmtListaEccezioni.setString(index++,eccezione.getContestoCodifica().getEngineValue());
  1478.                     pstmtListaEccezioni.setInt(index++,eccezione.getCodiceEccezione().getCodice());
  1479.                     pstmtListaEccezioni.setString(index++,eccezione.getRilevanza().getEngineValue());
  1480.                     pstmtListaEccezioni.setString(index++,eccezione.getDescrizione(this.protocolFactory));
  1481.                     pstmtListaEccezioni.setTimestamp(index++,dataRegistrazione);

  1482.                     // Add PreparedStatement
  1483.                     stateMSG.getPreparedStatement().put("INSERT(UPDATE) RegistrazioneListaEccezioni_eccezioneBusta["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaEccezioni);
  1484.                 }

  1485.                 /* Lista Eccezioni Validazione */
  1486.                 for(int i=0; i<errors.size(); i++){
  1487.                     Eccezione eccezione = errors.get(i);
  1488.                     query.delete(0,query.length());
  1489.                     query.append("INSERT INTO  ");
  1490.                     query.append(Costanti.LISTA_ECCEZIONI);
  1491.                     query.append(" (ID_MESSAGGIO,TIPO,VALIDAZIONE,CONTESTO,CODICE,RILEVANZA,POSIZIONE,DATA_REGISTRAZIONE)");
  1492.                     query.append(" VALUES (?,?,?,?,?,?,?,?)");
  1493.                     pstmtListaEccezioniValidazione = connectionDB.prepareStatement(query.toString());
  1494.                     index = 1;
  1495.                     pstmtListaEccezioniValidazione.setString(index++,busta.getID());
  1496.                     pstmtListaEccezioniValidazione.setString(index++,tipoBusta);
  1497.                     pstmtListaEccezioniValidazione.setInt(index++,1); // eccezione arrivata dopo la validazione
  1498.                     pstmtListaEccezioniValidazione.setString(index++,eccezione.getContestoCodifica().getEngineValue());
  1499.                     pstmtListaEccezioniValidazione.setInt(index++,eccezione.getCodiceEccezione().getCodice());
  1500.                     pstmtListaEccezioniValidazione.setString(index++,eccezione.getRilevanza().getEngineValue());
  1501.                     pstmtListaEccezioniValidazione.setString(index++,eccezione.getDescrizione(this.protocolFactory));
  1502.                     pstmtListaEccezioniValidazione.setTimestamp(index++,dataRegistrazione);

  1503.                     // Add PreparedStatement
  1504.                     stateMSG.getPreparedStatement().put("INSERT(UPDATE) RegistrazioneListaEccezioni_eccezioneValidazione["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaEccezioniValidazione);
  1505.                 }
  1506.                
  1507.                 /* Lista ExtProtocolInfo */
  1508.                 if(busta.sizeProperties()>0){
  1509.                     String[] names = busta.getPropertiesNames();
  1510.                     if(names!=null && names.length>0){
  1511.                         for (int i = 0; i < names.length; i++) {
  1512.                             String name = names[i];
  1513.                             String value = busta.getProperty(name);
  1514.                            
  1515.                             query.delete(0,query.length());
  1516.                             query.append("INSERT INTO  ");
  1517.                             query.append(Costanti.LISTA_EXT_INFO);
  1518.                             query.append(" (ID_MESSAGGIO,TIPO,NOME,VALORE,DATA_REGISTRAZIONE)");
  1519.                             query.append(" VALUES (?,?,?,?,?)");
  1520.                             pstmtListaExtInfo = connectionDB.prepareStatement(query.toString());
  1521.                             index = 1;
  1522.                             pstmtListaExtInfo.setString(index++,busta.getID());
  1523.                             pstmtListaExtInfo.setString(index++,tipoBusta);
  1524.                             pstmtListaExtInfo.setString(index++,name);
  1525.                             pstmtListaExtInfo.setString(index++,value);
  1526.                             pstmtListaExtInfo.setTimestamp(index++,dataRegistrazione);

  1527.                             // Add PreparedStatement
  1528.                             stateMSG.getPreparedStatement().put("INSERT(UPDATE) RegistrazioneListaExtInfoProtocol_info["+i+"]_"+tipoBusta+"_"+busta.getID(),pstmtListaExtInfo);
  1529.                         }
  1530.                     }
  1531.                 }
  1532.             }


  1533.         } catch(Exception e) {
  1534.             String id = busta.getID();
  1535.             String errorMsg = "REPOSITORY_BUSTE, Errore di aggiornamento "+tipoBusta+"/"+id+": "+e.getMessage();
  1536.             this.log.error(errorMsg,e);
  1537.             try{
  1538.                 if(pstmtBusta != null)
  1539.                     pstmtBusta.close();
  1540.             } catch(Exception er) {
  1541.                 // Eccezione SQL.
  1542.             }
  1543.             try{
  1544.                 if(pstmtDeleteListaRiscontri!= null)
  1545.                     pstmtDeleteListaRiscontri.close();
  1546.             } catch(Exception er) {
  1547.                 // Eccezione SQL.
  1548.             }
  1549.             try{
  1550.                 if(pstmtDeleteListaTrasmissioni!= null)
  1551.                     pstmtDeleteListaTrasmissioni.close();
  1552.             } catch(Exception er) {
  1553.                 // Eccezione SQL.
  1554.             }
  1555.             try{
  1556.                 if(pstmtDeleteListaEccezioni!= null)
  1557.                     pstmtDeleteListaEccezioni.close();
  1558.             } catch(Exception er) {
  1559.                 // Eccezione SQL.
  1560.             }
  1561.             try{
  1562.                 if(pstmtDeleteListaExtInfo!= null)
  1563.                     pstmtDeleteListaExtInfo.close();
  1564.             } catch(Exception er) {
  1565.                 // Eccezione SQL.
  1566.             }
  1567.             try{
  1568.                 if(pstmtListaRiscontri != null)
  1569.                     pstmtListaRiscontri.close();
  1570.             } catch(Exception er) {
  1571.                 // Eccezione SQL.
  1572.             }
  1573.             try{
  1574.                 if(pstmtListaTrasmissioni != null)
  1575.                     pstmtListaTrasmissioni.close();
  1576.             } catch(Exception er) {
  1577.                 // Eccezione SQL.
  1578.             }
  1579.             try{
  1580.                 if(pstmtListaEccezioni != null)
  1581.                     pstmtListaEccezioni.close();
  1582.             } catch(Exception er) {
  1583.                 // Eccezione SQL.
  1584.             }
  1585.             try{
  1586.                 if(pstmtListaEccezioniValidazione != null)
  1587.                     pstmtListaEccezioniValidazione.close();
  1588.             } catch(Exception er) {
  1589.                 // Eccezione SQL.
  1590.             }
  1591.             try{
  1592.                 if(pstmtListaExtInfo != null)
  1593.                     pstmtListaExtInfo.close();
  1594.             } catch(Exception er) {
  1595.                 // Eccezione SQL.
  1596.             }
  1597.             throw new ProtocolException(errorMsg,e);
  1598.         }

  1599.         if (stateMSG instanceof StatelessMessage)   ((StatelessMessage)this.state).setBusta(busta);

  1600.     }

  1601.     /**
  1602.      * Aggiorna l'informazione di duplicati della busta.
  1603.      *
  1604.      * @param id identificativo della busta da ritornare.
  1605.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1606.      *
  1607.      */
  1608.     private void aggiornaDuplicati(String id,String tipoBusta)throws ProtocolException{

  1609.         StateMessage stateMSG = (StateMessage)this.state;
  1610.         Connection connectionDB = stateMSG.getConnectionDB();

  1611.         PreparedStatement pstmt = null;
  1612.         try{

  1613.             // Costruzione Query
  1614.             StringBuilder query = new StringBuilder();
  1615.             query.append("UPDATE ");
  1616.             query.append(Costanti.REPOSITORY);
  1617.             query.append(" SET DUPLICATI=(DUPLICATI+1) WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  1618.             pstmt = connectionDB.prepareStatement(query.toString());
  1619.             pstmt.setString(1,id);
  1620.             pstmt.setString(2,tipoBusta);

  1621.             // Add PreparedStatement
  1622.             stateMSG.getPreparedStatement().put("UPDATE aggiornaDuplicati "+tipoBusta+"_"+id,pstmt);

  1623.         } catch(Exception e) {
  1624.             String errorMsg = "REPOSITORY_BUSTE, Errore di aggiornamento informazioni pacchetti duplicati "+tipoBusta+"/"+id+": "+e.getMessage();
  1625.             try{
  1626.                 if(pstmt != null)
  1627.                     pstmt.close();
  1628.             } catch(Exception er) {
  1629.                 // close
  1630.             }
  1631.             this.log.error(errorMsg,e);
  1632.             throw new ProtocolException(errorMsg,e);
  1633.         }
  1634.     }

  1635.     /**  Aggiorna le informazioni di integrazione della busta.
  1636.      *
  1637.      * @param id identificativo della busta da ritornare.
  1638.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1639.      * @param infoIntegrazione Informazioni di integrazione
  1640.      *
  1641.      */
  1642.     public void aggiornaInfoIntegrazione(String id,String tipoBusta,Integrazione infoIntegrazione)throws ProtocolException{

  1643.         boolean registrazioneInfoIntegrazione = false;
  1644.        
  1645.         if( this.state instanceof StatefulMessage) {
  1646.             registrazioneInfoIntegrazione = true;
  1647.         }else if(this.isRichiesta && Costanti.OUTBOX.equals(tipoBusta)){
  1648.             StatelessMessage stateless = (StatelessMessage)this.state;
  1649.             Busta busta = stateless.getBusta();
  1650.             if( org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ONEWAY.equals(busta.getProfiloDiCollaborazione()) &&
  1651.                     busta.isConfermaRicezione()){
  1652.                 // Le informazioni di integrazione servono per i riscontri
  1653.                 registrazioneInfoIntegrazione = true;
  1654.             }else if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO.equals(busta.getProfiloDiCollaborazione()) &&
  1655.                     busta.getRiferimentoMessaggio()==null){
  1656.                 // Le informazioni di integrazione servono per consegnare la risposta
  1657.                 registrazioneInfoIntegrazione = true;
  1658.             }
  1659.         }
  1660.        
  1661.         if( registrazioneInfoIntegrazione ) {

  1662.             StateMessage stateMSG = (StateMessage)this.state;
  1663.             Connection connectionDB = stateMSG.getConnectionDB();

  1664.             PreparedStatement pstmt = null;
  1665.             try{

  1666.                 // Costruzione Query
  1667.                 StringBuilder query = new StringBuilder();
  1668.                 query.append("UPDATE ");
  1669.                 query.append(Costanti.REPOSITORY);
  1670.                 query.append(" SET LOCATION_PD=? , SERVIZIO_APPLICATIVO=? , MODULO_IN_ATTESA=? , SCENARIO=? WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  1671.                 pstmt = connectionDB.prepareStatement(query.toString());
  1672.                 pstmt.setString(1,infoIntegrazione.getNomePorta());
  1673.                 pstmt.setString(2,infoIntegrazione.getServizioApplicativo());
  1674.                 pstmt.setString(3,infoIntegrazione.getIdModuloInAttesa());
  1675.                 pstmt.setString(4,infoIntegrazione.getScenario());
  1676.                 pstmt.setString(5,id);
  1677.                 pstmt.setString(6,tipoBusta);

  1678.                 // Add PreparedStatement
  1679.                 stateMSG.getPreparedStatement().put("UPDATE aggiornaInformazioniIntegrazione "+tipoBusta+"_"+id,pstmt);

  1680.             } catch(Exception e) {
  1681.                 String errorMsg = "REPOSITORY_BUSTE, Errore di aggiornamento informazioni di Integrazione "+tipoBusta+"/"+id+": "+e.getMessage();
  1682.                 try{
  1683.                     if(pstmt != null)
  1684.                         pstmt.close();
  1685.                 } catch(Exception er) {
  1686.                     // close
  1687.                 }
  1688.                 this.log.error(errorMsg,e);
  1689.                 throw new ProtocolException(errorMsg,e);
  1690.             }
  1691.         }else{
  1692.             //NOP
  1693.         }
  1694.     }

  1695.     /**
  1696.      * Aggiorna il servizio applicativo di integrazione nel repositoryBuste.
  1697.      *
  1698.      * @param id identificativo della busta da ritornare.
  1699.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1700.      * @param servizioApplicativo Servizio Applicativo
  1701.      *
  1702.      */
  1703.     private void aggiornaInfoIntegrazione_ServizioApplicativo(String id,String tipoBusta,String servizioApplicativo)throws ProtocolException{

  1704.         if(this.state instanceof StatefulMessage) {

  1705.             StatefulMessage stateful = (StatefulMessage)this.state;
  1706.             Connection connectionDB = stateful.getConnectionDB();
  1707.             PreparedStatement pstmt = null;
  1708.             try{

  1709.                 // Costruzione Query
  1710.                 StringBuilder query = new StringBuilder();
  1711.                 query.append("UPDATE ");
  1712.                 query.append(Costanti.REPOSITORY);
  1713.                 query.append(" SET SERVIZIO_APPLICATIVO=? WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  1714.                 pstmt = connectionDB.prepareStatement(query.toString());
  1715.                 pstmt.setString(1,servizioApplicativo);
  1716.                 pstmt.setString(2,id);
  1717.                 pstmt.setString(3,tipoBusta);

  1718.                 // Add PreparedStatement
  1719.                 stateful.getPreparedStatement().put("UPDATE aggiornaInformazioniIntegrazione_ServizioApplicativo_"+tipoBusta+"_"+id,pstmt);

  1720.             } catch(Exception e) {
  1721.                 String errorMsg = "REPOSITORY_BUSTE, Errore di aggiornamento informazioni di Integrazione "+tipoBusta+"/"+id+" (ServizioApplicativo): "+e.getMessage();
  1722.                 try{
  1723.                     if(pstmt != null)
  1724.                         pstmt.close();
  1725.                 } catch(Exception er) {
  1726.                     // close
  1727.                 }
  1728.                 this.log.error(errorMsg,e);
  1729.                 throw new ProtocolException(errorMsg,e);
  1730.             }
  1731.         }else{

  1732.             // NOP
  1733.         }

  1734.     }

  1735.     /**
  1736.      * Aggiorna lo scenario di integrazione del Msg gestito da OpenSPCoop.
  1737.      *
  1738.      * @param id identificativo della busta da ritornare.
  1739.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1740.      * @param scenario Scenario di integrazione
  1741.      *
  1742.      */
  1743.     private void aggiornaInfoIntegrazione_Scenario(String id,String tipoBusta,String scenario)throws ProtocolException{

  1744.         if(this.state instanceof StatefulMessage) {

  1745.             StatefulMessage stateful = (StatefulMessage)this.state;
  1746.             Connection connectionDB = stateful.getConnectionDB();
  1747.             PreparedStatement pstmt = null;
  1748.             try{

  1749.                 // Costruzione Query
  1750.                 StringBuilder query = new StringBuilder();
  1751.                 query.append("UPDATE ");
  1752.                 query.append(Costanti.REPOSITORY);
  1753.                 query.append(" SET SCENARIO=? WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  1754.                 pstmt = connectionDB.prepareStatement(query.toString());
  1755.                 pstmt.setString(1,scenario);
  1756.                 pstmt.setString(2,id);
  1757.                 pstmt.setString(3,tipoBusta);

  1758.                 // Add PreparedStatement
  1759.                 stateful.getPreparedStatement().put("UPDATE aggiornaInformazioniIntegrazione_Scenario_"+tipoBusta+"_"+id,pstmt);

  1760.             } catch(Exception e) {
  1761.                 String errorMsg = "REPOSITORY_BUSTE, Errore di aggiornamento informazioni di Integrazione "+tipoBusta+"/"+id+" (Scenario): "+e.getMessage();
  1762.                 try{
  1763.                     if(pstmt != null)
  1764.                         pstmt.close();
  1765.                 } catch(Exception er) {
  1766.                     // close
  1767.                 }
  1768.                 this.log.error(errorMsg,e);
  1769.                 throw new ProtocolException(errorMsg,e);
  1770.             }
  1771.         }else{
  1772.             // NOP
  1773.         }
  1774.     }

  1775.     /**
  1776.      * Metodo che si occupa di aggiornare la collaborazione di una busta.
  1777.      *
  1778.      * @param id  Identificativo di una busta
  1779.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1780.      * @param collaborazione ID di Collaborazione di una busta
  1781.      *
  1782.      */
  1783.     private void aggiornaCollaborazione(String id,String tipoBusta,String collaborazione) throws ProtocolException{

  1784.         if(this.state instanceof StatefulMessage) {

  1785.             StatefulMessage stateful = (StatefulMessage)this.state;
  1786.             Connection connectionDB = stateful.getConnectionDB();
  1787.             PreparedStatement pstmtBusta = null;
  1788.             try{
  1789.                 // Registrazione Sequenza
  1790.                 StringBuilder query = new StringBuilder();
  1791.                 query.append("UPDATE  ");
  1792.                 query.append(Costanti.REPOSITORY);
  1793.                 query.append(" SET ");
  1794.                 query.append("COLLABORAZIONE = ?");
  1795.                 query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  1796.                 pstmtBusta = connectionDB.prepareStatement(query.toString());
  1797.                 pstmtBusta.setString(1, collaborazione);
  1798.                 pstmtBusta.setString(2,id);
  1799.                 pstmtBusta.setString(3,tipoBusta);

  1800.                 // Add PreparedStatement
  1801.                 stateful.getPreparedStatement().put("UPDATE AggiornamentoCollaborazione"+tipoBusta+"_"+id,pstmtBusta);

  1802.             } catch(Exception e) {
  1803.                 String errorMsg = "REPOSITORY_BUSTE, Errore di aggiornamento collaborazione "+tipoBusta+"/"+id+": "+e.getMessage();
  1804.                 this.log.error(errorMsg,e);
  1805.                 try{
  1806.                     if(pstmtBusta != null)
  1807.                         pstmtBusta.close();
  1808.                 } catch(Exception er) {
  1809.                     // Eccezione SQL.
  1810.                 }
  1811.                 throw new ProtocolException(errorMsg,e);
  1812.             }
  1813.         }else{

  1814.             StatelessMessage statelessMsg = ((StatelessMessage)this.state);
  1815.             statelessMsg.getBusta().setCollaborazione(collaborazione);
  1816.         }

  1817.     }

  1818.     /**
  1819.      * Metodo che si occupa di aggiornare il numero di sequenza di una busta.
  1820.      *
  1821.      * @param id  Identificativo di una busta
  1822.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1823.      * @param sequenza Numero di sequenza di una busta
  1824.      *
  1825.      */
  1826.     private void aggiornaSequenza(String id,String tipoBusta,long sequenza) throws ProtocolException{

  1827.         if(this.state instanceof StatefulMessage) {

  1828.             StatefulMessage stateful = (StatefulMessage)this.state;
  1829.             Connection connectionDB = stateful.getConnectionDB();
  1830.             PreparedStatement pstmtBusta = null;
  1831.             try{
  1832.                 // Registrazione Sequenza
  1833.                 StringBuilder query = new StringBuilder();
  1834.                 query.append("UPDATE  ");
  1835.                 query.append(Costanti.REPOSITORY);
  1836.                 query.append(" SET ");
  1837.                 query.append("SEQUENZA = ?");
  1838.                 query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  1839.                 pstmtBusta = connectionDB.prepareStatement(query.toString());
  1840.                 pstmtBusta.setLong(1, sequenza);
  1841.                 pstmtBusta.setString(2,id);
  1842.                 pstmtBusta.setString(3,tipoBusta);

  1843.                 // Add PreparedStatement
  1844.                 stateful.getPreparedStatement().put("UPDATE AggiornamentoSequenza"+tipoBusta+"_"+id,pstmtBusta);

  1845.             } catch(Exception e) {
  1846.                 String errorMsg = "REPOSITORY_BUSTE, Errore di aggiornamento sequenza "+tipoBusta+"/"+id+": "+e.getMessage();
  1847.                 this.log.error(errorMsg,e);
  1848.                 try{
  1849.                     if(pstmtBusta != null)
  1850.                         pstmtBusta.close();
  1851.                 } catch(Exception er) {
  1852.                     // Eccezione SQL.
  1853.                 }
  1854.                 throw new ProtocolException(errorMsg,e);
  1855.             }

  1856.         }else{

  1857.             StatelessMessage statelessMsg = ((StatelessMessage)this.state);
  1858.             statelessMsg.getBusta().setSequenza(sequenza);
  1859.         }

  1860.     }

  1861.     /**
  1862.      * Ritorna l'informazione se una busta e' gia stata precedentemente registrata.
  1863.      *
  1864.      * @param id identificativo della busta da ritornare.
  1865.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1866.      * @return true se e' presente la busta richiesta.
  1867.      *
  1868.      */
  1869.     public boolean isRegistrata(String id, String tipoBusta) throws ProtocolException {

  1870.         Connection connectionDB = ((StateMessage) this.state).getConnectionDB();

  1871.         PreparedStatement pstmt = null;
  1872.         ResultSet rs = null;
  1873.         try {   // busta

  1874.             StringBuilder query = new StringBuilder();
  1875.             query.append("select ID_MESSAGGIO from ");
  1876.             query.append(Costanti.REPOSITORY);
  1877.             query.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  1878.             pstmt = connectionDB.prepareStatement(query.toString());
  1879.             pstmt.setString(1, id);
  1880.             pstmt.setString(2, tipoBusta);

  1881.             // Esecuzione comando SQL
  1882.             rs = pstmt.executeQuery();
  1883.             if (rs == null) {
  1884.                 throw new ProtocolException("RS Null?");
  1885.             }
  1886.             boolean value = rs.next();

  1887.             rs.close();
  1888.             pstmt.close();

  1889.             return value;


  1890.         } catch (Exception e) {
  1891.             String errorMsg = "REPOSITORY_BUSTE, Errore durante isRegistrata " + tipoBusta + "/" + id + ": " + e.getMessage();
  1892.             this.log.error(errorMsg, e);
  1893.             try {
  1894.                 if (rs != null) {
  1895.                     rs.close();
  1896.                 }
  1897.             } catch (Exception er) {
  1898.                 // Eccezione SQL.
  1899.             }
  1900.             try {
  1901.                 if (pstmt != null) {
  1902.                     pstmt.close();
  1903.                 }
  1904.             } catch (Exception er) {
  1905.                 // Eccezione SQL.
  1906.             }
  1907.             throw new ProtocolException(errorMsg, e);
  1908.         }


  1909.     }





  1910.     /**
  1911.      * Metodo che si occupa di ritornare un oggetto {@link org.openspcoop2.protocol.sdk.Busta} contenente
  1912.      * le informazioni di una busta, precedentemente salvata,
  1913.      * prelevandola dalla tabella delle buste. Alla busta, al momento della registrazione,
  1914.      * e' stato associato l'identificativo della busta, quindi attraverso esso sara' possibile trovarlo nella History.
  1915.      *
  1916.      * @param id identificativo della busta da ritornare.
  1917.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  1918.      * @return un oggetto {@link org.openspcoop2.protocol.sdk.Busta} se e' presente la busta richiesta.
  1919.      *
  1920.      */
  1921.     private Busta getBusta(String id, String tipoBusta) throws ProtocolException{
  1922.         return getBusta(id, tipoBusta, false);
  1923.     }
  1924.     private Busta getBusta(String id, String tipoBusta, boolean readServizioApplicativoFruitore) throws ProtocolException{

  1925.         if(this.state instanceof StatefulMessage) {

  1926.             StatefulMessage stateful = (StatefulMessage)this.state;
  1927.             Connection connectionDB = stateful.getConnectionDB();

  1928.             PreparedStatement pstmt = null;
  1929.             ResultSet rs = null;
  1930.             try{

  1931.                 // busta

  1932.                 StringBuilder query = new StringBuilder();
  1933.                 query.append("select * from ");
  1934.                 query.append(Costanti.REPOSITORY);
  1935.                 query.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");

  1936.                 pstmt = connectionDB.prepareStatement(query.toString());
  1937.                 pstmt.setString(1,id);
  1938.                 pstmt.setString(2,tipoBusta);

  1939.                 // Esecuzione comando SQL
  1940.                 rs = pstmt.executeQuery();
  1941.                 if(rs == null) {
  1942.                     throw new ProtocolException("RS Null?");
  1943.                 }
  1944.                 if (rs.next() == false) {
  1945.                     throw new ProtocolException("Busta non trovata");
  1946.                 }

  1947.                 // Lettura parametri busta
  1948.                 Busta busta = new Busta(rs.getString("PROTOCOLLO"));
  1949.                 if(this.protocolFactory==null){
  1950.                     if(busta.getProtocollo()!=null){
  1951.                         this.protocolFactory = ProtocolFactoryManager.getInstance().getProtocolFactoryByName(busta.getProtocollo());
  1952.                     }
  1953.                     else{
  1954.                         throw new ProtocolException("Protocol unknown");
  1955.                     }
  1956.                 }
  1957.                 busta.setID(rs.getString("ID_MESSAGGIO"));
  1958.                 busta.setTipoMittente(rs.getString("TIPO_MITTENTE"));
  1959.                 busta.setMittente(rs.getString("MITTENTE"));
  1960.                 busta.setIdentificativoPortaMittente(rs.getString("IDPORTA_MITTENTE"));
  1961.                 busta.setIndirizzoMittente(rs.getString("IND_TELEMATICO_MITT"));
  1962.                 //log.info("TipoMitt["+busta.getTipoMittente()+"] Mitt["+ busta.getMittente()+"]");
  1963.                 busta.setTipoDestinatario(rs.getString("TIPO_DESTINATARIO"));
  1964.                 busta.setDestinatario(rs.getString("DESTINATARIO"));
  1965.                 busta.setIdentificativoPortaDestinatario(rs.getString("IDPORTA_DESTINATARIO"));
  1966.                 busta.setIndirizzoDestinatario(rs.getString("IND_TELEMATICO_DEST"));
  1967.                 //log.info("TipoDest["+busta.getTipoDestinatario()+"] DEst["+ busta.getDestinatario()+"]");
  1968.                 busta.setVersioneServizio(rs.getInt("VERSIONE_SERVIZIO"));
  1969.                 busta.setServizio(rs.getString("SERVIZIO"));
  1970.                 busta.setTipoServizio(rs.getString("TIPO_SERVIZIO"));
  1971.                 busta.setAzione(rs.getString("AZIONE"));
  1972.                 //log.info("Servizio["+busta.getServizio()+"] Azione["+ busta.getAzione()+"]");
  1973.                 String profiloCollaborazione = rs.getString("PROFILO_DI_COLLABORAZIONE");
  1974.                 if(profiloCollaborazione!=null){
  1975.                     busta.setProfiloDiCollaborazione(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.toProfiloDiCollaborazione(profiloCollaborazione));
  1976.                 }
  1977.                 busta.setServizioCorrelato(rs.getString("SERVIZIO_CORRELATO"));
  1978.                 busta.setTipoServizioCorrelato(rs.getString("TIPO_SERVIZIO_CORRELATO"));
  1979.                 busta.setCollaborazione(rs.getString("COLLABORAZIONE"));
  1980.                 busta.setSequenza(rs.getLong("SEQUENZA"));
  1981.                 //log.info("COLL["+ busta.getCollaborazione()+"] SEQ["+busta.getSequenza()+"]");

  1982.                 if(rs.getInt("INOLTRO_SENZA_DUPLICATI") != 0)
  1983.                     busta.setInoltro(Inoltro.SENZA_DUPLICATI,this.protocolFactory.createTraduttore().toString(Inoltro.SENZA_DUPLICATI));
  1984.                 else
  1985.                     busta.setInoltro(Inoltro.CON_DUPLICATI,this.protocolFactory.createTraduttore().toString(Inoltro.CON_DUPLICATI));
  1986.                 //log.info("INOLTRO["+busta.getInoltro()+"]");
  1987.                 if(rs.getInt("CONFERMA_RICEZIONE") != 0)
  1988.                     busta.setConfermaRicezione(true);
  1989.                 else
  1990.                     busta.setConfermaRicezione(false);
  1991.                 //log.info("ConfermaRicezione["+busta.getConfermaRicezione()+"]");
  1992.                 busta.setOraRegistrazione(rs.getTimestamp("ORA_REGISTRAZIONE"));
  1993.                 TipoOraRegistrazione tipoOraRegistrazione = TipoOraRegistrazione.toTipoOraRegistrazione(rs.getString("TIPO_ORA_REGISTRAZIONE"));
  1994.                 busta.setTipoOraRegistrazione(tipoOraRegistrazione,this.protocolFactory.createTraduttore().toString(tipoOraRegistrazione));
  1995.                 busta.setRiferimentoMessaggio(rs.getString("RIFERIMENTO_MESSAGGIO"));
  1996.                 busta.setScadenza(rs.getTimestamp("SCADENZA_BUSTA"));
  1997.                
  1998.                 if(readServizioApplicativoFruitore) {
  1999.                     busta.setServizioApplicativoFruitore(rs.getString("SERVIZIO_APPLICATIVO"));
  2000.                 }

  2001.                 rs.close();
  2002.                 pstmt.close();


  2003.                 // Lista Tramsmissioni
  2004.                 query.delete(0,query.length());
  2005.                 query.append("select * from ");
  2006.                 query.append(Costanti.LISTA_TRASMISSIONI);
  2007.                 query.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");

  2008.                 pstmt = connectionDB.prepareStatement(query.toString());
  2009.                 pstmt.setString(1,id);
  2010.                 pstmt.setString(2,tipoBusta);

  2011.                 // Esecuzione comando SQL
  2012.                 rs = pstmt.executeQuery();
  2013.                 if(rs == null) {
  2014.                     throw new ProtocolException("RS Null?");
  2015.                 }


  2016.                 // Lettura parametri busta
  2017.                 while(rs.next()){
  2018.                     Trasmissione trasmissione = new Trasmissione();
  2019.                     trasmissione.setOrigine(rs.getString("ORIGINE"));
  2020.                     trasmissione.setTipoOrigine(rs.getString("TIPO_ORIGINE"));
  2021.                     trasmissione.setDestinazione(rs.getString("DESTINAZIONE"));
  2022.                     trasmissione.setTipoDestinazione(rs.getString("TIPO_DESTINAZIONE"));
  2023.                     trasmissione.setOraRegistrazione(rs.getTimestamp("ORA_REGISTRAZIONE"));
  2024.                     trasmissione.setTempo(TipoOraRegistrazione.toTipoOraRegistrazione(rs.getString("TIPO_ORA_REGISTRAZIONE")));
  2025.                     busta.addTrasmissione(trasmissione);
  2026.                 }

  2027.                 rs.close();
  2028.                 pstmt.close();


  2029.                 //  Lista Riscontri
  2030.                 query.delete(0,query.length());
  2031.                 query.append("select * from ");
  2032.                 query.append(Costanti.LISTA_RISCONTRI);
  2033.                 query.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");

  2034.                 pstmt = connectionDB.prepareStatement(query.toString());
  2035.                 pstmt.setString(1,id);
  2036.                 pstmt.setString(2,tipoBusta);

  2037.                 // Esecuzione comando SQL
  2038.                 rs = pstmt.executeQuery();
  2039.                 if(rs == null) {
  2040.                     throw new ProtocolException("RS Null?");
  2041.                 }


  2042.                 // Lettura parametri busta
  2043.                 while(rs.next()){
  2044.                     Riscontro riscontro = new Riscontro();
  2045.                     riscontro.setID(rs.getString("ID_RISCONTRO"));
  2046.                     riscontro.setRicevuta(rs.getString("RICEVUTA"));
  2047.                     riscontro.setOraRegistrazione(rs.getTimestamp("ORA_REGISTRAZIONE"));
  2048.                     riscontro.setTipoOraRegistrazione(TipoOraRegistrazione.toTipoOraRegistrazione(rs.getString("TIPO_ORA_REGISTRAZIONE")));
  2049.                     busta.addRiscontro(riscontro);
  2050.                 }

  2051.                 rs.close();
  2052.                 pstmt.close();


  2053.                 // Lista Eccezioni
  2054.                 query.delete(0,query.length());
  2055.                 query.append("select * from ");
  2056.                 query.append(Costanti.LISTA_ECCEZIONI);
  2057.                 query.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ? AND VALIDAZIONE=0");

  2058.                 pstmt = connectionDB.prepareStatement(query.toString());
  2059.                 pstmt.setString(1,id);
  2060.                 pstmt.setString(2,tipoBusta);

  2061.                 // Esecuzione comando SQL
  2062.                 rs = pstmt.executeQuery();
  2063.                 if(rs == null) {
  2064.                     throw new ProtocolException("RS Null?");
  2065.                 }


  2066.                 // Lettura parametri busta
  2067.                 while(rs.next()){
  2068.                     Eccezione eccezione = Eccezione.newEccezione();
  2069.                     eccezione.setContestoCodifica(ContestoCodificaEccezione.toContestoCodificaEccezione(rs.getString("CONTESTO")));
  2070.                     eccezione.setCodiceEccezione(CodiceErroreCooperazione.toCodiceErroreCooperazione((rs.getInt("CODICE"))));
  2071.                     eccezione.setRilevanza(LivelloRilevanza.toLivelloRilevanza(rs.getString("RILEVANZA")));
  2072.                     eccezione.setDescrizione(rs.getString("POSIZIONE"));
  2073.                     busta.addEccezione(eccezione);
  2074.                 }

  2075.                 rs.close();
  2076.                 pstmt.close();

  2077.                
  2078.                
  2079.                 // Lista ExtInfo
  2080.                 query.delete(0,query.length());
  2081.                 query.append("select * from ");
  2082.                 query.append(Costanti.LISTA_EXT_INFO);
  2083.                 query.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");

  2084.                 pstmt = connectionDB.prepareStatement(query.toString());
  2085.                 pstmt.setString(1,id);
  2086.                 pstmt.setString(2,tipoBusta);

  2087.                 // Esecuzione comando SQL
  2088.                 rs = pstmt.executeQuery();
  2089.                 if(rs == null) {
  2090.                     throw new ProtocolException("RS Null?");
  2091.                 }


  2092.                 // Lettura parametri busta
  2093.                 while(rs.next()){
  2094.                     busta.addProperty(rs.getString("NOME"), rs.getString("VALORE"));
  2095.                 }

  2096.                 rs.close();
  2097.                 pstmt.close();
  2098.                
  2099.                
  2100.                

  2101.                 return busta;


  2102.             } catch(Exception e) {
  2103.                 String errorMsg = "REPOSITORY_BUSTE, Errore durante la getBusta "+tipoBusta+"/"+id+": "+e.getMessage();
  2104.                 this.log.error(errorMsg,e);
  2105.                 try{
  2106.                     if(rs!=null)
  2107.                         rs.close();
  2108.                 } catch(Exception er) {
  2109.                     // Eccezione SQL.
  2110.                 }
  2111.                 try{
  2112.                     if(pstmt != null)
  2113.                         pstmt.close();
  2114.                 } catch(Exception er) {
  2115.                     // Eccezione SQL.
  2116.                 }
  2117.                 throw new ProtocolException(errorMsg,e);
  2118.             }
  2119.         }else{
  2120.             StatelessMessage statelessMsg = ((StatelessMessage)this.state);
  2121.             return statelessMsg.getBusta();
  2122.         }

  2123.     }

  2124.     /**
  2125.      * Metodo che si occupa di ritornare un oggetto contenente errori di validazione
  2126.      * {@link org.openspcoop2.protocol.sdk.Eccezione} avvenuti durante la validazione di una busta.
  2127.      *
  2128.      * @param id identificativo della busta da ritornare.
  2129.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2130.      * @return un oggetto List&lt;{@link org.openspcoop2.protocol.sdk.Eccezione}&gt; se e' presente la busta richiesta.
  2131.      *
  2132.      */
  2133.     private List<Eccezione> getErrors(String id,String tipoBusta) throws ProtocolException{

  2134.         if(this.state instanceof StatefulMessage) {

  2135.             StatefulMessage stateful = (StatefulMessage)this.state;
  2136.             Connection connectionDB = stateful.getConnectionDB();

  2137.             PreparedStatement pstmt = null;
  2138.             ResultSet rs = null;
  2139.             List<Eccezione> errors = new ArrayList<>();
  2140.             try{

  2141.                 // Costruzione Query
  2142.                 StringBuilder query = new StringBuilder();
  2143.                 query.append("select * from ");
  2144.                 query.append(Costanti.LISTA_ECCEZIONI);
  2145.                 query.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ? AND VALIDAZIONE=1");

  2146.                 pstmt = connectionDB.prepareStatement(query.toString());
  2147.                 pstmt.setString(1,id);
  2148.                 pstmt.setString(2,tipoBusta);

  2149.                 // Esecuzione comando SQL
  2150.                 rs = pstmt.executeQuery();
  2151.                 if(rs == null) {
  2152.                     throw new ProtocolException("RS Null?");
  2153.                 }


  2154.                 // Lettura parametri busta
  2155.                 while(rs.next()){
  2156.                     Eccezione eccezione = Eccezione.newEccezione();
  2157.                     eccezione.setContestoCodifica(ContestoCodificaEccezione.toContestoCodificaEccezione(rs.getString("CONTESTO")));
  2158.                     eccezione.setCodiceEccezione(CodiceErroreCooperazione.toCodiceErroreCooperazione(rs.getInt("CODICE")));
  2159.                     eccezione.setRilevanza(LivelloRilevanza.toLivelloRilevanza(rs.getString("RILEVANZA")));
  2160.                     eccezione.setDescrizione(rs.getString("POSIZIONE"));
  2161.                     errors.add(eccezione);
  2162.                 }

  2163.                 rs.close();
  2164.                 pstmt.close();

  2165.                 return errors;


  2166.             } catch(Exception e) {
  2167.                 String errorMsg = "REPOSITORY_BUSTE, Errore durante la getErrors "+tipoBusta+"/"+id+": "+e.getMessage();
  2168.                 this.log.error(errorMsg,e);
  2169.                 try{
  2170.                     if(rs!=null)
  2171.                         rs.close();
  2172.                 } catch(Exception er) {
  2173.                     // Eccezione SQL.
  2174.                 }
  2175.                 try{
  2176.                     if(pstmt != null)
  2177.                         pstmt.close();
  2178.                 } catch(Exception er) {
  2179.                     // Eccezione SQL.
  2180.                 }
  2181.                 throw new ProtocolException(errorMsg,e);
  2182.             }
  2183.         }else{
  2184.             // NOP
  2185.             return null;
  2186.         }

  2187.     }

  2188.     /**
  2189.      * Ritorna alcuni campi associata alla busta.
  2190.      *
  2191.      * @param id identificativo della busta.
  2192.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2193.      * @return alcuni valori della busta
  2194.      *
  2195.      */
  2196.     private Busta getSomeValues(String id,String tipoBusta, LetturaParametriBusta parametri,boolean forzaLetturaSuDatabase, Date dataRegistrazione) throws ProtocolException{

  2197.         if((this.state instanceof StatefulMessage) || (forzaLetturaSuDatabase)) {

  2198.             StateMessage state = (StateMessage)this.state;
  2199.             Connection connectionDB = state.getConnectionDB();

  2200.             PreparedStatement pstmt = null;
  2201.             ResultSet rs = null;
  2202.             String protocollo = null;
  2203.             if(this.protocolFactory!=null){
  2204.                 protocollo = this.protocolFactory.getProtocol();
  2205.             }
  2206.                    
  2207.             Busta busta = new Busta(protocollo);
  2208.             try{
  2209.                 // Costruzione Query
  2210.                 StringBuilder bf = new StringBuilder();
  2211.                 bf.append("SELECT ");
  2212.                 bf.append("PROTOCOLLO");
  2213.                 boolean first = false;
  2214.                 if(parametri.isMittente()){
  2215.                     if(first==false)
  2216.                         bf.append(",");
  2217.                     else
  2218.                         first = false;
  2219.                     bf.append("MITTENTE,TIPO_MITTENTE,IDPORTA_MITTENTE");
  2220.                     first = false;
  2221.                 }
  2222.                 if(parametri.isDestinatario()){
  2223.                     if(first==false)
  2224.                         bf.append(",");
  2225.                     else
  2226.                         first = false;
  2227.                     bf.append("DESTINATARIO,TIPO_DESTINATARIO,IDPORTA_DESTINATARIO");
  2228.                 }
  2229.                 if(parametri.isIndirizziTelematici()){
  2230.                     if(first==false)
  2231.                         bf.append(",");
  2232.                     else
  2233.                         first = false;
  2234.                     bf.append("IND_TELEMATICO_MITT,IND_TELEMATICO_DEST");
  2235.                 }
  2236.                 if(parametri.isServizio()){
  2237.                     if(first==false)
  2238.                         bf.append(",");
  2239.                     else
  2240.                         first = false;
  2241.                     bf.append("SERVIZIO,TIPO_SERVIZIO,VERSIONE_SERVIZIO");
  2242.                 }
  2243.                 if(parametri.isAzione()){
  2244.                     if(first==false)
  2245.                         bf.append(",");
  2246.                     else
  2247.                         first = false;
  2248.                     bf.append("AZIONE");
  2249.                 }
  2250.                 if(parametri.isProfiloDiCollaborazione()){
  2251.                     if(first==false)
  2252.                         bf.append(",");
  2253.                     else
  2254.                         first = false;
  2255.                     bf.append("PROFILO_DI_COLLABORAZIONE");
  2256.                 }
  2257.                 if(parametri.isServizioCorrelato()){
  2258.                     if(first==false)
  2259.                         bf.append(",");
  2260.                     else
  2261.                         first = false;
  2262.                     bf.append("SERVIZIO_CORRELATO,TIPO_SERVIZIO_CORRELATO");
  2263.                 }
  2264.                 if(parametri.isCollaborazione()){
  2265.                     if(first==false)
  2266.                         bf.append(",");
  2267.                     else
  2268.                         first = false;
  2269.                     bf.append("COLLABORAZIONE");
  2270.                 }
  2271.                 if(parametri.isSequenza()){
  2272.                     if(first==false)
  2273.                         bf.append(",");
  2274.                     else
  2275.                         first = false;
  2276.                     bf.append("SEQUENZA");
  2277.                 }
  2278.                 if(parametri.isProfiloTrasmissione()){
  2279.                     if(first==false)
  2280.                         bf.append(",");
  2281.                     else
  2282.                         first = false;
  2283.                     bf.append("INOLTRO_SENZA_DUPLICATI,CONFERMA_RICEZIONE");
  2284.                 }
  2285.                 if(parametri.isOraRegistrazione()){
  2286.                     if(first==false)
  2287.                         bf.append(",");
  2288.                     else
  2289.                         first = false;
  2290.                     bf.append("ORA_REGISTRAZIONE,TIPO_ORA_REGISTRAZIONE");
  2291.                 }
  2292.                 if(parametri.isRiferimentoMessaggio()){
  2293.                     if(first==false)
  2294.                         bf.append(",");
  2295.                     else
  2296.                         first = false;
  2297.                     bf.append("RIFERIMENTO_MESSAGGIO");
  2298.                 }
  2299.                 if(parametri.isScadenza()){
  2300.                     if(first==false)
  2301.                         bf.append(",");
  2302.                     else
  2303.                         first = false;
  2304.                     bf.append("SCADENZA_BUSTA");
  2305.                 }
  2306.                 bf.append(" FROM ");
  2307.                 bf.append(Costanti.REPOSITORY);
  2308.                 bf.append(" WHERE ");
  2309.                 if(dataRegistrazione!=null) {
  2310.                     bf.append("(DATA_REGISTRAZIONE BETWEEN ? AND ?) AND ");
  2311.                 }
  2312.                 bf.append("ID_MESSAGGIO=? AND TIPO=?");

  2313.                 //log.debug("Query: "+query);
  2314.                 pstmt = connectionDB.prepareStatement(bf.toString());
  2315.                 int index = 1;
  2316.                
  2317.                 Timestamp leftValue = null;
  2318.                 Timestamp rightValue = null;
  2319.                 if(dataRegistrazione!=null) {
  2320.                     leftValue = new Timestamp(dataRegistrazione.getTime() - (1000*60*5));
  2321.                     rightValue = new Timestamp(dataRegistrazione.getTime() + (1000*60*5));
  2322.                     pstmt.setTimestamp(index++,leftValue);
  2323.                     pstmt.setTimestamp(index++,rightValue);
  2324.                 }
  2325.                
  2326.                 pstmt.setString(index++,id);
  2327.                 pstmt.setString(index++,tipoBusta);
  2328.                 rs = pstmt.executeQuery();
  2329.                 if(rs == null) {
  2330.                     throw new ProtocolException("RS Null?");
  2331.                 }
  2332.                 if(rs.next()){
  2333.                     String protocolloRead = rs.getString("PROTOCOLLO");
  2334.                     if(busta.getProtocollo()==null){
  2335.                         busta.setProtocollo(protocolloRead);
  2336.                     }
  2337.                     if(this.protocolFactory==null){
  2338.                         this.protocolFactory = ProtocolFactoryManager.getInstance().getProtocolFactoryByName(protocolloRead);
  2339.                     }
  2340.                     if(parametri.isMittente()){
  2341.                         busta.setTipoMittente(rs.getString("TIPO_MITTENTE"));
  2342.                         busta.setMittente(rs.getString("MITTENTE"));
  2343.                         busta.setIdentificativoPortaMittente(rs.getString("IDPORTA_MITTENTE"));
  2344.                     }
  2345.                     if(parametri.isDestinatario()){
  2346.                         busta.setTipoDestinatario(rs.getString("TIPO_DESTINATARIO"));
  2347.                         busta.setDestinatario(rs.getString("DESTINATARIO"));
  2348.                         busta.setIdentificativoPortaDestinatario(rs.getString("IDPORTA_DESTINATARIO"));
  2349.                     }
  2350.                     if(parametri.isIndirizziTelematici()){
  2351.                         busta.setIndirizzoMittente(rs.getString("IND_TELEMATICO_MITT"));
  2352.                         busta.setIndirizzoDestinatario(rs.getString("IND_TELEMATICO_DEST"));
  2353.                     }
  2354.                     if(parametri.isServizio()){
  2355.                         busta.setTipoServizio(rs.getString("TIPO_SERVIZIO"));
  2356.                         busta.setServizio(rs.getString("SERVIZIO"));
  2357.                         busta.setVersioneServizio(rs.getInt("VERSIONE_SERVIZIO"));
  2358.                     }
  2359.                     if(parametri.isAzione()){
  2360.                         busta.setAzione(rs.getString("AZIONE"));
  2361.                     }
  2362.                     if(parametri.isProfiloDiCollaborazione()){
  2363.                         busta.setProfiloDiCollaborazione(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.toProfiloDiCollaborazione(rs.getString("PROFILO_DI_COLLABORAZIONE")));
  2364.                     }
  2365.                     if(parametri.isServizioCorrelato()){
  2366.                         busta.setTipoServizioCorrelato(rs.getString("TIPO_SERVIZIO_CORRELATO"));
  2367.                         busta.setServizioCorrelato(rs.getString("SERVIZIO_CORRELATO"));
  2368.                     }
  2369.                     if(parametri.isCollaborazione()){
  2370.                         busta.setCollaborazione(rs.getString("COLLABORAZIONE"));
  2371.                     }
  2372.                     if(parametri.isSequenza()){
  2373.                         busta.setSequenza(rs.getLong("SEQUENZA"));
  2374.                     }
  2375.                     if(parametri.isProfiloTrasmissione()){
  2376.                         if(rs.getInt("INOLTRO_SENZA_DUPLICATI") != 0)
  2377.                             busta.setInoltro(Inoltro.SENZA_DUPLICATI,this.protocolFactory.createTraduttore().toString(Inoltro.SENZA_DUPLICATI));
  2378.                         else
  2379.                             busta.setInoltro(Inoltro.CON_DUPLICATI,this.protocolFactory.createTraduttore().toString(Inoltro.CON_DUPLICATI));
  2380.                         //log.info("INOLTRO["+busta.getInoltro()+"]");
  2381.                         if(rs.getInt("CONFERMA_RICEZIONE") != 0)
  2382.                             busta.setConfermaRicezione(true);
  2383.                         else
  2384.                             busta.setConfermaRicezione(false);
  2385.                     }
  2386.                     if(parametri.isOraRegistrazione()){
  2387.                         busta.setOraRegistrazione(rs.getTimestamp("ORA_REGISTRAZIONE"));
  2388.                         TipoOraRegistrazione tipoOraRegistrazione = TipoOraRegistrazione.toTipoOraRegistrazione(rs.getString("TIPO_ORA_REGISTRAZIONE"));
  2389.                         busta.setTipoOraRegistrazione(tipoOraRegistrazione,this.protocolFactory.createTraduttore().toString(tipoOraRegistrazione));
  2390.                     }
  2391.                     if(parametri.isRiferimentoMessaggio()){
  2392.                         busta.setRiferimentoMessaggio(rs.getString("RIFERIMENTO_MESSAGGIO"));
  2393.                     }
  2394.                     if(parametri.isScadenza()){
  2395.                         busta.setScadenza(rs.getTimestamp("SCADENZA_BUSTA"));
  2396.                     }
  2397.                 }else{
  2398.                     throw new ProtocolException("Busta non trovata");
  2399.                 }
  2400.                 rs.close();
  2401.                 pstmt.close();

  2402.                 return busta;

  2403.             } catch(Exception e) {
  2404.                 String errorMsg = "REPOSITORY_BUSTE, Errore  getSomeValues "+tipoBusta+"/"+id+": "+e.getMessage();
  2405.                 try{
  2406.                     if(rs != null)
  2407.                         rs.close();
  2408.                 } catch(Exception er) {
  2409.                     // close
  2410.                 }
  2411.                 try{
  2412.                     if(pstmt != null)
  2413.                         pstmt.close();
  2414.                 } catch(Exception er) {
  2415.                     // close
  2416.                 }
  2417.                 this.log.error(errorMsg,e);
  2418.                 throw new ProtocolException(errorMsg,e);
  2419.             }
  2420.         }else{
  2421.             StatelessMessage statelessMsg = ((StatelessMessage)this.state);
  2422.             Busta busta = statelessMsg.getBusta().newInstance(); // Per evitare che venga modificato l'oggetto richiesta durante il salvataggio.
  2423.             if(parametri.isMittente()==false){
  2424.                 busta.setTipoMittente(null);
  2425.                 busta.setMittente(null);
  2426.             }
  2427.             if(parametri.isDestinatario()==false){
  2428.                 busta.setTipoDestinatario(null);
  2429.                 busta.setDestinatario(null);
  2430.             }
  2431.             if(parametri.isIndirizziTelematici()==false){
  2432.                 busta.setIndirizzoMittente(null);
  2433.                 busta.setIndirizzoDestinatario(null);
  2434.             }
  2435.             if(parametri.isServizio()==false){
  2436.                 busta.setTipoServizio(null);
  2437.                 busta.setServizio(null);
  2438.             }
  2439.             if(parametri.isAzione()==false){
  2440.                 busta.setAzione(null);
  2441.             }
  2442.             if(parametri.isProfiloDiCollaborazione()==false){
  2443.                 busta.setProfiloDiCollaborazione(null);
  2444.             }
  2445.             if(parametri.isServizioCorrelato()==false){
  2446.                 busta.setTipoServizioCorrelato(null);
  2447.                 busta.setServizioCorrelato(null);
  2448.             }
  2449.             if(parametri.isCollaborazione()==false){
  2450.                 busta.setCollaborazione(null);
  2451.             }
  2452.             if(parametri.isSequenza()==false){
  2453.                 busta.setSequenza(-1);
  2454.             }
  2455.             if(parametri.isProfiloTrasmissione()==false){
  2456.                 busta.setInoltro(null,null);
  2457.                 busta.setConfermaRicezione(false);
  2458.             }
  2459.             if(parametri.isOraRegistrazione()==false){
  2460.                 busta.setOraRegistrazione(null);
  2461.                 busta.setTipoOraRegistrazione(null,null);
  2462.             }
  2463.             if(parametri.isRiferimentoMessaggio()==false){
  2464.                 busta.setRiferimentoMessaggio(null);
  2465.             }
  2466.             if(parametri.isScadenza()==false){
  2467.                 busta.setScadenza(null);
  2468.             }
  2469.             for(int i=0;i<busta.sizeListaEccezioni();i++){
  2470.                 busta.removeEccezione(i);
  2471.             }
  2472.             for(int i=0;i<busta.sizeListaTrasmissioni();i++){
  2473.                 busta.removeTrasmissione(i);
  2474.             }
  2475.             for(int i=0;i<busta.sizeListaRiscontri();i++){
  2476.                 busta.removeRiscontro(i);
  2477.             }
  2478.             if(busta.sizeProperties()>0){
  2479.                 String [] pNames = busta.getPropertiesNames();
  2480.                 for(int i=0; i<pNames.length; i++){
  2481.                     busta.removeProperty(pNames[i]);
  2482.                 }
  2483.             }
  2484.            
  2485.            
  2486.             return busta;
  2487.         }
  2488.     }

  2489.     /**
  2490.      * Ritorna la collaborazione associata alla busta.
  2491.      *
  2492.      * @param id identificativo della busta.
  2493.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2494.      * @return Collaborazione associata alla busta
  2495.      *
  2496.      */
  2497.     private String getCollaborazione(String id,String tipoBusta) throws ProtocolException{

  2498.         if(this.state instanceof StatefulMessage) {

  2499.             StatefulMessage stateful = (StatefulMessage)this.state;
  2500.             Connection connectionDB = stateful.getConnectionDB();
  2501.             PreparedStatement pstmt = null;
  2502.             ResultSet rs = null;
  2503.             try{
  2504.                 // Costruzione Query
  2505.                 String query = "SELECT COLLABORAZIONE FROM "+Costanti.REPOSITORY+" WHERE ID_MESSAGGIO=? AND TIPO=?";
  2506.                 //log.debug("Query: "+query);
  2507.                 pstmt = connectionDB.prepareStatement(query);
  2508.                 pstmt.setString(1,id);
  2509.                 pstmt.setString(2,tipoBusta);
  2510.                 rs = pstmt.executeQuery();
  2511.                 if(rs == null) {
  2512.                     throw new ProtocolException("RS Null?");
  2513.                 }
  2514.                 String collaborazione = null;
  2515.                 if(rs.next()){
  2516.                     collaborazione = rs.getString("COLLABORAZIONE");
  2517.                 }
  2518.                 rs.close();
  2519.                 pstmt.close();

  2520.                 return collaborazione;

  2521.             } catch(Exception e) {
  2522.                 String errorMsg = "REPOSITORY_BUSTE, Errore  getCollaborazione "+tipoBusta+"/"+id+": "+e.getMessage();
  2523.                 try{
  2524.                     if(rs != null)
  2525.                         rs.close();
  2526.                 } catch(Exception er) {
  2527.                     // close
  2528.                 }
  2529.                 try{
  2530.                     if(pstmt != null)
  2531.                         pstmt.close();
  2532.                 } catch(Exception er) {
  2533.                     // close
  2534.                 }
  2535.                 this.log.error(errorMsg,e);
  2536.                 throw new ProtocolException(errorMsg,e);
  2537.             }
  2538.         }else{
  2539.             StatelessMessage statelessMsg = ((StatelessMessage)this.state);
  2540.             Busta busta = statelessMsg.getBusta();
  2541.             return busta.getCollaborazione();
  2542.         }
  2543.     }

  2544.     /**
  2545.      * Ritorna la collaborazione associata alla busta.
  2546.      *
  2547.      * @param id identificativo della busta.
  2548.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2549.      * @return Collaborazione associata alla busta
  2550.      *
  2551.      */
  2552.     private org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione getProfiloCollaborazione(String id,String tipoBusta) throws ProtocolException{

  2553.         if(this.state instanceof StatefulMessage) {

  2554.             StatefulMessage stateful = (StatefulMessage)this.state;
  2555.             Connection connectionDB = stateful.getConnectionDB();
  2556.             PreparedStatement pstmt = null;
  2557.             ResultSet rs = null;
  2558.             try{
  2559.                 // Costruzione Query
  2560.                 String query = "SELECT PROFILO_DI_COLLABORAZIONE FROM "+Costanti.REPOSITORY+" WHERE ID_MESSAGGIO=? AND TIPO=?";
  2561.                 //log.debug("Query: "+query);
  2562.                 pstmt = connectionDB.prepareStatement(query);
  2563.                 pstmt.setString(1,id);
  2564.                 pstmt.setString(2,tipoBusta);
  2565.                 rs = pstmt.executeQuery();
  2566.                 if(rs == null) {
  2567.                     throw new ProtocolException("RS Null?");
  2568.                 }
  2569.                 org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione profiloCollaborazione = null;
  2570.                 if(rs.next()){
  2571.                     profiloCollaborazione = org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.toProfiloDiCollaborazione(rs.getString("PROFILO_DI_COLLABORAZIONE"));
  2572.                 }
  2573.                 rs.close();
  2574.                 pstmt.close();

  2575.                 return profiloCollaborazione;

  2576.             } catch(Exception e) {
  2577.                 String errorMsg = "REPOSITORY_BUSTE, Errore  getProfiloCollaborazione "+tipoBusta+"/"+id+": "+e.getMessage();
  2578.                 try{
  2579.                     if(rs != null)
  2580.                         rs.close();
  2581.                 } catch(Exception er) {
  2582.                     // close
  2583.                 }
  2584.                 try{
  2585.                     if(pstmt != null)
  2586.                         pstmt.close();
  2587.                 } catch(Exception er) {
  2588.                     // close
  2589.                 }
  2590.                 this.log.error(errorMsg,e);
  2591.                 throw new ProtocolException(errorMsg,e);
  2592.             }
  2593.         }   else{
  2594.             StatelessMessage statelessMsg = ((StatelessMessage)this.state);
  2595.             Busta busta = statelessMsg.getBusta();
  2596.             return busta.getProfiloDiCollaborazione();
  2597.         }
  2598.     }
  2599.    
  2600.     /**
  2601.      * Ritorna la collaborazione associata alla busta.
  2602.      *
  2603.      * @param id identificativo della busta.
  2604.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2605.      * @return Collaborazione associata alla busta
  2606.      *
  2607.      */
  2608.     private String getProfiloCollaborazioneValue(String id,String tipoBusta) throws ProtocolException{

  2609.         if(this.state instanceof StatefulMessage) {

  2610.             return null; // info non disponibile, poiche' non salvata nel repository

  2611.         }   else{
  2612.             StatelessMessage statelessMsg = ((StatelessMessage)this.state);
  2613.             Busta busta = statelessMsg.getBusta();
  2614.             return busta.getProfiloDiCollaborazioneValue();
  2615.         }
  2616.     }

  2617.     /**
  2618.      * Ritorna la sequenza associata alla busta.
  2619.      *
  2620.      * @param id identificativo della busta.
  2621.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2622.      * @return Sequenza associata alla busta
  2623.      *
  2624.      */
  2625.     private long getSequenza(String id,String tipoBusta) throws ProtocolException{

  2626.         if(this.state instanceof StatefulMessage) {

  2627.             StatefulMessage stateful = (StatefulMessage)this.state;
  2628.             Connection connectionDB = stateful.getConnectionDB();
  2629.             PreparedStatement pstmt = null;
  2630.             ResultSet rs = null;
  2631.             try{
  2632.                 // Costruzione Query
  2633.                 String query = "SELECT SEQUENZA FROM "+Costanti.REPOSITORY+" WHERE ID_MESSAGGIO=? AND TIPO=?";
  2634.                 //log.debug("Query: "+query);
  2635.                 pstmt = connectionDB.prepareStatement(query);
  2636.                 pstmt.setString(1,id);
  2637.                 pstmt.setString(2,tipoBusta);
  2638.                 rs = pstmt.executeQuery();
  2639.                 if(rs == null) {
  2640.                     throw new ProtocolException("RS Null?");
  2641.                 }
  2642.                 long sequenza = -1;
  2643.                 if(rs.next()){
  2644.                     sequenza = rs.getLong("SEQUENZA");
  2645.                 }
  2646.                 rs.close();
  2647.                 pstmt.close();

  2648.                 return sequenza;

  2649.             } catch(Exception e) {
  2650.                 String errorMsg = "REPOSITORY_BUSTE, Errore  getSequenza "+tipoBusta+"/"+id+": "+e.getMessage();
  2651.                 try{
  2652.                     if(rs != null)
  2653.                         rs.close();
  2654.                 } catch(Exception er) {
  2655.                     // close
  2656.                 }
  2657.                 try{
  2658.                     if(pstmt != null)
  2659.                         pstmt.close();
  2660.                 } catch(Exception er) {
  2661.                     // close
  2662.                 }
  2663.                 this.log.error(errorMsg,e);
  2664.                 throw new ProtocolException(errorMsg,e);
  2665.             }
  2666.         }else{

  2667.             StatelessMessage statelessMsg = ((StatelessMessage)this.state);
  2668.             Busta busta = statelessMsg.getBusta();
  2669.             return busta.getSequenza();
  2670.         }
  2671.     }

  2672.     /**
  2673.      * Ritorna le informazioni di integrazione associate alla busta.
  2674.      *
  2675.      * @param id identificativo della busta.
  2676.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2677.      * @return Informazioni di integrazione associate alla busta
  2678.      *
  2679.      */
  2680.     private Integrazione getInfoIntegrazione(String id,String tipoBusta) throws ProtocolException{

  2681.         StateMessage stateful = (StateMessage)this.state;
  2682.         Connection connectionDB = stateful.getConnectionDB();
  2683.         PreparedStatement pstmt = null;
  2684.         ResultSet rs = null;
  2685.         try{
  2686.             // Costruzione Query
  2687.             String query = "SELECT LOCATION_PD,SERVIZIO_APPLICATIVO,MODULO_IN_ATTESA,SCENARIO FROM "+Costanti.REPOSITORY+" WHERE ID_MESSAGGIO=? AND TIPO=?";
  2688.             //log.debug("Query: "+query);
  2689.             pstmt = connectionDB.prepareStatement(query);
  2690.             pstmt.setString(1,id);
  2691.             pstmt.setString(2,tipoBusta);
  2692.             rs = pstmt.executeQuery();
  2693.             if(rs == null) {
  2694.                 throw new ProtocolException("RS Null?");
  2695.             }
  2696.             Integrazione infoIntegrazione = new Integrazione();
  2697.             if(rs.next()){
  2698.                 infoIntegrazione.setIdModuloInAttesa(rs.getString("MODULO_IN_ATTESA"));
  2699.                 infoIntegrazione.setNomePorta(rs.getString("LOCATION_PD"));
  2700.                 infoIntegrazione.setScenario(rs.getString("SCENARIO"));
  2701.                 infoIntegrazione.setServizioApplicativo(rs.getString("SERVIZIO_APPLICATIVO"));
  2702.             }
  2703.             rs.close();
  2704.             pstmt.close();

  2705.             return infoIntegrazione;

  2706.         } catch(Exception e) {
  2707.             String errorMsg = "REPOSITORY_BUSTE, Errore  getInfoIntegrazione "+tipoBusta+"/"+id+": "+e.getMessage();
  2708.             try{
  2709.                 if(rs != null)
  2710.                     rs.close();
  2711.             } catch(Exception er) {
  2712.                 // close
  2713.             }
  2714.             try{
  2715.                 if(pstmt != null)
  2716.                     pstmt.close();
  2717.             } catch(Exception er) {
  2718.                 // close
  2719.             }
  2720.             this.log.error(errorMsg,e);
  2721.             throw new ProtocolException(errorMsg,e);
  2722.         }
  2723.     }

  2724.     /**
  2725.      * Metodo che si occupa di eliminare l'indicazione di utilizzo della busta dalla PdD
  2726.      *
  2727.      * @param id identificativo della busta.
  2728.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2729.      *
  2730.      */
  2731.     private void eliminaUtilizzoPdD(String id,String tipoBusta,boolean forzaEliminazioneDB, Date dataRegistrazione) throws ProtocolException{
  2732.         this.eliminaUtilizzoPdD(id, tipoBusta, forzaEliminazioneDB, true, dataRegistrazione);
  2733.     }
  2734.     private void eliminaUtilizzoPdD(String id,String tipoBusta,boolean forzaEliminazioneDB, boolean savePreparedStatement, Date dataRegistrazione) throws ProtocolException{

  2735.         if(this.state instanceof StatefulMessage || forzaEliminazioneDB) {

  2736.             StateMessage stateMSG = (StateMessage)this.state;
  2737.             Connection connectionDB = stateMSG.getConnectionDB();

  2738.             PreparedStatement pstmtUpdate = null;
  2739.             try{

  2740.                 StringBuilder queryUpdate = new StringBuilder();
  2741.                 queryUpdate.append("UPDATE ");
  2742.                 queryUpdate.append(Costanti.REPOSITORY);
  2743.                 queryUpdate.append(" SET ");
  2744.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_PdD(false));
  2745.                 queryUpdate.append(" WHERE ");
  2746.                 if(dataRegistrazione!=null) {
  2747.                     queryUpdate.append("(DATA_REGISTRAZIONE BETWEEN ? AND ?) AND ");
  2748.                 }
  2749.                 queryUpdate.append("ID_MESSAGGIO = ? AND TIPO=?");
  2750.                            
  2751.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  2752.                 int index = 1;
  2753.                
  2754.                 Timestamp leftValue = null;
  2755.                 Timestamp rightValue = null;
  2756.                 if(dataRegistrazione!=null) {
  2757.                     leftValue = new Timestamp(dataRegistrazione.getTime() - (1000*60*5));
  2758.                     rightValue = new Timestamp(dataRegistrazione.getTime() + (1000*60*5));
  2759.                     pstmtUpdate.setTimestamp(index++,leftValue);
  2760.                     pstmtUpdate.setTimestamp(index++,rightValue);
  2761.                 }
  2762.                
  2763.                 pstmtUpdate.setString(index++,id);
  2764.                 pstmtUpdate.setString(index++,tipoBusta);

  2765.                 // Add PreparedStatement
  2766.                 if(savePreparedStatement)
  2767.                     stateMSG.getPreparedStatement().put("UPDATE AggiornamentoBusta"+tipoBusta+"_"+id,pstmtUpdate);
  2768.                 else
  2769.                     pstmtUpdate.executeUpdate();

  2770.             } catch(Exception e) {
  2771.                 String errorMsg = "REPOSITORY_BUSTE, Errore di cancellazione utilizzo from PdD "+tipoBusta+"/"+id+": "+e.getMessage();
  2772.                 this.log.error(errorMsg,e);
  2773.                 try{
  2774.                     if(pstmtUpdate != null)
  2775.                         pstmtUpdate.close();
  2776.                 } catch(Exception er) {
  2777.                     // Eccezione SQL.
  2778.                 }
  2779.                 throw new ProtocolException(errorMsg,e);
  2780.             }
  2781.         }

  2782.     }


  2783.     /**
  2784.      * Metodo che si occupa di eliminare l'indicazione di utilizzo della busta dalla PdD
  2785.      *
  2786.      * @param id identificativo della busta.
  2787.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2788.      *
  2789.      */
  2790.     private void eliminaBustaStateless(String id,String tipoBusta, Date dataRegistrazione) throws ProtocolException{

  2791.         StateMessage stateMSG = (StateMessage)this.state;
  2792.         Connection connectionDB = stateMSG.getConnectionDB();

  2793.         PreparedStatement pstmtUpdate = null;
  2794.         try{

  2795.             StringBuilder queryUpdate = new StringBuilder();
  2796.             queryUpdate.append("UPDATE ");
  2797.             queryUpdate.append(Costanti.REPOSITORY);
  2798.             queryUpdate.append(" SET ");
  2799.             queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_PdD(false));
  2800.             queryUpdate.append(" WHERE ");
  2801.             if(dataRegistrazione!=null) {
  2802.                 queryUpdate.append("(DATA_REGISTRAZIONE BETWEEN ? AND ?) AND ");
  2803.             }
  2804.             queryUpdate.append("ID_MESSAGGIO = ? AND TIPO=?");
  2805.                    
  2806.             pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  2807.             int index = 1;
  2808.            
  2809.             Timestamp leftValue = null;
  2810.             Timestamp rightValue = null;
  2811.             if(dataRegistrazione!=null) {
  2812.                 leftValue = new Timestamp(dataRegistrazione.getTime() - (1000*60*5));
  2813.                 rightValue = new Timestamp(dataRegistrazione.getTime() + (1000*60*5));
  2814.                 pstmtUpdate.setTimestamp(index++,leftValue);
  2815.                 pstmtUpdate.setTimestamp(index++,rightValue);
  2816.             }
  2817.            
  2818.             pstmtUpdate.setString(index++,id);
  2819.             pstmtUpdate.setString(index++,tipoBusta);

  2820.             // Add PreparedStatement
  2821.             stateMSG.getPreparedStatement().put("UPDATE AggiornamentoBusta"+tipoBusta+"_"+id,pstmtUpdate);
  2822.            
  2823.         } catch(Exception e) {
  2824.             String errorMsg = "REPOSITORY_BUSTE, Errore di cancellazione utilizzo from PdD "+tipoBusta+"/"+id+": "+e.getMessage();
  2825.             this.log.error(errorMsg,e);
  2826.             try{
  2827.                 if(pstmtUpdate != null)
  2828.                     pstmtUpdate.close();
  2829.             } catch(Exception er) {
  2830.                 // Eccezione SQL.
  2831.             }
  2832.             throw new ProtocolException(errorMsg,e);
  2833.         }

  2834.     }  
  2835.    
  2836.    
  2837.     /**
  2838.      * Metodo che si occupa di eliminare una busta, precedentemente registrata.
  2839.      * Alla busta, al momento della registrazione e' stato associato
  2840.      * l'identificativo della busta, quindi attraverso esso sara' possibile trovarlo
  2841.      *
  2842.      * @param id identificativo della busta da eliminare.
  2843.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  2844.      *
  2845.      */
  2846.     private void eliminaBusta(String id, String tipoBusta, Date data) throws ProtocolException{

  2847.         StateMessage state = (StateMessage)this.state;
  2848.         Connection connectionDB = state.getConnectionDB();
  2849.         PreparedStatement pstmtDelete = null;
  2850.         try{

  2851.             // Eliminazione dati applicativi

  2852.             // eliminazione di richieste delegata
  2853.             if(Costanti.OUTBOX.equals(tipoBusta)){

  2854.                 // Eliminazione ricezione riscontro
  2855.                 if(this.state instanceof StatefulMessage) {
  2856.                     Riscontri riscontri = new Riscontri(state,this.log);
  2857.                     riscontri.validazioneRiscontroRicevuto(id);
  2858.                     state.executePreparedStatement();
  2859.                 }

  2860.                 // Eliminazione invio asincrono
  2861.                 ProfiloDiCollaborazione profilo = new ProfiloDiCollaborazione(state, this.log, this.protocolFactory);
  2862.                 profilo.asincrono_eliminaRegistrazione(id, Costanti.OUTBOX, data);
  2863.                 state.executePreparedStatement();

  2864.             }
  2865.             // eliminazione di richieste applicativa
  2866.             else if(Costanti.INBOX.equals(tipoBusta)){

  2867.                 //  Eliminazione ricezione asincrono
  2868.                 ProfiloDiCollaborazione profilo = new ProfiloDiCollaborazione(state, this.log, this.protocolFactory);
  2869.                 profilo.asincrono_eliminaRegistrazione(id, Costanti.INBOX, data);
  2870.                 state.executePreparedStatement();
  2871.             }

  2872.             java.sql.Timestamp nowT = null;
  2873.             if(data!=null) {
  2874.                 nowT = new java.sql.Timestamp(data.getTime());
  2875.             }

  2876.             if(this.state instanceof StatefulMessage) {
  2877.            
  2878.                 // elimino lista trasmissioni
  2879.                 StringBuilder queryDelete = new StringBuilder();
  2880.                 queryDelete.append("DELETE FROM ");
  2881.                 queryDelete.append(Costanti.LISTA_TRASMISSIONI);
  2882.                 queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  2883.                 if(data!=null) {
  2884.                     queryDelete.append(" AND DATA_REGISTRAZIONE<=?");
  2885.                 }
  2886.                 pstmtDelete = connectionDB.prepareStatement(queryDelete.toString());
  2887.                 pstmtDelete.setString(1,id);
  2888.                 pstmtDelete.setString(2,tipoBusta);
  2889.                 if(data!=null) {
  2890.                     pstmtDelete.setTimestamp(3,nowT);
  2891.                 }
  2892.                 pstmtDelete.execute();
  2893.                 pstmtDelete.close();
  2894.    
  2895.                 //  elimino lista riscontri
  2896.                 queryDelete.delete(0,queryDelete.length());
  2897.                 queryDelete.append("DELETE FROM ");
  2898.                 queryDelete.append(Costanti.LISTA_RISCONTRI);
  2899.                 queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  2900.                 if(data!=null) {
  2901.                     queryDelete.append(" AND DATA_REGISTRAZIONE<=?");
  2902.                 }
  2903.                 pstmtDelete = connectionDB.prepareStatement(queryDelete.toString());
  2904.                 pstmtDelete.setString(1,id);
  2905.                 pstmtDelete.setString(2,tipoBusta);
  2906.                 if(data!=null) {
  2907.                     pstmtDelete.setTimestamp(3,nowT);
  2908.                 }
  2909.                 pstmtDelete.execute();
  2910.                 pstmtDelete.close();
  2911.    
  2912.                 //  elimino lista eccezioni
  2913.                 queryDelete.delete(0,queryDelete.length());
  2914.                 queryDelete.append("DELETE FROM ");
  2915.                 queryDelete.append(Costanti.LISTA_ECCEZIONI);
  2916.                 queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  2917.                 if(data!=null) {
  2918.                     queryDelete.append(" AND DATA_REGISTRAZIONE<=?");
  2919.                 }
  2920.                 pstmtDelete = connectionDB.prepareStatement(queryDelete.toString());
  2921.                 pstmtDelete.setString(1,id);
  2922.                 pstmtDelete.setString(2,tipoBusta);
  2923.                 if(data!=null) {
  2924.                     pstmtDelete.setTimestamp(3,nowT);
  2925.                 }
  2926.                 pstmtDelete.execute();
  2927.                 pstmtDelete.close();
  2928.                
  2929.                 // elimino lista ext
  2930.                 queryDelete.delete(0,queryDelete.length());
  2931.                 queryDelete.append("DELETE FROM ");
  2932.                 queryDelete.append(Costanti.LISTA_EXT_INFO);
  2933.                 queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  2934.                 if(data!=null) {
  2935.                     queryDelete.append(" AND DATA_REGISTRAZIONE<=?");
  2936.                 }
  2937.                 pstmtDelete = connectionDB.prepareStatement(queryDelete.toString());
  2938.                 pstmtDelete.setString(1,id);
  2939.                 pstmtDelete.setString(2,tipoBusta);
  2940.                 if(data!=null) {
  2941.                     pstmtDelete.setTimestamp(3,nowT);
  2942.                 }
  2943.                 pstmtDelete.execute();
  2944.                 pstmtDelete.close();
  2945.             }

  2946.             // Elimino busta
  2947.             StringBuilder queryDelete = new StringBuilder();
  2948.             queryDelete.append("DELETE FROM ");
  2949.             queryDelete.append(Costanti.REPOSITORY);
  2950.             queryDelete.append(" WHERE ID_MESSAGGIO = ? AND TIPO = ?");
  2951.             if(data!=null) {
  2952.                 queryDelete.append(" AND DATA_REGISTRAZIONE<=?");
  2953.             }
  2954.             pstmtDelete = connectionDB.prepareStatement(queryDelete.toString());
  2955.             pstmtDelete.setString(1,id);
  2956.             pstmtDelete.setString(2,tipoBusta);
  2957.             if(data!=null) {
  2958.                 pstmtDelete.setTimestamp(3,nowT);
  2959.             }
  2960.             pstmtDelete.execute();
  2961.             pstmtDelete.close();

  2962.         } catch(Exception e) {
  2963.             String errorMsg = "REPOSITORY_BUSTE, Errore di cancellazione from "+Costanti.REPOSITORY+" "+tipoBusta+"/"+id+": "+e.getMessage();
  2964.             this.log.error(errorMsg,e);
  2965.             try{
  2966.                 if( pstmtDelete != null )
  2967.                     pstmtDelete.close();
  2968.             } catch(Exception er) {
  2969.                 // Eccezione SQL.
  2970.             }
  2971.             throw new ProtocolException(errorMsg,e);
  2972.         }
  2973.     }





  2974.    
  2975.    
  2976.    
  2977.     /* ------------- UTILITY PER LETTURA MESSAGGI DA ELIMINARE -------------- */
  2978.    
  2979.     public static Date getDataRegistrazioneBustaMassima(Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws ProtocolException{
  2980.         return _getDataRegistrazioneBusta(false, connectionDB , tipoDatabase, logQuery, logger);
  2981.     }
  2982.     public static Date getDataRegistrazioneBustaMinima(Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws ProtocolException{
  2983.         return _getDataRegistrazioneBusta(true, connectionDB , tipoDatabase, logQuery, logger);
  2984.     }
  2985.     private static Date _getDataRegistrazioneBusta(boolean min, Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws ProtocolException{
  2986.    
  2987.         PreparedStatement pstmt = null;
  2988.         ResultSet rs = null;
  2989.         String queryString = null;
  2990.         try{    
  2991.        
  2992.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  2993.             if(min) {
  2994.                 sqlQueryObject.addSelectMinField(Costanti.REPOSITORY_COLUMN_DATA_REGISTRAZIONE, "check_data");
  2995.             }
  2996.             else {
  2997.                 sqlQueryObject.addSelectMaxField(Costanti.REPOSITORY_COLUMN_DATA_REGISTRAZIONE, "check_data");
  2998.             }
  2999.             sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  3000.             sqlQueryObject.setANDLogicOperator(true);
  3001.             queryString = sqlQueryObject.createSQLQuery();
  3002.             if(logQuery) {
  3003.                 logger.debug("Esecuzione query ["+queryString+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  3004.             }
  3005.            
  3006.             pstmt = connectionDB.prepareStatement(queryString);
  3007.             rs = pstmt.executeQuery();
  3008.            
  3009.             if(logQuery) {
  3010.                 logger.debug("Esecuzione query ["+queryString+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata");
  3011.             }
  3012.            
  3013.             if(rs.next()) {
  3014.                 return rs.getTimestamp("check_data");
  3015.             }
  3016.             return null;
  3017.        
  3018.         } catch(Exception e) {
  3019.             String errorMsg = "[RepositoryBuste.getDataRegistrazioneBusta] errore, queryString["+queryString+"]: "+e.getMessage();
  3020.             throw new ProtocolException(errorMsg,e);
  3021.         }
  3022.         finally {
  3023.             try{
  3024.                 if(rs != null)
  3025.                     rs.close();
  3026.             } catch(Exception er) {
  3027.                 // close
  3028.             }
  3029.             try{
  3030.                 if(pstmt != null)
  3031.                     pstmt.close();
  3032.             } catch(Exception er) {
  3033.                 // close
  3034.             }
  3035.         }
  3036.     }
  3037.    
  3038.     public static Date getDataScadenzaBustaMassima(Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws ProtocolException{
  3039.         return _getDataScadenzaBusta(false, connectionDB , tipoDatabase, logQuery, logger);
  3040.     }
  3041.     public static Date getDataScadenzaBustaMinima(Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws ProtocolException{
  3042.         return _getDataScadenzaBusta(true, connectionDB , tipoDatabase, logQuery, logger);
  3043.     }
  3044.     private static Date _getDataScadenzaBusta(boolean min, Connection connectionDB , String tipoDatabase, boolean logQuery, Logger logger) throws ProtocolException{
  3045.    
  3046.         PreparedStatement pstmt = null;
  3047.         ResultSet rs = null;
  3048.         String queryString = null;
  3049.         try{    
  3050.        
  3051.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  3052.             if(min) {
  3053.                 sqlQueryObject.addSelectMinField(Costanti.REPOSITORY_COLUMN_SCADENZA, "check_data");
  3054.             }
  3055.             else {
  3056.                 sqlQueryObject.addSelectMaxField(Costanti.REPOSITORY_COLUMN_SCADENZA, "check_data");
  3057.             }
  3058.             sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  3059.             sqlQueryObject.setANDLogicOperator(true);
  3060.             queryString = sqlQueryObject.createSQLQuery();
  3061.             if(logQuery) {
  3062.                 logger.debug("Esecuzione query ["+queryString+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  3063.             }
  3064.            
  3065.             pstmt = connectionDB.prepareStatement(queryString);
  3066.             rs = pstmt.executeQuery();
  3067.            
  3068.             if(logQuery) {
  3069.                 logger.debug("Esecuzione query ["+queryString+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata");
  3070.             }
  3071.            
  3072.             if(rs.next()) {
  3073.                 return rs.getTimestamp("check_data");
  3074.             }
  3075.             return null;
  3076.        
  3077.         } catch(Exception e) {
  3078.             String errorMsg = "[RepositoryBuste.getDataScadenzaBusta] errore, queryString["+queryString+"]: "+e.getMessage();
  3079.             throw new ProtocolException(errorMsg,e);
  3080.         }
  3081.         finally {
  3082.             try{
  3083.                 if(rs != null)
  3084.                     rs.close();
  3085.             } catch(Exception er) {
  3086.                 // close
  3087.             }
  3088.             try{
  3089.                 if(pstmt != null)
  3090.                     pstmt.close();
  3091.             } catch(Exception er) {
  3092.                 // close
  3093.             }
  3094.         }
  3095.     }
  3096.    
  3097.     public static int countBusteInutiliIntoInBox(Connection connectionDB , String tipoDatabase,
  3098.             boolean logQuery, Logger logger,
  3099.             IGestoreRepository repository,
  3100.             Date leftDate, Date rightDate, boolean useDataRegistrazione) throws ProtocolException{
  3101.         return _countBusteIntoBox(true, connectionDB, tipoDatabase, logQuery, logger, false, repository, leftDate, rightDate, useDataRegistrazione);
  3102.     }
  3103.     public static int countBusteInutiliIntoOutBox(Connection connectionDB , String tipoDatabase,
  3104.             boolean logQuery, Logger logger,
  3105.             IGestoreRepository repository,
  3106.             Date leftDate, Date rightDate, boolean useDataRegistrazione) throws ProtocolException{
  3107.         return _countBusteIntoBox(false, connectionDB, tipoDatabase, logQuery, logger, false, repository, leftDate, rightDate, useDataRegistrazione);
  3108.     }
  3109.     public static int countBusteScaduteIntoInBox(Connection connectionDB , String tipoDatabase,
  3110.             boolean logQuery, Logger logger,
  3111.             IGestoreRepository repository) throws ProtocolException{
  3112.         return _countBusteIntoBox(true, connectionDB, tipoDatabase, logQuery, logger, true, repository, null, null, false);
  3113.     }
  3114.     public static int countBusteScaduteIntoOutBox(Connection connectionDB , String tipoDatabase,
  3115.             boolean logQuery, Logger logger,
  3116.             IGestoreRepository repository) throws ProtocolException{
  3117.         return _countBusteIntoBox(false, connectionDB, tipoDatabase, logQuery, logger, true, repository, null, null, false);
  3118.     }
  3119.     private static int _countBusteIntoBox(boolean searchIntoInbox, Connection connectionDB , String tipoDatabase,
  3120.             boolean logQuery, Logger logger,
  3121.             boolean scadenzaMsg, IGestoreRepository repository,
  3122.             Date leftDate, Date rightDate, boolean useDataRegistrazione) throws ProtocolException{
  3123.        
  3124.         // Le buste da eliminare sono quelle che
  3125.         // -1 sono scadute e non possiedono l'accesso da pdd o l'accesso da profilo
  3126.         // -2 non possiedono piu' accessi da nessuna fonte
  3127.         //      se possiedono ancora l'accesso da pdd, vuole dire che un msg e' in rollback,
  3128.         //        e sara' eliminato l'accesso una volta consegnato con successo il msg,
  3129.         //        o una volta scaduto il msg (rollback)
  3130.         //      se possiedono ancora l'accesso da profilo, vuole dire che un msg e' in rollback,
  3131.         //        e sara' eliminato una volta terminato il profilo,
  3132.         //        o una volta scaduto il msg (rollback)
  3133.        
  3134.         String tipo = null;
  3135.         if(searchIntoInbox)
  3136.             tipo = Costanti.INBOX;
  3137.         else
  3138.             tipo = Costanti.OUTBOX;
  3139.    
  3140.         PreparedStatement pstmt = null;
  3141.         ResultSet rs = null;
  3142.         String queryString = null;
  3143.         try{    
  3144.        
  3145.             // Query per Ricerca messaggi scaduti
  3146.             java.sql.Timestamp nowT = null;
  3147.             if(scadenzaMsg) {
  3148.                 nowT = DateManager.getTimestamp();
  3149.             }
  3150.            
  3151.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  3152.             sqlQueryObject.addSelectCountField("totale_msg");
  3153.             sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  3154.            
  3155.             if(leftDate!=null) {
  3156.                 sqlQueryObject.addWhereCondition((useDataRegistrazione ? Costanti.REPOSITORY_COLUMN_DATA_REGISTRAZIONE : Costanti.REPOSITORY_COLUMN_SCADENZA)+">=?");
  3157.             }
  3158.             if(rightDate!=null) {
  3159.                 sqlQueryObject.addWhereCondition((useDataRegistrazione ? Costanti.REPOSITORY_COLUMN_DATA_REGISTRAZIONE : Costanti.REPOSITORY_COLUMN_SCADENZA)+"<=?");
  3160.             }
  3161.             if(scadenzaMsg) {
  3162.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY_COLUMN_SCADENZA+" < ?");
  3163.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY_COLUMN_TIPO_MESSAGGIO+"=?");
  3164.                 // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3165.                 //sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3166.                 //sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3167.                 sqlQueryObject.addWhereCondition(repository.createSQLCondition_enableOnlyHistory());
  3168.             }
  3169.             else {
  3170.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY_COLUMN_TIPO_MESSAGGIO+"=?");
  3171.             // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3172.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_History(false));
  3173.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3174.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3175.                 sqlQueryObject.addWhereCondition(repository.createSQLCondition_disabledAll());
  3176.             }
  3177.             sqlQueryObject.setANDLogicOperator(true);
  3178.             queryString = sqlQueryObject.createSQLQuery();

  3179.             pstmt = connectionDB.prepareStatement(queryString);
  3180.             int index = 1;
  3181.             List<Object> objects = new ArrayList<>();
  3182.             if(leftDate!=null) {
  3183.                 java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  3184.                 pstmt.setTimestamp(index++, leftDateT);
  3185.                 if(logQuery) {
  3186.                     objects.add(DateUtils.getSimpleDateFormatMs().format(leftDateT));
  3187.                 }
  3188.             }
  3189.             if(rightDate!=null) {
  3190.                 java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  3191.                 pstmt.setTimestamp(index++, rightDateT);
  3192.                 if(logQuery) {
  3193.                     objects.add(DateUtils.getSimpleDateFormatMs().format(rightDateT));
  3194.                 }
  3195.             }
  3196.             if(scadenzaMsg) {
  3197.                 pstmt.setTimestamp(index++,nowT);
  3198.                 if(logQuery) {
  3199.                     objects.add(DateUtils.getSimpleDateFormatMs().format(nowT));
  3200.                 }
  3201.                 pstmt.setString(index++,tipo);
  3202.                 if(logQuery) {
  3203.                     objects.add(tipo);
  3204.                 }
  3205.             }
  3206.             else {
  3207.                 pstmt.setString(index++,tipo);
  3208.                 if(logQuery) {
  3209.                     objects.add(tipo);
  3210.                 }
  3211.             }
  3212.            
  3213.             String query = null;
  3214.             if(logQuery) {
  3215.                 query = DBUtils.formatSQLString(queryString, objects.toArray());
  3216.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  3217.             }
  3218.             rs = pstmt.executeQuery();
  3219.            
  3220.             int res = 0;
  3221.             if(rs.next()) {
  3222.                 res = rs.getInt("totale_msg");
  3223.             }
  3224.            
  3225.             if(logQuery) {
  3226.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; trovati "+res+" risultati");
  3227.             }
  3228.            
  3229.             return res;
  3230.        
  3231.         } catch(Exception e) {
  3232.             String errorMsg = "[RepositoryBuste.countBusteIntoBox] errore, queryString["+queryString+"]: "+e.getMessage();
  3233.             throw new ProtocolException(errorMsg,e);
  3234.         }
  3235.         finally {
  3236.             try{
  3237.                 if(rs != null)
  3238.                     rs.close();
  3239.             } catch(Exception er) {
  3240.                 // close
  3241.             }
  3242.             try{
  3243.                 if(pstmt != null)
  3244.                     pstmt.close();
  3245.             } catch(Exception er) {
  3246.                 // close
  3247.             }
  3248.         }
  3249.     }
  3250.    
  3251.    
  3252.    
  3253.    
  3254.     public static SortedMap<Integer> deleteBusteInutiliIntoInBox(Connection connectionDB , String tipoDatabase,
  3255.             boolean logQuery, Logger logger,
  3256.             IGestoreRepository repository,
  3257.             Date leftDate, Date rightDate, boolean useDataRegistrazione) throws ProtocolException{
  3258.         return _deleteBusteIntoBox(true, connectionDB, tipoDatabase, logQuery, logger, false, repository, leftDate, rightDate, useDataRegistrazione);
  3259.     }
  3260.     public static SortedMap<Integer> deleteBusteInutiliIntoOutBox(Connection connectionDB , String tipoDatabase,
  3261.             boolean logQuery, Logger logger,
  3262.             IGestoreRepository repository,
  3263.             Date leftDate, Date rightDate, boolean useDataRegistrazione) throws ProtocolException{
  3264.         return _deleteBusteIntoBox(false, connectionDB, tipoDatabase, logQuery, logger, false, repository, leftDate, rightDate, useDataRegistrazione);
  3265.     }
  3266.     public static SortedMap<Integer> deleteBusteScaduteIntoInBox(Connection connectionDB , String tipoDatabase,
  3267.             boolean logQuery, Logger logger,
  3268.             IGestoreRepository repository) throws ProtocolException{
  3269.         return _deleteBusteIntoBox(true, connectionDB, tipoDatabase, logQuery, logger, true, repository, null, null, false);
  3270.     }
  3271.     public static SortedMap<Integer> deleteBusteScaduteIntoOutBox(Connection connectionDB , String tipoDatabase,
  3272.             boolean logQuery, Logger logger,
  3273.             IGestoreRepository repository) throws ProtocolException{
  3274.         return _deleteBusteIntoBox(false, connectionDB, tipoDatabase, logQuery, logger, true, repository, null, null, false);
  3275.     }
  3276.     private static SortedMap<Integer> _deleteBusteIntoBox(boolean searchIntoInbox, Connection connectionDB , String tipoDatabase,
  3277.             boolean logQuery, Logger logger,
  3278.             boolean scadenzaMsg, IGestoreRepository repository,
  3279.             Date leftDate, Date rightDate, boolean useDataRegistrazione) throws ProtocolException{
  3280.        
  3281.         SortedMap<Integer> mapTabelleRigheEliminate = new SortedMap<Integer>();
  3282.        
  3283.         String tipo = null;
  3284.         if(searchIntoInbox)
  3285.             tipo = Costanti.INBOX;
  3286.         else
  3287.             tipo = Costanti.OUTBOX;
  3288.        
  3289.         PreparedStatement pstmt = null;
  3290.         String deleteString = null;
  3291.         try{    
  3292.        
  3293.             // Query per Ricerca messaggi scaduti
  3294.             java.sql.Timestamp nowT = null;
  3295.             if(scadenzaMsg) {
  3296.                 nowT = DateManager.getTimestamp();
  3297.             }

  3298.             // Le buste da eliminare sono quelle che
  3299.             // -1 sono scadute e non possiedono l'accesso da pdd o l'accesso da profilo
  3300.             // -2 non possiedono piu' accessi da nessuna fonte
  3301.             //      se possiedono ancora l'accesso da pdd, vuole dire che un msg e' in rollback,
  3302.             //        e sara' eliminato l'accesso una volta consegnato con successo il msg,
  3303.             //        o una volta scaduto il msg (rollback)
  3304.             //      se possiedono ancora l'accesso da profilo, vuole dire che un msg e' in rollback,
  3305.             //        e sara' eliminato una volta terminato il profilo,
  3306.             //        o una volta scaduto il msg (rollback)
  3307.                
  3308.             // lista
  3309.             ISQLQueryObject sqlQueryObjectRepositoryBusteJoin = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  3310.             sqlQueryObjectRepositoryBusteJoin.addSelectField(org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY_COLUMN_ID_MESSAGGIO);
  3311.             sqlQueryObjectRepositoryBusteJoin.addFromTable(Costanti.REPOSITORY);
  3312.             if(leftDate!=null) {
  3313.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition((useDataRegistrazione ? Costanti.REPOSITORY_COLUMN_DATA_REGISTRAZIONE : Costanti.REPOSITORY_COLUMN_SCADENZA)+">=?");
  3314.             }
  3315.             if(rightDate!=null) {
  3316.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition((useDataRegistrazione ? Costanti.REPOSITORY_COLUMN_DATA_REGISTRAZIONE : Costanti.REPOSITORY_COLUMN_SCADENZA)+"<=?");
  3317.             }
  3318.             if(scadenzaMsg) {
  3319.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition(Costanti.REPOSITORY_COLUMN_SCADENZA+" < ?");
  3320.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition(Costanti.REPOSITORY_COLUMN_TIPO_MESSAGGIO+"=?");
  3321.                 // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3322.                 //sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3323.                 //sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3324.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition(repository.createSQLCondition_enableOnlyHistory());
  3325.             }
  3326.             else {
  3327.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition(Costanti.REPOSITORY_COLUMN_TIPO_MESSAGGIO+"=?");
  3328.             // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3329.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_History(false));
  3330.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3331.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3332.                 sqlQueryObjectRepositoryBusteJoin.addWhereCondition(repository.createSQLCondition_disabledAll());
  3333.             }
  3334.             sqlQueryObjectRepositoryBusteJoin.setANDLogicOperator(true);
  3335.            
  3336.            
  3337.             _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  3338.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_RISCONTRI,
  3339.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_RISCONTRI_COLUMN_TIPO_MESSAGGIO,
  3340.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_RISCONTRI_COLUMN_ID_MESSAGGIO,
  3341.                     tipo, nowT, sqlQueryObjectRepositoryBusteJoin,
  3342.                     leftDate, rightDate,
  3343.                     mapTabelleRigheEliminate);
  3344.            
  3345.             _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  3346.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_TRASMISSIONI,
  3347.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_TRASMISSIONI_COLUMN_TIPO_MESSAGGIO,
  3348.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_TRASMISSIONI_COLUMN_ID_MESSAGGIO,
  3349.                     tipo, nowT, sqlQueryObjectRepositoryBusteJoin,
  3350.                     leftDate, rightDate,
  3351.                     mapTabelleRigheEliminate);
  3352.            
  3353.             _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  3354.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_ECCEZIONI,
  3355.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_ECCEZIONI_COLUMN_TIPO_MESSAGGIO,
  3356.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_ECCEZIONI_COLUMN_ID_MESSAGGIO,
  3357.                     tipo, nowT, sqlQueryObjectRepositoryBusteJoin,
  3358.                     leftDate, rightDate,
  3359.                     mapTabelleRigheEliminate);
  3360.            
  3361.             _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  3362.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_EXT_INFO,
  3363.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_EXT_INFO_COLUMN_TIPO_MESSAGGIO,
  3364.                     org.openspcoop2.protocol.engine.constants.Costanti.LISTA_EXT_INFO_COLUMN_ID_MESSAGGIO,
  3365.                     tipo, nowT, sqlQueryObjectRepositoryBusteJoin,
  3366.                     leftDate, rightDate,
  3367.                     mapTabelleRigheEliminate);
  3368.            
  3369.             _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  3370.                     org.openspcoop2.protocol.engine.constants.Costanti.PROFILO_ASINCRONO,
  3371.                     org.openspcoop2.protocol.engine.constants.Costanti.PROFILO_ASINCRONO_COLUMN_TIPO_MESSAGGIO,
  3372.                     org.openspcoop2.protocol.engine.constants.Costanti.PROFILO_ASINCRONO_COLUMN_ID_MESSAGGIO,
  3373.                     tipo, nowT, sqlQueryObjectRepositoryBusteJoin,
  3374.                     leftDate, rightDate,
  3375.                     mapTabelleRigheEliminate);
  3376.            
  3377.             if(!searchIntoInbox){
  3378.                 _deleteListaRepositoryBuste(tipoDatabase, connectionDB, logQuery, logger,
  3379.                         org.openspcoop2.protocol.engine.constants.Costanti.RISCONTRI_DA_RICEVERE,
  3380.                         null,
  3381.                         org.openspcoop2.protocol.engine.constants.Costanti.RISCONTRI_COLUMN_ID_MESSAGGIO,
  3382.                         tipo, nowT, sqlQueryObjectRepositoryBusteJoin,
  3383.                         leftDate, rightDate,
  3384.                         mapTabelleRigheEliminate);
  3385.             }
  3386.                
  3387.            
  3388.             // Eliminazione busta reale
  3389.            
  3390.             ISQLQueryObject sqlQueryObjectRepositoryBuste = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  3391.             sqlQueryObjectRepositoryBuste.addDeleteTable(Costanti.REPOSITORY);
  3392.             if(leftDate!=null) {
  3393.                 sqlQueryObjectRepositoryBuste.addWhereCondition((useDataRegistrazione ? Costanti.REPOSITORY_COLUMN_DATA_REGISTRAZIONE : Costanti.REPOSITORY_COLUMN_SCADENZA)+">=?");
  3394.             }
  3395.             if(rightDate!=null) {
  3396.                 sqlQueryObjectRepositoryBuste.addWhereCondition((useDataRegistrazione ? Costanti.REPOSITORY_COLUMN_DATA_REGISTRAZIONE : Costanti.REPOSITORY_COLUMN_SCADENZA)+"<=?");
  3397.             }
  3398.             if(scadenzaMsg) {
  3399.                 sqlQueryObjectRepositoryBuste.addWhereCondition(Costanti.REPOSITORY_COLUMN_SCADENZA+" < ?");
  3400.                 sqlQueryObjectRepositoryBuste.addWhereCondition(Costanti.REPOSITORY_COLUMN_TIPO_MESSAGGIO+"=?");
  3401.                 // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3402.                 //sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3403.                 //sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3404.                 sqlQueryObjectRepositoryBuste.addWhereCondition(repository.createSQLCondition_enableOnlyHistory());
  3405.             }
  3406.             else {
  3407.                 sqlQueryObjectRepositoryBuste.addWhereCondition(Costanti.REPOSITORY_COLUMN_TIPO_MESSAGGIO+"=?");
  3408.             // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3409.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_History(false));
  3410.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3411.     //          sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3412.                 sqlQueryObjectRepositoryBuste.addWhereCondition(repository.createSQLCondition_disabledAll());
  3413.             }
  3414.             sqlQueryObjectRepositoryBuste.setANDLogicOperator(true);
  3415.            
  3416.             deleteString = sqlQueryObjectRepositoryBuste.createSQLDelete();
  3417.             pstmt = connectionDB.prepareStatement(deleteString);
  3418.             int index = 1;
  3419.             List<Object> objects = new ArrayList<>();
  3420.             if(leftDate!=null) {
  3421.                 java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  3422.                 pstmt.setTimestamp(index++, leftDateT);
  3423.                 if(logQuery) {
  3424.                     objects.add(DateUtils.getSimpleDateFormatMs().format(leftDateT));
  3425.                 }
  3426.             }
  3427.             if(rightDate!=null) {
  3428.                 java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  3429.                 pstmt.setTimestamp(index++, rightDateT);
  3430.                 if(logQuery) {
  3431.                     objects.add(DateUtils.getSimpleDateFormatMs().format(rightDateT));
  3432.                 }
  3433.             }
  3434.             if(scadenzaMsg) {
  3435.                 pstmt.setTimestamp(index++,nowT);
  3436.                 if(logQuery) {
  3437.                     objects.add(DateUtils.getSimpleDateFormatMs().format(nowT));
  3438.                 }
  3439.                 pstmt.setString(index++,tipo);
  3440.                 if(logQuery) {
  3441.                     objects.add(tipo);
  3442.                 }
  3443.             }
  3444.             else {
  3445.                 pstmt.setString(index++,tipo);
  3446.                 if(logQuery) {
  3447.                     objects.add(tipo);
  3448.                 }
  3449.             }
  3450.            
  3451.             String query = null;
  3452.             if(logQuery) {
  3453.                 query = DBUtils.formatSQLString(deleteString, objects.toArray());
  3454.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  3455.             }
  3456.             int result = pstmt.executeUpdate();
  3457.             pstmt.close();
  3458.             pstmt = null;
  3459.            
  3460.             if(logQuery) {
  3461.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; "+result+" righe eliminate");
  3462.             }
  3463.             mapTabelleRigheEliminate.add(org.openspcoop2.protocol.engine.constants.Costanti.REPOSITORY, result);
  3464.            
  3465.            
  3466.             return mapTabelleRigheEliminate;
  3467.        
  3468.         } catch(Exception e) {
  3469.             String errorMsg = "[RepositoryBuste.deleteBusteIntoBox] errore, deleteString["+deleteString+"]: "+e.getMessage();
  3470.             throw new ProtocolException(errorMsg,e);
  3471.         } finally {
  3472.             try{
  3473.                 if(pstmt != null)
  3474.                     pstmt.close();
  3475.             } catch(Exception er) {
  3476.                 // close
  3477.             }
  3478.         }
  3479.     }
  3480.    
  3481.    
  3482.     private static void _deleteListaRepositoryBuste(String tipoDatabase, Connection connectionDB, boolean logQuery, Logger logger,
  3483.             String nomeTabella, String nomeColonnaTipoMessaggio, String nomeColonnaIdMessaggio,
  3484.             String tipo, Timestamp scandenzaT, ISQLQueryObject sqlQueryObjectRepositoryBusteJoin,
  3485.             Date leftDate, Date rightDate,
  3486.             SortedMap<Integer> mapTabelleRigheEliminate) throws Exception {
  3487.        
  3488.         // Eliminazione busta reale
  3489.        
  3490.         ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDatabase);
  3491.         sqlQueryObject.addDeleteTable(nomeTabella);
  3492.         if(nomeColonnaTipoMessaggio!=null) {
  3493.             sqlQueryObject.addWhereCondition(nomeColonnaTipoMessaggio+"=?");
  3494.         }
  3495.         sqlQueryObject.addWhereINSelectSQLCondition(false, nomeColonnaIdMessaggio, sqlQueryObjectRepositoryBusteJoin);
  3496.         sqlQueryObject.setANDLogicOperator(true);
  3497.        
  3498.         String deleteString = sqlQueryObject.createSQLDelete();
  3499.         PreparedStatement pstmt = null;
  3500.         try{    
  3501.             pstmt = connectionDB.prepareStatement(deleteString);
  3502.             int index = 1;
  3503.             List<Object> objects = new ArrayList<>();
  3504.             if(nomeColonnaTipoMessaggio!=null) {
  3505.                 pstmt.setString(index++,tipo);
  3506.                 if(logQuery) {
  3507.                     objects.add(tipo);
  3508.                 }
  3509.             }
  3510.            
  3511.             if(leftDate!=null) {
  3512.                 java.sql.Timestamp leftDateT = new java.sql.Timestamp(leftDate.getTime());
  3513.                 pstmt.setTimestamp(index++, leftDateT);
  3514.                 if(logQuery) {
  3515.                     objects.add(DateUtils.getSimpleDateFormatMs().format(leftDateT));
  3516.                 }
  3517.             }
  3518.             if(rightDate!=null) {
  3519.                 java.sql.Timestamp rightDateT = new java.sql.Timestamp(rightDate.getTime());
  3520.                 pstmt.setTimestamp(index++, rightDateT);
  3521.                 if(logQuery) {
  3522.                     objects.add(DateUtils.getSimpleDateFormatMs().format(rightDateT));
  3523.                 }
  3524.             }
  3525.             if(scandenzaT!=null) {
  3526.                 pstmt.setTimestamp(index++,scandenzaT);
  3527.                 if(logQuery) {
  3528.                     objects.add(DateUtils.getSimpleDateFormatMs().format(scandenzaT));
  3529.                 }
  3530.                 pstmt.setString(index++,tipo);
  3531.                 if(logQuery) {
  3532.                     objects.add(tipo);
  3533.                 }
  3534.             }
  3535.             else {
  3536.                 pstmt.setString(index++,tipo);
  3537.                 if(logQuery) {
  3538.                     objects.add(tipo);
  3539.                 }
  3540.             }
  3541.            
  3542.             String query = null;
  3543.             if(logQuery) {
  3544.                 query = DBUtils.formatSQLString(deleteString, objects.toArray());
  3545.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") ...");
  3546.             }
  3547.             int result = pstmt.executeUpdate();
  3548.             pstmt.close();
  3549.             pstmt = null;
  3550.            
  3551.             if(logQuery) {
  3552.                 logger.debug("Esecuzione query ["+query+"] ("+DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+") completata; "+result+" righe eliminate");
  3553.             }
  3554.             mapTabelleRigheEliminate.add(nomeTabella, result);
  3555.         } finally {
  3556.             try{
  3557.                 if(pstmt != null)
  3558.                     pstmt.close();
  3559.             } catch(Exception er) {
  3560.                 // close
  3561.             }
  3562.         }
  3563.     }
  3564.    
  3565.    








  3566.     /**
  3567.      * Ritorna le buste salvate scadute o inutilizzate (tutti gli accessi uguale a 0) nella INBOX
  3568.      *
  3569.      * @return List di stringhe contenenti gli ID delle buste scadute e/o inutilizzate con il tipo passato come parametro.
  3570.      *
  3571.      */
  3572.     public List<String> getBusteDaEliminareFromInBox(int limit,boolean logQuery,boolean forceIndex,boolean filtraBustaScadetureRispettoOraRegistrazione,boolean orderBy, Date data) throws ProtocolException{
  3573.         return this.getBusteDaEliminare(Costanti.INBOX,limit,logQuery,forceIndex,filtraBustaScadetureRispettoOraRegistrazione,orderBy, data);
  3574.     }

  3575.     /**
  3576.      * Ritorna le buste salvate scadute o inutilizzate (tutti gli accessi uguale a 0) nella OUTBOX
  3577.      *
  3578.      * @return List di stringhe contenenti gli ID delle buste scadute e/o inutilizzate con il tipo passato come parametro.
  3579.      *
  3580.      */
  3581.     public List<String> getBusteDaEliminareFromOutBox(int limit,boolean logQuery,boolean forceIndex,boolean filtraBustaScadetureRispettoOraRegistrazione,boolean orderBy, Date data) throws ProtocolException{
  3582.         return this.getBusteDaEliminare(Costanti.OUTBOX,limit,logQuery,forceIndex,filtraBustaScadetureRispettoOraRegistrazione,orderBy, data);
  3583.     }


  3584.     /**
  3585.      * Ritorna le buste salvate scadute o inutilizzate (tutti gli accessi uguale a 0)
  3586.      *
  3587.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  3588.      * @return List di stringhe contenenti gli ID delle buste scadute e/o inutilizzate con il tipo passato come parametro.
  3589.      *
  3590.      */
  3591.     private List<String> getBusteDaEliminare(String tipoBusta,int limit,boolean logQuery,boolean forceIndex,boolean filtraBustaScadetureRispettoOraRegistrazione,boolean orderBy, Date data) throws ProtocolException{

  3592.         if(this.state instanceof StatefulMessage) {

  3593.             StatefulMessage stateful = (StatefulMessage)this.state;
  3594.             Connection connectionDB = stateful.getConnectionDB();

  3595.             java.sql.Timestamp nowT = null;
  3596.             if(data!=null) {
  3597.                 nowT = new java.sql.Timestamp(data.getTime());
  3598.             }
  3599.            
  3600.             PreparedStatement pstmt = null;
  3601.             ResultSet rs = null;
  3602.             List<String> idBuste = new ArrayList<>();
  3603.             IGestoreRepository gestorerepositoryBuste = Configurazione.getGestoreRepositoryBuste();
  3604.             String queryString = null;
  3605.             try{

  3606.                 // Le buste da eliminare sono quelle che
  3607.                 // -1 sono scadute e non possiedono l'accesso da pdd o l'accesso da profilo
  3608.                 // -2 non possiedono piu' accessi da nessuna fonte
  3609.                 //      se possiedono ancora l'accesso da pdd, vuole dire che un msg e' in rollback,
  3610.                 //        e sara' eliminato l'accesso una volta consegnato con successo il msg,
  3611.                 //        o una volta scaduto il msg (rollback)
  3612.                 //      se possiedono ancora l'accesso da profilo, vuole dire che un msg e' in rollback,
  3613.                 //        e sara' eliminato una volta terminato il profilo,
  3614.                 //        o una volta scaduto il msg (rollback)

  3615.                
  3616.                 // 1 sono scadute e non possiedono l'accesso da pdd o l'accesso da profilo
  3617.                 // Viene effettuato tale filtro SOLO se il filtro delle buste scadute rispetto all'ora di registrazione è attivo.
  3618.                 // Se invece tale opzione viene disabilitata, le informazioni per effettuare il filtro duplicati
  3619.                 // vengono mantenute all'infinito.
  3620.                 // Sara' necessaria una manutenzione sistemistica del database per prevenire una crescita
  3621.                 // del database che comporta un esaurimento di risorse
  3622.                 if(filtraBustaScadetureRispettoOraRegistrazione){
  3623.                     if(Configurazione.getSqlQueryObjectType()==null){
  3624.                         StringBuilder query = new StringBuilder();
  3625.                         query.append("SELECT ");
  3626.                         if(forceIndex){
  3627.                             query.append("/*+ index("+Costanti.REPOSITORY+" "+Costanti.REPOSITORY_INDEX_SCADENZA_SEARCH+") */");
  3628.                         }
  3629.                         query.append(" ID_MESSAGGIO FROM ");
  3630.                         query.append(Costanti.REPOSITORY);
  3631.                         query.append(" WHERE SCADENZA_BUSTA < ? AND TIPO=? AND ");
  3632.                         // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3633.                         //query.append(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3634.                         //query.append(" AND ");
  3635.                         //query.append(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3636.                         query.append(gestorerepositoryBuste.createSQLCondition_enableOnlyHistory());
  3637.                         if(data!=null) {
  3638.                             query.append(" AND DATA_REGISTRAZIONE<=?");
  3639.                         }
  3640.                         queryString = query.toString();
  3641.                     }else{
  3642.                         ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  3643.                         if(forceIndex){
  3644.                             sqlQueryObject.addSelectForceIndex(Costanti.REPOSITORY, Costanti.REPOSITORY_INDEX_SCADENZA_SEARCH);
  3645.                         }
  3646.                         sqlQueryObject.addSelectField("ID_MESSAGGIO");
  3647.                         sqlQueryObject.addSelectField("ORA_REGISTRAZIONE");
  3648.                         sqlQueryObject.addSelectField("SCADENZA_BUSTA");
  3649.                         sqlQueryObject.addSelectField("TIPO");
  3650.                         sqlQueryObject.addSelectField(gestorerepositoryBuste.createSQLFields());
  3651.                         sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  3652.                         sqlQueryObject.addWhereCondition("SCADENZA_BUSTA < ?");
  3653.                         sqlQueryObject.addWhereCondition("TIPO=?");
  3654.                         // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3655.                         //sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3656.                         //sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3657.                         sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_enableOnlyHistory());
  3658.                         if(data!=null) {
  3659.                             sqlQueryObject.addWhereCondition("DATA_REGISTRAZIONE<=?");
  3660.                         }
  3661.                         sqlQueryObject.setANDLogicOperator(true);
  3662.                         if(orderBy){
  3663.                             //sqlQueryObject.addOrderBy("ORA_REGISTRAZIONE");
  3664.                             sqlQueryObject.addOrderBy("SCADENZA_BUSTA"); // almeno si usa l'indice
  3665.                             sqlQueryObject.setSortType(true);
  3666.                         }
  3667.                         sqlQueryObject.setLimit(limit);
  3668.                         queryString = sqlQueryObject.createSQLQuery();
  3669.                     }
  3670.    
  3671.                     Timestamp now = DateManager.getTimestamp();
  3672.                     //System.out.println("STRING QUERY REPOSITORY1 ["+queryString+"] 1["+now+"] 2["+tipoBusta+"]");
  3673.                     pstmt = connectionDB.prepareStatement(queryString);
  3674.                     pstmt.setTimestamp(1,now);
  3675.                     pstmt.setString(2,tipoBusta);
  3676.                     if(data!=null) {
  3677.                         pstmt.setTimestamp(3,nowT);
  3678.                     }
  3679.    
  3680.                     long startDateSQLCommand = DateManager.getTimeMillis();
  3681.                     if(logQuery)
  3682.                         this.log.debug("[QUERY] (repositoryBuste.busteScadute) ["+queryString+"] 1["+now+"] 2["+tipoBusta+"] 3["+nowT+"]...");
  3683.                     rs = pstmt.executeQuery();
  3684.                     long endDateSQLCommand = DateManager.getTimeMillis();
  3685.                     long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  3686.                     if(logQuery)
  3687.                         this.log.debug("[QUERY] (repositoryBuste.busteScadute) ["+queryString+"] 1["+now+"] 2["+tipoBusta+"] 3["+nowT+"] effettuata in "+secondSQLCommand+" secondi");
  3688.    
  3689.                     int countLimit = 0;
  3690.                     while(rs.next()){
  3691.                         idBuste.add(rs.getString("ID_MESSAGGIO"));
  3692.                         // LIMIT Applicativo
  3693.                         if(Configurazione.getSqlQueryObjectType()==null){
  3694.                             countLimit++;
  3695.                             if(countLimit==limit)
  3696.                                 break;
  3697.                         }
  3698.                     }
  3699.                     rs.close();
  3700.                     pstmt.close();
  3701.                 }

  3702.                 queryString = null;
  3703.                 if(Configurazione.getSqlQueryObjectType()==null){
  3704.                     StringBuilder query = new StringBuilder();
  3705.                     query.append("SELECT ");
  3706.                     if(forceIndex){
  3707.                         query.append("/*+ index("+Costanti.REPOSITORY+" "+Costanti.REPOSITORY_INDEX_TIPO_SEARCH+") */");
  3708.                     }
  3709.                     query.append(" ID_MESSAGGIO FROM ");
  3710.                     query.append(Costanti.REPOSITORY);
  3711.                     query.append(" WHERE TIPO=? AND ");
  3712.                     // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3713. //                  query.append(gestorerepositoryBuste.createSQLCondition_History(false));
  3714. //                  query.append(" AND ");
  3715. //                  query.append(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3716. //                  query.append(" AND ");
  3717. //                  query.append(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3718.                     query.append(gestorerepositoryBuste.createSQLCondition_disabledAll());
  3719.                     if(data!=null) {
  3720.                         query.append(" AND DATA_REGISTRAZIONE<=?");
  3721.                     }
  3722.                     queryString = query.toString();
  3723.                 }else{
  3724.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  3725.                     if(forceIndex){
  3726.                         sqlQueryObject.addSelectForceIndex(Costanti.REPOSITORY, Costanti.REPOSITORY_INDEX_TIPO_SEARCH);
  3727.                     }
  3728.                     sqlQueryObject.addSelectField("ID_MESSAGGIO");
  3729.                     sqlQueryObject.addSelectField("ORA_REGISTRAZIONE");
  3730.                     sqlQueryObject.addSelectField("TIPO");
  3731.                     sqlQueryObject.addSelectField(gestorerepositoryBuste.createSQLFields());
  3732.                     sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  3733.                     sqlQueryObject.addWhereCondition("TIPO=?");
  3734.                     // Inefficiente. Si usa il nuovo metodo dell'interfaccia
  3735. //                  sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_History(false));
  3736. //                  sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  3737. //                  sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_PdD(false));
  3738.                     sqlQueryObject.addWhereCondition(gestorerepositoryBuste.createSQLCondition_disabledAll());
  3739.                     if(data!=null) {
  3740.                         sqlQueryObject.addWhereCondition("DATA_REGISTRAZIONE<=?");
  3741.                     }
  3742.                     sqlQueryObject.setANDLogicOperator(true);
  3743.                     if(orderBy){
  3744.                         //sqlQueryObject.addOrderBy("ORA_REGISTRAZIONE");
  3745.                         sqlQueryObject.addOrderBy("SCADENZA_BUSTA"); // almeno si usa l'indice
  3746.                         sqlQueryObject.setSortType(true);
  3747.                     }
  3748.                     sqlQueryObject.setLimit(limit);
  3749.                     queryString = sqlQueryObject.createSQLQuery();
  3750.                 }
  3751.                 //System.out.println("STRING QUERY REPOSITORY2 ["+queryString+"] 1["+tipoBusta+"]");
  3752.                 pstmt = connectionDB.prepareStatement(queryString.toString());
  3753.                 pstmt.setString(1,tipoBusta);
  3754.                 if(data!=null) {
  3755.                     pstmt.setTimestamp(2,nowT);
  3756.                 }

  3757.                 long startDateSQLCommand = DateManager.getTimeMillis();
  3758.                 if(logQuery)
  3759.                     this.log.debug("[QUERY] (repositoryBuste.busteCancellateLogicamente) ["+queryString+"] 1["+tipoBusta+"] 2["+nowT+"]...");
  3760.                 rs = pstmt.executeQuery();
  3761.                 long endDateSQLCommand = DateManager.getTimeMillis();
  3762.                 long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  3763.                 if(logQuery)
  3764.                     this.log.debug("[QUERY] (repositoryBuste.busteCancellateLogicamente) ["+queryString+"] 1["+tipoBusta+"] 2["+nowT+"] effettuata in "+secondSQLCommand+" secondi");

  3765.                 int countLimit = 0;
  3766.                 while(rs.next()){
  3767.                     idBuste.add(rs.getString("ID_MESSAGGIO"));
  3768.                     // LIMIT Applicativo
  3769.                     if(Configurazione.getSqlQueryObjectType()==null){
  3770.                         countLimit++;
  3771.                         if(countLimit==limit)
  3772.                             break;
  3773.                     }
  3774.                 }
  3775.                 rs.close();
  3776.                 pstmt.close();

  3777.                 return idBuste;

  3778.             } catch(Exception e) {
  3779.                 String errorMsg = "[repositoryBuste.getBusteDaEliminare] errore, queryString["+queryString+"]: "+e.getMessage();
  3780.                 this.log.error(errorMsg,e);
  3781.                 try{
  3782.                     if(rs != null)
  3783.                         rs.close();
  3784.                 } catch(Exception er) {
  3785.                     // Eccezione SQL.
  3786.                 }
  3787.                 try{
  3788.                     if(pstmt != null)
  3789.                         pstmt.close();
  3790.                 } catch(Exception er) {
  3791.                     // Eccezione SQL.
  3792.                 }
  3793.                 throw new ProtocolException(errorMsg,e);
  3794.             }
  3795.         }else{
  3796.             throw new ProtocolException("Metodo non invocabile in stateless mode");
  3797.         }
  3798.     }

  3799.    
  3800.    
  3801.     /**
  3802.      * Metodo che si occupa di impostare l'indicazione di utilizzo della busta dalla PdD
  3803.      *
  3804.      * @param id identificativo della busta.
  3805.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  3806.      *
  3807.      */
  3808.     public void impostaUtilizzoPdD(String id,String tipoBusta) throws ProtocolException{

  3809.         StateMessage stateMSG = (StateMessage)this.state;
  3810.         Connection connectionDB = stateMSG.getConnectionDB();

  3811.         PreparedStatement pstmtUpdate = null;
  3812.         try{

  3813.             StringBuilder queryUpdate = new StringBuilder();
  3814.             queryUpdate.append("UPDATE ");
  3815.             queryUpdate.append(Costanti.REPOSITORY);
  3816.             queryUpdate.append(" SET ");
  3817.             queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_PdD(true));
  3818.             queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  3819.             pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  3820.             pstmtUpdate.setString(1,id);
  3821.             pstmtUpdate.setString(2,tipoBusta);

  3822.             // Add PreparedStatement
  3823.             stateMSG.getPreparedStatement().put("UPDATE AggiornamentoBusta_setUtilizzoPdD"+tipoBusta+"_"+id,pstmtUpdate);

  3824.         } catch(Exception e) {
  3825.             String errorMsg = "REPOSITORY_BUSTE, Errore di impostazione utilizzo from PdD "+tipoBusta+"/"+id+": "+e.getMessage();
  3826.             this.log.error(errorMsg,e);
  3827.             try{
  3828.                 if(pstmtUpdate != null)
  3829.                     pstmtUpdate.close();
  3830.             } catch(Exception er) {
  3831.                 // Eccezione SQL.
  3832.             }
  3833.             throw new ProtocolException(errorMsg,e);
  3834.         }

  3835.     }

  3836.    
  3837.    
  3838.     public boolean exists(String id,String tipoBusta) throws ProtocolException{

  3839.         StateMessage stateMSG = (StateMessage)this.state;
  3840.         Connection connectionDB = stateMSG.getConnectionDB();

  3841.         PreparedStatement pstmt = null;
  3842.         ResultSet rs = null;
  3843.         try{

  3844.             StringBuilder queryUpdate = new StringBuilder();
  3845.             queryUpdate.append("SELECT ID_MESSAGGIO FROM ");
  3846.             queryUpdate.append(Costanti.REPOSITORY);
  3847.             queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=? AND (");
  3848.             queryUpdate.append(this.gestoreRepositoryBuste.createSQLCondition_History(true));
  3849.             queryUpdate.append(" OR ");
  3850.             queryUpdate.append(this.gestoreRepositoryBuste.createSQLCondition_PdD(true));
  3851.             queryUpdate.append(" OR ");
  3852.             queryUpdate.append(this.gestoreRepositoryBuste.createSQLCondition_ProfiloCollaborazione(true));
  3853.             queryUpdate.append(" ) ");
  3854.             pstmt = connectionDB.prepareStatement(queryUpdate.toString());
  3855.             pstmt.setString(1,id);
  3856.             pstmt.setString(2,tipoBusta);
  3857.             rs = pstmt.executeQuery();
  3858.             if(rs==null){
  3859.                 throw new Exception("Result set is null??");
  3860.             }
  3861.             boolean value = rs.next();
  3862.             rs.close();
  3863.             pstmt.close();
  3864.             return value;

  3865.         } catch(Exception e) {
  3866.             String errorMsg = "REPOSITORY_BUSTE, Errore durante l'utilizzo di exists "+tipoBusta+"/"+id+": "+e.getMessage();
  3867.             this.log.error(errorMsg,e);
  3868.             try{
  3869.                 if(rs != null)
  3870.                     rs.close();
  3871.             } catch(Exception er) {
  3872.                 // Eccezione SQL.
  3873.             }
  3874.             try{
  3875.                 if(pstmt != null)
  3876.                     pstmt.close();
  3877.             } catch(Exception er) {
  3878.                 // Eccezione SQL.
  3879.             }
  3880.             throw new ProtocolException(errorMsg,e);
  3881.         }

  3882.     }
  3883.    
  3884.     public boolean isRegistrazioneInCorso() {
  3885.         if(this.state!=null) {
  3886.             StateMessage stateMSG = (StateMessage)this.state;
  3887.             if(stateMSG.getPreparedStatement()!=null && stateMSG.getPreparedStatement().size()>0) {
  3888.                 List<String> keys = stateMSG.getPreparedStatement().keys();
  3889.                 if(keys!=null && !keys.isEmpty()) {
  3890.                     for (String key : keys) {
  3891.                         if(key!=null && key.startsWith("INSERT")) {
  3892.                             return true;
  3893.                         }
  3894.                         else if(key!=null && key.startsWith("UPDATE")) {
  3895.                             return true;
  3896.                         }
  3897.                     }
  3898.                 }
  3899.             }
  3900.         }
  3901.         return false;
  3902.     }
  3903. }