ProfiloDiCollaborazione.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.util.ArrayList;
  25. import java.util.Date;
  26. import java.util.List;

  27. import org.openspcoop2.core.id.IDServizio;
  28. import org.openspcoop2.core.id.IDSoggetto;
  29. import org.openspcoop2.core.registry.driver.IDServizioFactory;
  30. import org.openspcoop2.protocol.engine.Configurazione;
  31. import org.openspcoop2.protocol.engine.LetturaParametriBusta;
  32. import org.openspcoop2.protocol.engine.constants.Costanti;
  33. import org.openspcoop2.protocol.engine.driver.repository.IGestoreRepository;
  34. import org.openspcoop2.protocol.registry.RegistroServiziManager;
  35. import org.openspcoop2.protocol.registry.RisultatoValidazione;
  36. import org.openspcoop2.protocol.sdk.Busta;
  37. import org.openspcoop2.protocol.sdk.Eccezione;
  38. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  39. import org.openspcoop2.protocol.sdk.Integrazione;
  40. import org.openspcoop2.protocol.sdk.ProtocolException;
  41. import org.openspcoop2.protocol.sdk.config.IProtocolConfiguration;
  42. import org.openspcoop2.protocol.sdk.config.IProtocolManager;
  43. import org.openspcoop2.protocol.sdk.config.ITraduttore;
  44. import org.openspcoop2.protocol.sdk.constants.ErroriCooperazione;
  45. import org.openspcoop2.protocol.sdk.constants.TipoOraRegistrazione;
  46. import org.openspcoop2.protocol.sdk.state.IState;
  47. import org.openspcoop2.protocol.sdk.state.StateMessage;
  48. import org.openspcoop2.protocol.sdk.state.StatefulMessage;
  49. import org.openspcoop2.protocol.sdk.state.StatelessMessage;
  50. import org.openspcoop2.utils.LoggerWrapperFactory;
  51. import org.openspcoop2.utils.Utilities;
  52. import org.openspcoop2.utils.date.DateManager;
  53. import org.openspcoop2.utils.jdbc.JDBCUtilities;
  54. import org.openspcoop2.utils.sql.ISQLQueryObject;
  55. import org.openspcoop2.utils.sql.SQLObjectFactory;
  56. import org.slf4j.Logger;

  57. /**
  58.  * Sono inclusi i metodi per la gestione del profilo di collaborazione.
  59.  * Tutti i metodi hanno bisogno di una connessione ad un DB, precedentemente impostata
  60.  * e passata attraverso l'apposito metodo.
  61.  *
  62.  *
  63.  * @author Poli Andrea (apoli@link.it)
  64.  * @author Tronci Fabio (tronci@link.it)
  65.  * @author $Author$
  66.  * @version $Rev$, $Date$
  67.  */

  68. public class ProfiloDiCollaborazione {
  69.    
  70.     /** Logger utilizzato per debug. */
  71.     private Logger log = null;

  72.     private IState state;

  73.     /** GestoreRepository */
  74.     private IGestoreRepository gestoreRepositoryBuste;
  75.    
  76.     private IProtocolFactory<?> protocolFactory;
  77.     private IProtocolConfiguration protocolConfiguration;
  78.     private IProtocolManager protocolManager;
  79.     private ITraduttore protocolTraduttore;
  80.    
  81.     private void initProtocolFactory(IProtocolFactory<?> protocolFactory) throws ProtocolException{
  82.         this.protocolFactory = protocolFactory;
  83.         this.protocolManager = this.protocolFactory.createProtocolManager();
  84.         this.protocolTraduttore = this.protocolFactory.createTraduttore();
  85.         this.protocolConfiguration = this.protocolFactory.createProtocolConfiguration();
  86.     }

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

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


  116.     public void updateState(IState state){
  117.         this.state = state;
  118.     }
  119.    

  120.     /* ********  PROFILO GENERICO  ******** */

  121.     /**
  122.      * Metodo che si occupa di salvare una busta, precedentemente registrata,
  123.      * tra le buste usate per la gestione del Profilo di Collaborazione.
  124.      *
  125.      * @param id identificativo della busta da salvare.
  126.      *
  127.      */
  128.     public void registraBustaInviata(String id) throws ProtocolException{
  129.         registraBusta(id,Costanti.OUTBOX);
  130.     }
  131.     /**
  132.      * Metodo che si occupa di eliminare una busta, precedentemente registrata,
  133.      * tra le buste usate per la gestione del Profilo di Collaborazione.
  134.      *
  135.      * @param id identificativo della busta da eliminare.
  136.      *
  137.      */
  138.     public void eliminaBustaInviata(String id,boolean forzaEliminazioneDB) throws ProtocolException{
  139.         eliminaBusta(id,Costanti.OUTBOX,forzaEliminazioneDB);
  140.     }
  141.     public void eliminaBustaInviata(String id) throws ProtocolException{
  142.         eliminaBusta(id,Costanti.OUTBOX);
  143.     }

  144.     /**
  145.      * Metodo che si occupa di salvare una busta, precedentemente registrata,
  146.      * tra le buste usate per la gestione del Profilo di Collaborazione.
  147.      *
  148.      * @param id identificativo della busta da salvare.
  149.      *
  150.      */
  151.     public void registraBustaRicevuta(String id) throws ProtocolException{
  152.         registraBusta(id,Costanti.INBOX);
  153.     }
  154.     /**
  155.      * Metodo che si occupa di eliminare una busta, precedentemente registrata,
  156.      * tra le buste usate per la gestione del Profilo di Collaborazione.
  157.      *
  158.      * @param id identificativo della busta da eliminare.
  159.      *
  160.      */
  161.     public void eliminaBustaRicevuta(String id,boolean forzaEliminazioneDB) throws ProtocolException{
  162.         eliminaBusta(id,Costanti.INBOX,forzaEliminazioneDB);
  163.     }
  164.     public void eliminaBustaRicevuta(String id) throws ProtocolException{
  165.         eliminaBusta(id,Costanti.INBOX);
  166.     }

  167.     /**
  168.      * Metodo che si occupa di salvare una busta, precedentemente registrata,
  169.      * tra le buste usate per la gestione del Profilo di Collaborazione.
  170.      *
  171.      * @param id identificativo della busta da salvare.
  172.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  173.      *
  174.      */
  175.     public void registraBusta(String id,String tipoBusta) throws ProtocolException{

  176.         if(this.state instanceof StatefulMessage) {
  177.             StatefulMessage stateful = (StatefulMessage)this.state;
  178.             Connection connectionDB = stateful.getConnectionDB();

  179.             PreparedStatement pstmtUpdate = null;
  180.             try{    

  181.                 StringBuilder queryUpdate = new StringBuilder();
  182.                 queryUpdate.append("UPDATE ");
  183.                 queryUpdate.append(Costanti.REPOSITORY);
  184.                 queryUpdate.append(" SET ");
  185.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_ProfiloCollaborazione(true));
  186.                 queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  187.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  188.                 pstmtUpdate.setString(1,id);
  189.                 pstmtUpdate.setString(2,tipoBusta);

  190.                 // Add PreparedStatement
  191.                 stateful.getPreparedStatement().put("UPDATE saveBustaForProfilo"+tipoBusta+"_"+id,pstmtUpdate);

  192.             } catch(Exception e) {
  193.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE, Errore di registrazione "+tipoBusta+"/"+id+": "+e.getMessage();      
  194.                 this.log.error(errorMsg,e);
  195.                 try{
  196.                     if( pstmtUpdate != null )
  197.                         pstmtUpdate.close();
  198.                 } catch(Exception er) {
  199.                     // Eccezione SQL.
  200.                 }
  201.                 throw new ProtocolException(errorMsg,e);
  202.             }
  203.         }
  204.         else {  //NOP
  205.         }
  206.     }
  207.     /**
  208.      * Metodo che si occupa di eliminare una busta, precedentemente registrata,
  209.      * tra le buste usate per la gestione del Profilo di Collaborazione..
  210.      *
  211.      * @param id identificativo della busta da salvare.
  212.      * @param tipoBusta Indicazione sul tipo di busta inviata/ricevuta
  213.      *
  214.      */
  215.     public void eliminaBusta(String id,String tipoBusta) throws ProtocolException{
  216.         this.eliminaBusta(id, tipoBusta, false);
  217.     }
  218.     public void eliminaBusta(String id,String tipoBusta, boolean forzaEliminazioneDB) throws ProtocolException{
  219.         if(this.state instanceof StatefulMessage  ||  forzaEliminazioneDB) {
  220.             StateMessage state = (StateMessage)this.state;
  221.             Connection connectionDB = state.getConnectionDB();

  222.             PreparedStatement pstmtUpdate = null;
  223.             try{    

  224.                 StringBuilder queryUpdate = new StringBuilder();
  225.                 queryUpdate.append("UPDATE ");
  226.                 queryUpdate.append(Costanti.REPOSITORY);
  227.                 queryUpdate.append(" SET ");
  228.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_ProfiloCollaborazione(false));
  229.                 queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  230.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  231.                 pstmtUpdate.setString(1,id);
  232.                 pstmtUpdate.setString(2,tipoBusta);

  233.                 // Add PreparedStatement
  234.                 state.getPreparedStatement().put("UPDATE eliminaBustaForProfilo"+tipoBusta+"_"+id,pstmtUpdate);

  235.             } catch(Exception e) {
  236.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE, Errore di cancellazione "+tipoBusta+"/"+id+": "+e.getMessage();      
  237.                 this.log.error(errorMsg,e);
  238.                 try{
  239.                     if( pstmtUpdate != null )
  240.                         pstmtUpdate.close();
  241.                 } catch(Exception er) {
  242.                     // Eccezione SQL.
  243.                 }
  244.                 throw new ProtocolException(errorMsg,e);
  245.             }
  246.         }
  247.     }


  248.     /* ********  PROFILO SINCRONO  ******** */

  249.     /**
  250.      * Controlla se e' stato precedentemente registrata una richiesta sincrona.
  251.      *
  252.      * @param riferimentoMessaggio Identificativo.
  253.      * @return true se esiste una entry nella tabella apposita.
  254.      *
  255.      */
  256.     public boolean sincrono_validazioneRiferimentoMessaggio(String riferimentoMessaggio) throws ProtocolException{
  257.         if(this.state instanceof StatefulMessage) {
  258.             StatefulMessage stateful = (StatefulMessage)this.state;
  259.             try{
  260.                 RepositoryBuste repositoryBuste = new RepositoryBuste(stateful, this.log, this.protocolFactory);
  261.                 if(repositoryBuste.isRegistrataIntoOutBox(riferimentoMessaggio)){
  262.                     return true;
  263.                 }else{
  264.                     return false;
  265.                 }
  266.             }catch(Exception e){    
  267.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_SINCRONO, Errore durante la sincrono_validazioneRiferimentoMessaggio "+riferimentoMessaggio+": "+e.getMessage();      
  268.                 this.log.error(errorMsg);
  269.                 return false;
  270.             }
  271.         }
  272.         else {
  273.             //TODO CHECKME
  274.             return true;
  275.         }
  276.     }

  277.     /**
  278.      * Valida la collaborazione utilizzata
  279.      *
  280.      * @param riferimentoMessaggio Identificativo.
  281.      * @return true se la collaborazione e' valida
  282.      *
  283.      */
  284.     public boolean sincrono_validazioneCollaborazione(String riferimentoMessaggio,String idCollaborazione) throws ProtocolException{
  285.         if(this.state instanceof StatefulMessage) {
  286.             StatefulMessage stateful = (StatefulMessage)this.state;

  287.             try{
  288.                 RepositoryBuste repositoryBuste = new RepositoryBuste(stateful, this.log, this.protocolFactory);
  289.                 if(repositoryBuste.isRegistrataIntoOutBox(riferimentoMessaggio)){
  290.                     return idCollaborazione.equals(repositoryBuste.getCollaborazioneFromOutBox(riferimentoMessaggio));
  291.                 }else{
  292.                     return false;
  293.                 }
  294.             }catch(Exception e){    
  295.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_SINCRONO, Errore durante la sincrono_validazioneRiferimentoMessaggio "+riferimentoMessaggio+": "+e.getMessage();      
  296.                 this.log.error(errorMsg);
  297.                 return false;
  298.             }
  299.         }
  300.         else{ //TODO CHECKME
  301.             return true;
  302.         }
  303.     }


  304.     /**
  305.      * Controlla se e' stato precedentemente registrata una richiesta sincrona.
  306.      *
  307.      * @param id Identificativo.
  308.      *
  309.      */
  310.     public void sincrono_eliminaRichiestaInOutBox(String id) throws ProtocolException{
  311.         try{
  312.             this.eliminaBustaInviata(id);
  313.         }catch(ProtocolException e){    
  314.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_SINCRONO, Errore durante la sincrono_eliminaRichiestaInOutBox "+id+": "+e.getMessage();        
  315.             this.log.error(errorMsg);
  316.             throw e;
  317.         }
  318.     }

  319.     /**
  320.      * Costruisce una {@link org.openspcoop2.protocol.sdk.Busta} inizializzata con
  321.      * tutte le informazioni necessarie per costruire la busta di ritorno in cui includere
  322.      * il risultato applicativo da spedire alla porta di dominio mittente.
  323.      * La costruire dell'apposita risposta comportera' vari aspetti come : rifMsg = id precedente ,
  324.      * Mitt e Dest scambiati , nuova OraRegistrazione e ID, ecc...
  325.      * <p>
  326.      * In caso in cui la busta di ritorno venga costruita con successo, l'entry verra' cancellata dalla tabella.
  327.      *
  328.      * @param id ID della busta contenente la richiesta sincrona.
  329.      * @return {@link org.openspcoop2.protocol.sdk.Busta} inizializzata per la costruzione della risposta sincrona in caso di successo,
  330.      *         null altrimenti.
  331.      *
  332.      */
  333.     public Busta sincrono_generaBustaRisposta(String id,TipoOraRegistrazione tipoTempo) throws ProtocolException {

  334.         StateMessage stateMSG = (StateMessage)this.state;
  335.         Busta busta = null;
  336.         try{
  337.             RepositoryBuste repository = new RepositoryBuste(stateMSG, this.log, this.protocolFactory);
  338.             LetturaParametriBusta parametri = new LetturaParametriBusta();
  339.             parametri.setMittente(true);
  340.             parametri.setDestinatario(true);
  341.             parametri.setServizio(true);
  342.             parametri.setAzione(true);
  343.             parametri.setCollaborazione(true);
  344.             parametri.setProfiloTrasmissione(true);
  345.             parametri.setIndirizziTelematici(this.protocolConfiguration.isSupportoIndirizzoRisposta());
  346.             busta = repository.getSomeValuesFromInBox(id, parametri);
  347.         }catch(Exception e){
  348.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_SINCRONO, Errore durante la getBusta dal repository "+id+": "+e.getMessage();      
  349.             this.log.error(errorMsg,e);
  350.             throw new ProtocolException(errorMsg,e);
  351.         }

  352.         // inverto mitt con dest
  353.         String mitt = busta.getMittente();
  354.         String tipoMitt = busta.getTipoMittente();
  355.         String portaMitt = busta.getIdentificativoPortaMittente();
  356.         String indMitt = busta.getIndirizzoMittente();
  357.         busta.setMittente(busta.getDestinatario());
  358.         busta.setTipoMittente(busta.getTipoDestinatario());
  359.         busta.setIdentificativoPortaMittente(busta.getIdentificativoPortaDestinatario());
  360.         busta.setIndirizzoMittente(busta.getIndirizzoDestinatario());
  361.         busta.setDestinatario(mitt);
  362.         busta.setTipoDestinatario(tipoMitt);
  363.         busta.setIdentificativoPortaDestinatario(portaMitt);
  364.         busta.setIndirizzoDestinatario(indMitt);

  365.         // ProfiloDiCollaborazione
  366.         busta.setProfiloDiCollaborazione(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.SINCRONO);

  367.         // ID
  368.         busta.setRiferimentoMessaggio(id);

  369.         // OraRegistrazione
  370.         busta.setOraRegistrazione(DateManager.getDate());
  371.         busta.setTipoOraRegistrazione(tipoTempo,this.protocolTraduttore.toString(tipoTempo));

  372.         // la busta non serve piu' per il profilo di collaborazione
  373.         this.eliminaBustaRicevuta(busta.getRiferimentoMessaggio());

  374.         return busta;

  375.     }

  376.     /**
  377.      * Effettua una validazione della busta di risposta che sia in correlazione con la richiesta.
  378.      *
  379.      * @param bustaDaValidare Busta da controllare
  380.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  381.      *
  382.      */
  383.     public Eccezione sincrono_validazioneCorrelazione(Busta bustaDaValidare, IProtocolFactory<?> protocolFactory) throws ProtocolException {
  384.         if(this.state instanceof StatefulMessage) {
  385.             StatefulMessage stateful = (StatefulMessage)this.state;

  386.             Busta bustaRichiesta = null;
  387.             try{
  388.                 RepositoryBuste repository = new RepositoryBuste(stateful, this.log, this.protocolFactory);
  389.                 LetturaParametriBusta parametri = new LetturaParametriBusta();
  390.                 parametri.setMittente(true);
  391.                 parametri.setDestinatario(true);
  392.                 parametri.setServizio(true);
  393.                 parametri.setAzione(true);
  394.                 bustaRichiesta = repository.getSomeValuesFromOutBox(bustaDaValidare.getRiferimentoMessaggio(), parametri);
  395.             } catch(Exception e) {
  396.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_SINCRONO, Errore durante la sincrono_validazioneCorrelazione, get dal repository "+bustaDaValidare.getRiferimentoMessaggio()+": "+e.getMessage();      
  397.                 this.log.error(errorMsg,e);
  398.                 throw new ProtocolException(errorMsg,e);
  399.             }

  400.             // validazione
  401.             if (bustaRichiesta.getTipoDestinatario().equals(bustaDaValidare.getTipoMittente())==false){
  402.                 String msgErrore = "Tipo del mittente diverso da quello atteso nella gestione del profilo di collaborazione Sincrono";
  403.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_MITTENTE_NON_VALIDO.
  404.                         getErroreCooperazione(msgErrore),
  405.                         true,null,protocolFactory);
  406.                 this.log.error(msgErrore);
  407.                 return eccValidazione;
  408.             }
  409.             if (bustaRichiesta.getDestinatario().equals(bustaDaValidare.getMittente())==false){
  410.                 String msgErrore = "Mittente diverso da quello atteso nella gestione del profilo di collaborazione Sincrono";
  411.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.MITTENTE_NON_VALIDO.
  412.                         getErroreCooperazione(msgErrore),
  413.                         true,null,protocolFactory);
  414.                 this.log.error(msgErrore);
  415.                 return eccValidazione;
  416.             }
  417.             if (bustaRichiesta.getTipoMittente().equals(bustaDaValidare.getTipoDestinatario())==false){
  418.                 String msgErrore = "Tipo del destinatario diverso da quello atteso nella gestione del profilo di collaborazione Sincrono";
  419.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_DESTINATARIO_NON_VALIDO.
  420.                         getErroreCooperazione(msgErrore),
  421.                         true,null,protocolFactory);
  422.                 this.log.error(msgErrore);
  423.                 return eccValidazione;
  424.             }
  425.             if (bustaRichiesta.getMittente().equals(bustaDaValidare.getDestinatario())==false){
  426.                 String msgErrore = "Destinatario diverso da quello atteso nella gestione del profilo di collaborazione Sincrono";
  427.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.DESTINATARIO_NON_VALIDO.
  428.                         getErroreCooperazione(msgErrore),
  429.                         true,null,protocolFactory);
  430.                 this.log.error(msgErrore);
  431.                 return eccValidazione;
  432.             }

  433.             if(bustaDaValidare.getServizio()!=null && bustaDaValidare.getTipoServizio()!=null){
  434.                 if (bustaRichiesta.getTipoServizio().equals(bustaDaValidare.getTipoServizio())==false){
  435.                     String msgErrore = "Tipo di servizio diverso da quello atteso nella gestione del profilo di collaborazione Sincrono";
  436.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_SERVIZIO_NON_VALIDO.
  437.                             getErroreCooperazione(msgErrore),
  438.                             true,null,protocolFactory);
  439.                     this.log.error(msgErrore);
  440.                     return eccValidazione;
  441.                 }
  442.                 if (bustaRichiesta.getServizio().equals(bustaDaValidare.getServizio())==false){
  443.                     String msgErrore = "Servizio diverso da quello atteso nella gestione del profilo di collaborazione Sincrono";
  444.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.SERVIZIO_NON_VALIDO.
  445.                             getErroreCooperazione(msgErrore),
  446.                             true,null,protocolFactory);
  447.                     this.log.error(msgErrore);
  448.                     return eccValidazione;
  449.                 }
  450.                 if(bustaDaValidare.getAzione()!=null){
  451.                     if (bustaDaValidare.getAzione().equals(bustaRichiesta.getAzione()) == false){
  452.                         String msgErrore = "Azione diversa da quello atteso nella gestione del profilo di collaborazione Sincrono";
  453.                         Eccezione eccValidazione = new Eccezione(ErroriCooperazione.AZIONE_NON_VALIDA.
  454.                                 getErroreCooperazione(msgErrore),
  455.                                 true,null,protocolFactory);
  456.                         this.log.error(msgErrore);
  457.                         return eccValidazione;
  458.                     }
  459.                 }
  460.             }

  461.             return null;
  462.         }

  463.         else{
  464.             //CHECKME
  465.             return null;
  466.         }
  467.     }


  468.     /* ********  PROFILO ASINCRONO SIMMETRICO ******** */

  469.     /**
  470.      * Registrazione di una richiesta inviata.
  471.      * Viene mantenuto nella tabella asincrona una entry con ID_MESSAGGIO, OUTBOX, dataInvio(serve per la respedizione)
  472.      * e ServizioCorrelato inserito nella richiesta.
  473.      *
  474.      * @param id Identificativo della richiesta
  475.      * @param tipoServizioCorrelato Tipo del Servizio Correlato
  476.      * @param servizioCorrelato Servizio Correlato
  477.      * @param ricevutaApplicativa Indicazione sull'abilitazione di una ricevuta applicativa
  478.      */
  479.     public void asincronoSimmetrico_registraRichiestaInviata(String id,String idCollaborazione,
  480.             String tipoServizioCorrelato,String servizioCorrelato,Integer versioneServizioCorrelato,
  481.             boolean ricevutaApplicativa,Integrazione integrazione,
  482.             long scadenzaMessaggi) throws ProtocolException{
  483.        
  484.         StateMessage state = (StateMessage)this.state;
  485.         Connection connectionDB = state.getConnectionDB();

  486.         PreparedStatement pstmt = null;
  487.         PreparedStatement pstmtUpdate = null;
  488.         try{    

  489.             java.sql.Timestamp oraInvio = DateManager.getTimestamp();

  490.             StringBuilder query = new StringBuilder();
  491.             query.append("INSERT INTO  ");
  492.             query.append(Costanti.PROFILO_ASINCRONO);
  493.             query.append(" (ID_MESSAGGIO,TIPO,ORA_REGISTRAZIONE,RICEVUTA_ASINCRONA,TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO");
  494.             query.append(",IS_RICHIESTA,ID_ASINCRONO,ID_COLLABORAZIONE,RICEVUTA_APPLICATIVA) ");
  495.             query.append(" VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? )");

  496.             pstmt = connectionDB.prepareStatement(query.toString());
  497.             int index = 1;
  498.             pstmt.setString(index++,id);
  499.             pstmt.setString(index++,Costanti.OUTBOX);
  500.             pstmt.setTimestamp(index++,oraInvio);
  501.             pstmt.setInt(index++,0); // stato ricevuta: attesa
  502.             pstmt.setString(index++,tipoServizioCorrelato);
  503.             pstmt.setString(index++,servizioCorrelato);
  504.             if(versioneServizioCorrelato!=null){
  505.                 pstmt.setInt(index++,versioneServizioCorrelato);
  506.             }
  507.             else{
  508.                 pstmt.setNull(index++, java.sql.Types.INTEGER);
  509.             }
  510.             pstmt.setInt(index++,1); // is richiesta
  511.             pstmt.setString(index++,id); // idasincrono utilizzato per identificare questa instanza di cooperazione asincrona
  512.             pstmt.setString(index++,idCollaborazione); // idcollaborazione
  513.             if(ricevutaApplicativa){
  514.                 pstmt.setInt(index++,1); // ricevuta applicativa abilitata
  515.             }else{
  516.                 pstmt.setInt(index++,0); // ricevuta applicativa non abilitata
  517.             }

  518.             //  Add PreparedStatement
  519.             state.getPreparedStatement().put("INSERT save_RichiestaAsincronaSimmetricaInviata"+id,pstmt);

  520.             if(this.state instanceof StatefulMessage) {
  521.                
  522.                 // salvo busta per profilo
  523.                 this.registraBustaInviata(id);
  524.                
  525.             }else{
  526.                
  527.                 StatelessMessage statelessMessage = (StatelessMessage) this.state;
  528.                
  529.                 // Registro proprio la busta
  530.                 RepositoryBuste repository = new RepositoryBuste(this.state, this.log, true, this.protocolFactory);
  531.                 long scadenza = scadenzaMessaggi;
  532.                 if(scadenza<=0){
  533.                     scadenza = this.protocolManager.getIntervalloScadenzaBuste();
  534.                 }
  535.                 repository.registraBustaIntoOutBox(statelessMessage.getBusta(),scadenza);
  536.                 repository.aggiornaInfoIntegrazioneIntoOutBox(id,integrazione);
  537.                 this.registraBustaInviata(id);
  538.                
  539.                 // salvo busta per profilo
  540.                 StringBuilder queryUpdate = new StringBuilder();
  541.                 queryUpdate.append("UPDATE ");
  542.                 queryUpdate.append(Costanti.REPOSITORY);
  543.                 queryUpdate.append(" SET ");
  544.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_ProfiloCollaborazione(true));
  545.                 queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  546.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  547.                 pstmtUpdate.setString(1,id);
  548.                 pstmtUpdate.setString(2,Costanti.OUTBOX);

  549.                 // Add PreparedStatement
  550.                 state.getPreparedStatement().put("UPDATE saveBustaForProfilo"+Costanti.OUTBOX+"_"+id,pstmtUpdate);
  551.             }

  552.         } catch(Exception e) {
  553.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore di registrazione richiesta inviata "+id+": "+e.getMessage();      
  554.             this.log.error(errorMsg,e);
  555.             try{
  556.                 if( pstmt != null )
  557.                     pstmt.close();
  558.             } catch(Exception er) {
  559.                 // Eccezione SQL.
  560.             }
  561.             try{
  562.                 if( pstmtUpdate != null )
  563.                     pstmtUpdate.close();
  564.             } catch(Exception er) {
  565.                 // Eccezione SQL.
  566.             }
  567.             throw new ProtocolException(errorMsg,e);
  568.         }
  569.     }

  570.     /**
  571.      * Controlla se e' stato precedentemente registrata una richiesta asincrona simmetrica,
  572.      * ritornando eventuali dati dell'integrazione per la consegna della risposta.
  573.      *
  574.      * @param riferimentoMessaggio RiferimentoMessaggio
  575.      * @return Dati di integrazione per la consegna della risposta
  576.      *
  577.      */
  578.     public Integrazione asincronoSimmetrico_getDatiConsegnaRisposta(String riferimentoMessaggio) throws ProtocolException{
  579.         StateMessage state = (StateMessage)this.state;
  580.         try{    
  581.             // I dati asincroni saranno eliminati quando scadra' la busta asincrona
  582.             History history = new History(state,this.log);
  583.             history.registraBustaInviata(riferimentoMessaggio);

  584.             // Prendo i dati di integrazione
  585.             RepositoryBuste repositoryBuste = new RepositoryBuste(state,  this.log, this.protocolFactory);
  586.             Integrazione integrazione = repositoryBuste.getInfoIntegrazioneFromOutBox(riferimentoMessaggio);
  587.             if(integrazione==null)
  588.                 throw new Exception("Dati di integrazione non trovati");
  589.             else
  590.                 return integrazione;

  591.         } catch(Exception e) {
  592.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore durante la asincronoSimmetrico_getDatiConsegnaRisposta "+riferimentoMessaggio+": "+e.getMessage();    
  593.             this.log.error(errorMsg,e);
  594.             throw new ProtocolException(errorMsg,e);
  595.         }
  596.     }

  597.     /**
  598.      * Controlla se e' stato precedentemente registrata una richiesta asincrona simmetrica,
  599.      * ritornando eventuali dati dell'integrazione per la consegna della ricevuta.
  600.      *
  601.      * @return Dati di integrazione per la consegna della risposta
  602.      *
  603.      */
  604.     public Integrazione asincronoSimmetrico_getDatiConsegnaRicevuta(String riferimentoMessaggio) throws ProtocolException{
  605.         StateMessage state = (StateMessage)this.state;
  606.         try{    
  607.             // Prendo i dati di integrazione
  608.             RepositoryBuste repositoryBuste = new RepositoryBuste(state,  this.log, this.protocolFactory);
  609.             Integrazione integrazione = repositoryBuste.getInfoIntegrazioneFromOutBox(riferimentoMessaggio);
  610.             if(integrazione==null)
  611.                 throw new Exception("Dati di integrazione non trovati");
  612.             else
  613.                 return integrazione;

  614.         } catch(Exception e) {
  615.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore durante la asincronoSimmetrico_getDatiConsegnaRicevuta "+riferimentoMessaggio+": "+e.getMessage();    
  616.             this.log.error(errorMsg,e);
  617.             throw new ProtocolException(errorMsg,e);
  618.         }

  619.     }

  620.     /**
  621.      * Registrazione di una richiesta ricevuta.
  622.      * Viene mantenuto nella tabella asincrona una entry con ID_MESSAGGIO, INBOX
  623.      * e ServizioCorrelato inserito nella richiesta.
  624.      *
  625.      * @param id Identificativo della richiesta
  626.      * @param tipoServizioCorrelato Tipo del Servizio Correlato
  627.      * @param servizioCorrelato Servizio Correlato
  628.      * @param ricevutaApplicativa Indicazione sull'abilitazione di una ricevuta applicativa
  629.      */
  630.     public void asincronoSimmetrico_registraRichiestaRicevuta(String id,String idCollaborazione,
  631.             String tipoServizioCorrelato,String servizioCorrelato, Integer versioneServizioCorrelato,
  632.             boolean ricevutaApplicativa,long scadenzaMessaggi)throws ProtocolException{
  633.         StateMessage state = (StateMessage)this.state;
  634.         Connection connectionDB = state.getConnectionDB();
  635.         PreparedStatement pstmt = null;
  636.         PreparedStatement pstmtUpdate = null;
  637.         ResultSet rs = null;
  638.         try{    

  639.             java.sql.Timestamp oraRicezione = DateManager.getTimestamp();

  640.             StringBuilder querySearch = new StringBuilder();
  641.             querySearch.append("SELECT ID_MESSAGGIO FROM ");
  642.             querySearch.append(Costanti.PROFILO_ASINCRONO);
  643.             querySearch.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  644.             pstmt = connectionDB.prepareStatement(querySearch.toString());
  645.             pstmt.setString(1,id);
  646.             pstmt.setString(2,Costanti.INBOX);
  647.             rs = pstmt.executeQuery();
  648.             boolean exists = rs.next();
  649.             rs.close();
  650.             pstmt.close();

  651.             StringBuilder query = new StringBuilder();
  652.             if(exists){
  653.                 query.append("UPDATE ");
  654.                 query.append(Costanti.PROFILO_ASINCRONO);
  655.                 query.append(" SET ID_MESSAGGIO=?,TIPO=?,ORA_REGISTRAZIONE=?,RICEVUTA_ASINCRONA=?,TIPO_SERVIZIO_CORRELATO=?,SERVIZIO_CORRELATO=?,VERSIONE_SERVIZIO_CORRELATO=?," +
  656.                 "IS_RICHIESTA=?,ID_ASINCRONO=?,ID_COLLABORAZIONE=?,RICEVUTA_APPLICATIVA=? WHERE ID_MESSAGGIO=? AND TIPO=?");
  657.             }else{
  658.                 query.append("INSERT INTO  ");
  659.                 query.append(Costanti.PROFILO_ASINCRONO);
  660.                 query.append(" (ID_MESSAGGIO,TIPO,ORA_REGISTRAZIONE,RICEVUTA_ASINCRONA,TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO");
  661.                 query.append(",IS_RICHIESTA,ID_ASINCRONO,ID_COLLABORAZIONE,RICEVUTA_APPLICATIVA) ");
  662.                 query.append(" VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? )");
  663.             }


  664.             pstmt = connectionDB.prepareStatement(query.toString());
  665.             int index = 1;
  666.             pstmt.setString(index++,id);
  667.             pstmt.setString(index++,Costanti.INBOX);
  668.             pstmt.setTimestamp(index++,oraRicezione);
  669.             pstmt.setInt(index++,1); // stato ricevuta: non attesa
  670.             pstmt.setString(index++,tipoServizioCorrelato);
  671.             pstmt.setString(index++,servizioCorrelato);
  672.             if(versioneServizioCorrelato!=null){
  673.                 pstmt.setInt(index++,versioneServizioCorrelato);
  674.             }
  675.             else{
  676.                 pstmt.setNull(index++, java.sql.Types.INTEGER);
  677.             }
  678.             pstmt.setInt(index++,1); // is richiesta
  679.             pstmt.setString(index++,id); // idasincrono utilizzato per identificare questa instanza di cooperazione asincrona
  680.             pstmt.setString(index++,idCollaborazione); // idCollaborazione
  681.             if(ricevutaApplicativa){
  682.                 pstmt.setInt(index++,1); // ricevuta applicativa abilitata
  683.             }else{
  684.                 pstmt.setInt(index++,0); // ricevuta applicativa non abilitata
  685.             }
  686.             if(exists){
  687.                 pstmt.setString(index++,id);
  688.                 pstmt.setString(index++,Costanti.INBOX);
  689.             }

  690.             //  Add PreparedStatement
  691.             if(exists){
  692.                 state.getPreparedStatement().put("UPDATE save_RichiestaAsincronaSimmetricaRicevuta"+id,pstmt);
  693.             }else{
  694.                 state.getPreparedStatement().put("INSERT save_RichiestaAsincronaSimmetricaRicevuta"+id,pstmt);
  695.             }

  696.            
  697.             if(this.state instanceof StatefulMessage) {
  698.                
  699.                 // salvo busta per profilo
  700.                 this.registraBustaRicevuta(id);
  701.                
  702.             }else{
  703.                
  704.                 StatelessMessage statelessMessage = (StatelessMessage) this.state;
  705.                
  706.                 long scadenza = scadenzaMessaggi;
  707.                 if(scadenza<=0){
  708.                     scadenza = this.protocolManager.getIntervalloScadenzaBuste();
  709.                 }
  710.                
  711.                 // Registro proprio la busta
  712.                 RepositoryBuste repository = new RepositoryBuste(this.state,  this.log, true, this.protocolFactory);
  713.                 String key = "INSERT RegistrazioneBustaForHistory" + Costanti.INBOX + "_" + statelessMessage.getBusta().getID();
  714.                 if(repository.isRegistrataIntoInBox(statelessMessage.getBusta().getID())){
  715.                     repository.aggiornaBustaIntoInBox(statelessMessage.getBusta(),
  716.                             scadenza);
  717.                 }else if(state.getPreparedStatement().containsKey(key)){
  718.                     repository.aggiornaBustaIntoInBox(statelessMessage.getBusta(),
  719.                             scadenza);
  720.                 }else{
  721.                     repository.registraBustaIntoInBox(statelessMessage.getBusta(),
  722.                             scadenza);
  723.                 }
  724.                 this.registraBustaRicevuta(id);
  725.                
  726.                
  727.                 // salvo busta per profilo
  728.                 StringBuilder queryUpdate = new StringBuilder();
  729.                 queryUpdate.append("UPDATE ");
  730.                 queryUpdate.append(Costanti.REPOSITORY);
  731.                 queryUpdate.append(" SET ");
  732.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_ProfiloCollaborazione(true));
  733.                 queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  734.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  735.                 pstmtUpdate.setString(1,id);
  736.                 pstmtUpdate.setString(2,Costanti.INBOX);

  737.                 // Add PreparedStatement
  738.                 state.getPreparedStatement().put("UPDATE saveBustaForProfilo" + Costanti.INBOX + "_" + id,pstmtUpdate);
  739.             }
  740.            
  741.            

  742.         } catch(Exception e) {
  743.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore di registrazione richiesta ricevuta " + id + ": " + e.getMessage();        
  744.             this.log.error(errorMsg,e);
  745.             try{
  746.                 if( rs != null )
  747.                     rs.close();
  748.             } catch(Exception er) {
  749.                 // Eccezione SQL.
  750.             }
  751.             try{
  752.                 if( pstmt != null )
  753.                     pstmt.close();
  754.             } catch(Exception er) {
  755.                 // Eccezione SQL.
  756.             }
  757.             try{
  758.                 if( pstmtUpdate != null )
  759.                     pstmtUpdate.close();
  760.             } catch(Exception er) {
  761.                 // Eccezione SQL.
  762.             }
  763.             throw new ProtocolException(errorMsg,e);
  764.         }
  765.     }

  766.     /**
  767.      * Controlla se e' stato precedentemente registrata una richiesta asincrona simmetrica,
  768.      * ritornando eventuale busta da usare con la risposta applicativa.
  769.      *
  770.      * @param id Identificativo della richiesta.
  771.      * @param idRisposta Identificativo della risposta.
  772.      * @return Dati di integrazione per la consegna della risposta
  773.      *
  774.      */
  775.     public Busta asincronoSimmetrico_getBustaRisposta(String id, String idRisposta, long scadenzaMessaggi) throws ProtocolException{
  776.        
  777.         StateMessage state = (StateMessage)this.state;
  778.         Connection connectionDB = state.getConnectionDB();
  779.         // getBustaRicevuta
  780.         Busta busta = null;
  781.         try{
  782.             RepositoryBuste repository = new RepositoryBuste(state,  this.log, this.protocolFactory);
  783.             // exists: controlla anche il marcatore logico, per vedere che la busta cmq non sia eliminata
  784.             if(repository.exists(id, Costanti.INBOX)){
  785.                 LetturaParametriBusta parametri = new LetturaParametriBusta();
  786.                 parametri.setMittente(true);
  787.                 parametri.setDestinatario(true);
  788.                 parametri.setServizioCorrelato(true);
  789.                 busta = repository.getSomeValuesFromInBox(id, parametri ,true); // Ultimo parametro forza la lettura su database
  790.             }else{
  791.                 throw new Exception("Busta non trovata");
  792.             }
  793.         }catch(Exception e){
  794.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore durante la getBusta dal repository "+id+": "+e.getMessage();      
  795.             this.log.error(errorMsg,e);
  796.             throw new ProtocolException(errorMsg,e);
  797.         }

  798.         // ProfiloDiCollaborazione
  799.         busta.setProfiloDiCollaborazione(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO);

  800.         // check eventuali spedizione-risposta precedentemente effettuate
  801.         PreparedStatement pstmtCheck = null;
  802.         ResultSet rsCheck = null;
  803.         String oldIDRisposta = null;
  804.         String oldTipoRisposta = null;
  805.         try{
  806.             StringBuilder query = new StringBuilder();
  807.             query.append("SELECT ID_MESSAGGIO,TIPO FROM ");
  808.             query.append(Costanti.PROFILO_ASINCRONO);
  809.             query.append(" WHERE BACKUP_ID_RICHIESTA=?");

  810.             pstmtCheck = connectionDB.prepareStatement(query.toString());
  811.             pstmtCheck.setString(1,id);
  812.             rsCheck = pstmtCheck.executeQuery();        
  813.             if(rsCheck == null) {
  814.                 throw new ProtocolException("RS Check Null?");          
  815.             }
  816.             if(rsCheck.next()){
  817.                 oldIDRisposta = rsCheck.getString("ID_MESSAGGIO");
  818.                 oldTipoRisposta = rsCheck.getString("TIPO");
  819.             }      
  820.             rsCheck.close();
  821.             pstmtCheck.close();

  822.         }catch(Exception e){    
  823.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, asincronoSimmetrico_getBustaRisposta "+id+": "+e.getMessage();
  824.             this.log.error(errorMsg,e);
  825.             try{
  826.                 if( rsCheck != null )
  827.                     rsCheck.close();
  828.             } catch(Exception er) {
  829.                 // Eccezione SQL.
  830.             }
  831.             try{
  832.                 if( pstmtCheck != null )
  833.                     pstmtCheck.close();
  834.             } catch(Exception er) {
  835.                 // Eccezione SQL.
  836.             }
  837.             throw new ProtocolException(errorMsg,e);
  838.         }

  839.         // Imposto parametri per la consegna della risposta
  840.         PreparedStatement pstmt = null;
  841.         try{    

  842.             java.sql.Timestamp oraInvioRisposta = DateManager.getTimestamp();

  843.             StringBuilder query = new StringBuilder();
  844.             query.append("UPDATE ");
  845.             query.append(Costanti.PROFILO_ASINCRONO);
  846.             query.append(" SET IS_RICHIESTA=0, RICEVUTA_ASINCRONA=0, ORA_REGISTRAZIONE=?, ID_MESSAGGIO=?, TIPO=?, BACKUP_ID_RICHIESTA=? WHERE  ID_MESSAGGIO = ? AND TIPO=?");

  847.             pstmt = connectionDB.prepareStatement(query.toString());
  848.             pstmt.setTimestamp(1,oraInvioRisposta);
  849.             pstmt.setString(2,idRisposta);
  850.             pstmt.setString(3,Costanti.OUTBOX);
  851.             pstmt.setString(4,id);
  852.             if(oldIDRisposta!=null && oldTipoRisposta!=null){
  853.                 pstmt.setString(5,oldIDRisposta);
  854.                 pstmt.setString(6,oldTipoRisposta);
  855.             }else{
  856.                 pstmt.setString(5,id);
  857.                 pstmt.setString(6,Costanti.INBOX);
  858.             }

  859.             //  Add PreparedStatement
  860.             state.getPreparedStatement().put("UPDATE save_RispostaAsincronaSimmetricaInviata"+id,pstmt);

  861.         } catch(Exception e) {
  862.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore di registrazione risposta inviata "+id+": "+e.getMessage();        
  863.             this.log.error(errorMsg,e);
  864.             try{
  865.                 if( pstmt != null )
  866.                     pstmt.close();
  867.             } catch(Exception er) {
  868.                 // Eccezione SQL.
  869.             }
  870.             throw new ProtocolException(errorMsg,e);
  871.         }

  872.         // Imposto tipo e nome servizio correlato
  873.         if(busta.getTipoServizioCorrelato()==null || busta.getServizioCorrelato()==null){
  874.             PreparedStatement pstmtServizioCorrelato = null;
  875.             ResultSet rsServizioCorrelato = null;
  876.             String tipoSC = null;
  877.             String nomeSC = null;
  878.             Integer versioneSC = null;
  879.             try{
  880.                 StringBuilder query = new StringBuilder();
  881.                 query.append("SELECT TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO FROM ");
  882.                 query.append(Costanti.PROFILO_ASINCRONO);
  883.                 query.append(" WHERE ID_MESSAGGIO = ? AND TIPO=?");

  884.                 pstmtServizioCorrelato = connectionDB.prepareStatement(query.toString());
  885.                 if(oldIDRisposta!=null && oldTipoRisposta!=null){
  886.                     pstmtServizioCorrelato.setString(1,oldIDRisposta);
  887.                     pstmtServizioCorrelato.setString(2,oldTipoRisposta);
  888.                 }else{
  889.                     pstmtServizioCorrelato.setString(1,id);
  890.                     pstmtServizioCorrelato.setString(2,Costanti.INBOX);
  891.                 }
  892.                 rsServizioCorrelato = pstmtServizioCorrelato.executeQuery();        
  893.                 if(rsServizioCorrelato == null) {
  894.                     throw new ProtocolException("RS Check Null?");          
  895.                 }
  896.                 if(rsServizioCorrelato.next()){
  897.                     tipoSC = rsServizioCorrelato.getString("TIPO_SERVIZIO_CORRELATO");
  898.                     nomeSC = rsServizioCorrelato.getString("SERVIZIO_CORRELATO");
  899.                     versioneSC = rsServizioCorrelato.getInt("VERSIONE_SERVIZIO_CORRELATO");
  900.                     if(rsServizioCorrelato.wasNull()){
  901.                         versioneSC = null;
  902.                     }
  903.                 }      
  904.                 rsServizioCorrelato.close();
  905.                 pstmtServizioCorrelato.close();

  906.                 if(tipoSC==null || nomeSC==null || versioneSC==null)
  907.                     throw new Exception("Tipo/Nome/Versione servizio correlato non trovato");

  908.             }catch(Exception e){    
  909.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, asincronoSimmetrico_getBustaRisposta "+id+": "+e.getMessage();
  910.                 this.log.error(errorMsg,e);
  911.                 try{
  912.                     if( rsServizioCorrelato != null )
  913.                         rsServizioCorrelato.close();
  914.                 } catch(Exception er) {
  915.                     // Eccezione SQL.
  916.                 }
  917.                 try{
  918.                     if( pstmtServizioCorrelato != null )
  919.                         pstmtServizioCorrelato.close();
  920.                 } catch(Exception er) {
  921.                     // Eccezione SQL.
  922.                 }
  923.                 throw new ProtocolException(errorMsg,e);
  924.             }
  925.             busta.setTipoServizioCorrelato(tipoSC);
  926.             busta.setServizioCorrelato(nomeSC);
  927.             busta.setVersioneServizioCorrelato(versioneSC);
  928.         }

  929.         if(this.state instanceof StatefulMessage) {
  930.        
  931.             // Registro la busta con il nuovo id
  932.             this.registraBustaInviata(idRisposta);
  933.            
  934.         }else{
  935.        
  936.             PreparedStatement pstmtUpdate = null;
  937.             try{
  938.            
  939.                 StatelessMessage statelessMessage = (StatelessMessage) this.state;
  940.                
  941.                 // Registro proprio la busta
  942.                 RepositoryBuste repository = new RepositoryBuste(this.state,  this.log, true, this.protocolFactory);
  943.                 long scadenza = scadenzaMessaggi;
  944.                 if(scadenza<=0){
  945.                     scadenza = this.protocolManager.getIntervalloScadenzaBuste();
  946.                 }
  947.                 repository.registraBustaIntoOutBox(statelessMessage.getBusta(),scadenza);
  948.                 this.registraBustaInviata(idRisposta);
  949.                
  950.                 // salvo busta per profilo
  951.                 StringBuilder queryUpdate = new StringBuilder();
  952.                 queryUpdate.append("UPDATE ");
  953.                 queryUpdate.append(Costanti.REPOSITORY);
  954.                 queryUpdate.append(" SET ");
  955.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_ProfiloCollaborazione(true));
  956.                 queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  957.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  958.                 pstmtUpdate.setString(1,idRisposta);
  959.                 pstmtUpdate.setString(2,Costanti.OUTBOX);
  960.    
  961.                 // Add PreparedStatement
  962.                 state.getPreparedStatement().put("UPDATE saveBustaForProfilo"+Costanti.OUTBOX+"_"+idRisposta,pstmtUpdate);
  963.            
  964.             } catch(Exception e) {
  965.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore di aggiornamento busta di risposta "+idRisposta+": "+e.getMessage();      
  966.                 this.log.error(errorMsg,e);
  967.                 try{
  968.                     if( pstmtUpdate != null )
  969.                         pstmtUpdate.close();
  970.                 } catch(Exception er) {
  971.                     // Eccezione SQL.
  972.                 }
  973.                 throw new ProtocolException(errorMsg,e);
  974.             }
  975.            
  976.         }

  977.         //  delete vecchia risposta
  978.         if(oldIDRisposta!=null && oldTipoRisposta!=null){
  979.             this.eliminaBusta(oldIDRisposta,oldTipoRisposta,true);
  980.         }

  981.         return busta;
  982.     }

  983.     /**
  984.      * Controlla se e' stato precedentemente registrata una richiesta asincrona simmetrica,
  985.      * ritornando eventuale busta da usare con la ricevuta applicativa.
  986.      *
  987.      * @param id Identificativo della richiesta asincrona.
  988.      * @param rifMsgRicevuta Riferimento Messaggio da applicare alla ricevuta.
  989.      * @param isRichiesta Indicazione se si desidera la busta per una ricevuta ad una richiesta o risposta
  990.      * @return Busta da utilizzare per la ricevuta
  991.      *
  992.      */
  993.     public Busta asincronoSimmetrico_getBustaRicevuta(String id,String rifMsgRicevuta,boolean isRichiesta,TipoOraRegistrazione tipoTempo) throws ProtocolException{
  994.         StateMessage state = (StateMessage)this.state;
  995.         Connection connectionDB = state.getConnectionDB();
  996.         Busta busta = null;
  997.         try{
  998.             RepositoryBuste repository = new RepositoryBuste(state,  this.log, this.protocolFactory);
  999.             LetturaParametriBusta parametri = new LetturaParametriBusta();
  1000.             parametri.setMittente(true);
  1001.             parametri.setDestinatario(true);
  1002.             parametri.setServizio(true);
  1003.             parametri.setServizioCorrelato(true);
  1004.             parametri.setAzione(true);
  1005.             parametri.setCollaborazione(true);
  1006.             parametri.setProfiloTrasmissione(true);
  1007.             parametri.setIndirizziTelematici(this.protocolConfiguration.isSupportoIndirizzoRisposta());

  1008.             if(isRichiesta){
  1009.                 busta = repository.getSomeValuesFromInBox(id, parametri,true); // devo leggere i valori dal database
  1010.             }else{
  1011.                 busta = repository.getSomeValuesFromOutBox(id, parametri,true); // devo leggere i valori dal database

  1012.                 // elimino busta per profilo
  1013.                 this.eliminaBustaInviata(id,true);
  1014.             }

  1015.             // costruzione busta di risposta

  1016.             // ProfiloDiCollaborazione
  1017.             busta.setProfiloDiCollaborazione(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO);

  1018.             // inverto mitt con dest solo se e' una ricevuta alla richiesta
  1019.             if(isRichiesta){
  1020.                 String mitt = busta.getMittente();
  1021.                 String tipoMitt = busta.getTipoMittente();
  1022.                 String portaMitt = busta.getIdentificativoPortaMittente();
  1023.                 String indMitt = busta.getIndirizzoMittente();
  1024.                 busta.setMittente(busta.getDestinatario());
  1025.                 busta.setTipoMittente(busta.getTipoDestinatario());
  1026.                 busta.setIdentificativoPortaMittente(busta.getIdentificativoPortaDestinatario());
  1027.                 busta.setIndirizzoMittente(busta.getIndirizzoDestinatario());
  1028.                 busta.setDestinatario(mitt);
  1029.                 busta.setTipoDestinatario(tipoMitt);
  1030.                 busta.setIdentificativoPortaDestinatario(portaMitt);
  1031.                 busta.setIndirizzoDestinatario(indMitt);
  1032.             }

  1033.             if(isRichiesta == false){

  1034.                 String tipoServizioCorrelato = busta.getTipoServizioCorrelato();
  1035.                 String servizioCorrelato = busta.getServizioCorrelato();
  1036.                 Integer versioneServizioCorrelato = busta.getVersioneServizioCorrelato();

  1037.                 if(tipoServizioCorrelato==null || servizioCorrelato==null || versioneServizioCorrelato==null){
  1038.                     StringBuilder query = new StringBuilder();
  1039.                     query.append("SELECT TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO FROM ");
  1040.                     query.append(Costanti.PROFILO_ASINCRONO);
  1041.                     query.append(" WHERE ID_MESSAGGIO = ? AND TIPO=?");
  1042.                     PreparedStatement pstmtServizioCorrelato = null;
  1043.                     ResultSet rsServizioCorrelato = null;
  1044.                     try {
  1045.                         pstmtServizioCorrelato = connectionDB.prepareStatement(query.toString());
  1046.                         pstmtServizioCorrelato.setString(1,id);
  1047.                         pstmtServizioCorrelato.setString(2,Costanti.OUTBOX);
  1048.                         rsServizioCorrelato = pstmtServizioCorrelato.executeQuery();        
  1049. //                      if(rsServizioCorrelato == null) {
  1050. //                          throw new ProtocolException("RS Check Null?");          
  1051. //                      }
  1052.                         if(rsServizioCorrelato.next()){
  1053.                             tipoServizioCorrelato = rsServizioCorrelato.getString("TIPO_SERVIZIO_CORRELATO");
  1054.                             servizioCorrelato = rsServizioCorrelato.getString("SERVIZIO_CORRELATO");
  1055.                             versioneServizioCorrelato = rsServizioCorrelato.getInt("VERSIONE_SERVIZIO_CORRELATO");
  1056.                             if(rsServizioCorrelato.wasNull()){
  1057.                                 versioneServizioCorrelato = null;
  1058.                             }
  1059.                         }      
  1060.                         if(tipoServizioCorrelato==null || servizioCorrelato==null || versioneServizioCorrelato==null)
  1061.                             throw new Exception("Tipo/Nome/Versione servizio correlato non trovato");

  1062.                     }catch(Exception e){
  1063.                         throw new Exception("Lettura Servizio correlato non riuscita "+e.getMessage(),e );
  1064.                     }
  1065.                     finally {
  1066.                         try {
  1067.                             if(rsServizioCorrelato!=null) {
  1068.                                 rsServizioCorrelato.close();
  1069.                             }
  1070.                         }catch(Throwable e){
  1071.                             // ignore
  1072.                         }
  1073.                         try {
  1074.                             if(pstmtServizioCorrelato!=null) {
  1075.                                 pstmtServizioCorrelato.close();
  1076.                             }
  1077.                         }catch(Throwable e){
  1078.                             // ignore
  1079.                         }
  1080.                     }
  1081.                 }

  1082.                 busta.setTipoServizio(tipoServizioCorrelato);
  1083.                 busta.setServizio(servizioCorrelato);
  1084.             }

  1085.             busta.setRiferimentoMessaggio(rifMsgRicevuta);
  1086.             busta.setOraRegistrazione(DateManager.getDate());
  1087.             busta.setTipoOraRegistrazione(tipoTempo,this.protocolTraduttore.toString(tipoTempo));

  1088.             busta.setTipoServizioCorrelato(null);
  1089.             busta.setServizioCorrelato(null);

  1090.         }catch(Exception e){
  1091.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore durante la asincronoSimmetrico_getBustaRicevuta dal repository "+id+": "+e.getMessage();      
  1092.             this.log.error(errorMsg,e);
  1093.             throw new ProtocolException(errorMsg,e);
  1094.         }
  1095.         return busta;
  1096.     }

  1097.     /**
  1098.      * Validazione della busta, che sia coerente con la precedente richiesta asincrona simmetrica.
  1099.      *
  1100.      * @param bustaDaValidare Busta da controllare
  1101.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  1102.      *
  1103.      */
  1104.     public Eccezione asincronoSimmetrico_validazioneCorrelazione_ricevutaRichiesta(Busta bustaDaValidare, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  1105.         return asincronoSimmetrico_validazioneCorrelazione(bustaDaValidare,true,false,false,protocolFactory);
  1106.     }
  1107.     /**
  1108.      * Validazione della busta, che sia coerente con la precedente richiesta asincrona simmetrica.
  1109.      *
  1110.      * @param bustaDaValidare Busta da controllare
  1111.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  1112.      *
  1113.      */
  1114.     public Eccezione asincronoSimmetrico_validazioneCorrelazione_risposta(Busta bustaDaValidare, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  1115.         return asincronoSimmetrico_validazioneCorrelazione(bustaDaValidare,false,true,false,protocolFactory);
  1116.     }
  1117.     /**
  1118.      * Validazione della busta, che sia coerente con la precedente richiesta asincrona simmetrica.
  1119.      *
  1120.      * @param bustaDaValidare Busta da controllare
  1121.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  1122.      *
  1123.      */
  1124.     public Eccezione asincronoSimmetrico_validazioneCorrelazione_ricevutaRisposta(Busta bustaDaValidare, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  1125.         return asincronoSimmetrico_validazioneCorrelazione(bustaDaValidare,false,false,true,protocolFactory);
  1126.     }
  1127.     /**
  1128.      * Validazione della busta, che sia coerente con la precedente richiesta asincrona simmetrica.
  1129.      *
  1130.      * @param bustaDaValidare Busta da controllare
  1131.      * @param isRicevutaRichiesta Ricevuta della Richiesta
  1132.      * @param isRisposta Risposta
  1133.      * @param isRicevutaRisposta Ricevuta della Risposta
  1134.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  1135.      *
  1136.      */
  1137.     private Eccezione asincronoSimmetrico_validazioneCorrelazione(Busta bustaDaValidare,boolean isRicevutaRichiesta,boolean isRisposta,
  1138.             boolean isRicevutaRisposta, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  1139.         StateMessage state = (StateMessage)this.state;
  1140.         Connection connectionDB = state.getConnectionDB();
  1141.         Busta bustaRichiesta = null;
  1142.         try{
  1143.             RepositoryBuste repository = new RepositoryBuste(state,  this.log, this.protocolFactory);
  1144.             LetturaParametriBusta parametri = new LetturaParametriBusta();
  1145.             parametri.setMittente(true);
  1146.             parametri.setDestinatario(true);
  1147.             parametri.setServizio(true);
  1148.             parametri.setAzione(true);

  1149.             // NOTA:
  1150.             //   una busta asincrona RISPOSTA puo avere riferimentoMessaggio o collaborazione
  1151.             if(isRisposta && bustaDaValidare.getRiferimentoMessaggio()==null)
  1152.                 bustaRichiesta = repository.getSomeValuesFromOutBox(bustaDaValidare.getCollaborazione(), parametri, true); // deve leggere sempre da database
  1153.             else
  1154.                 bustaRichiesta = repository.getSomeValuesFromOutBox(bustaDaValidare.getRiferimentoMessaggio(), parametri, true); // deve leggere sempre da database

  1155.         }catch(Exception e){
  1156.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, Errore durante la validazioneCorrelazione, get dal repository "+bustaDaValidare.getRiferimentoMessaggio()+": "+e.getMessage();        
  1157.             this.log.error(errorMsg,e);
  1158.             throw new ProtocolException(errorMsg,e);
  1159.         }

  1160.         // Validazione Servizio (Tipo e Nome)
  1161.         // Obbligatoria per una risposta, opzionale per una ricevuta
  1162.         if( isRicevutaRichiesta ){
  1163.             if(bustaDaValidare.getServizio()!=null && bustaDaValidare.getTipoServizio()!=null){
  1164.                 if (bustaRichiesta.getTipoServizio().equals(bustaDaValidare.getTipoServizio())==false){
  1165.                     String msgErrore = "Tipo del servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1166.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_SERVIZIO_NON_VALIDO.
  1167.                             getErroreCooperazione(msgErrore),
  1168.                             true,null,protocolFactory);
  1169.                     this.log.error(msgErrore);
  1170.                     return eccValidazione;
  1171.                 }
  1172.                 if (bustaRichiesta.getServizio().equals(bustaDaValidare.getServizio())==false){
  1173.                     String msgErrore = "Servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1174.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.SERVIZIO_NON_VALIDO.
  1175.                             getErroreCooperazione(msgErrore),
  1176.                             true,null,protocolFactory);
  1177.                     this.log.error(msgErrore);
  1178.                     return eccValidazione;
  1179.                 }
  1180.             }
  1181.         }
  1182.         else if(  (isRisposta) || (isRicevutaRisposta && bustaDaValidare.getServizio()!=null && bustaDaValidare.getTipoServizio()!=null) ) {
  1183.             PreparedStatement pstmt = null;
  1184.             ResultSet rs = null;
  1185.             try{
  1186.                 StringBuilder query = new StringBuilder();
  1187.                 query.append("SELECT TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO FROM ");
  1188.                 query.append(Costanti.PROFILO_ASINCRONO);
  1189.                 query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  1190.                 pstmt = connectionDB.prepareStatement(query.toString());

  1191.                 // NOTA:
  1192.                 //   una busta asincrona RISPOSTA puo avere riferimentoMessaggio o collaborazione
  1193.                 if(isRisposta && bustaDaValidare.getRiferimentoMessaggio()==null)
  1194.                     pstmt.setString(1,bustaDaValidare.getCollaborazione());
  1195.                 else
  1196.                     pstmt.setString(1,bustaDaValidare.getRiferimentoMessaggio());

  1197.                 pstmt.setString(2,Costanti.OUTBOX);
  1198.                 rs = pstmt.executeQuery();      
  1199.                 if(rs == null) {
  1200.                     throw new ProtocolException("RS Null?");            
  1201.                 }
  1202.                 String tipoServizioCorrelatoRegistrato = null;
  1203.                 String servizioCorrelatoRegistrato = null;
  1204.                 Integer versioneServizioCorrelatoRegistrato = null;
  1205.                 if(rs.next()){
  1206.                     tipoServizioCorrelatoRegistrato = rs.getString("TIPO_SERVIZIO_CORRELATO");
  1207.                     servizioCorrelatoRegistrato = rs.getString("SERVIZIO_CORRELATO");
  1208.                     versioneServizioCorrelatoRegistrato = rs.getInt("VERSIONE_SERVIZIO_CORRELATO");
  1209.                     if(rs.wasNull()){
  1210.                         versioneServizioCorrelatoRegistrato = null;
  1211.                     }
  1212.                 }

  1213.                 rs.close();
  1214.                 pstmt.close();

  1215.                 if (bustaDaValidare.getTipoServizio().equals(tipoServizioCorrelatoRegistrato) == false){
  1216.                     String msgErrore = "Tipo del servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1217.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_SERVIZIO_NON_VALIDO.
  1218.                             getErroreCooperazione(msgErrore),
  1219.                             true,null,protocolFactory);
  1220.                     this.log.error(msgErrore);
  1221.                     return eccValidazione;
  1222.                 }
  1223.                 if (bustaDaValidare.getServizio().equals(servizioCorrelatoRegistrato) == false){
  1224.                     String msgErrore = "Servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1225.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.SERVIZIO_NON_VALIDO.
  1226.                             getErroreCooperazione(msgErrore),
  1227.                             true,null,protocolFactory);
  1228.                     this.log.error(msgErrore);
  1229.                     return eccValidazione;
  1230.                 }
  1231.                 if(versioneServizioCorrelatoRegistrato==null){
  1232.                     versioneServizioCorrelatoRegistrato = -1; // valore apposta errato
  1233.                 }
  1234.                 if (bustaDaValidare.getVersioneServizio().intValue() != versioneServizioCorrelatoRegistrato.intValue()){
  1235.                     String msgErrore = "Versione del servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1236.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.VERSIONE_SERVIZIO_NON_VALIDO.
  1237.                             getErroreCooperazione(msgErrore),
  1238.                             true,null,protocolFactory);
  1239.                     this.log.error(msgErrore);
  1240.                     return eccValidazione;
  1241.                 }

  1242.             }catch(Exception e){    
  1243.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, validazioneCorrelazioneRichiesta RifMsg("+bustaDaValidare.getRiferimentoMessaggio()+") Collab("+bustaDaValidare.getCollaborazione()+"): "+e.getMessage();
  1244.                 this.log.error(errorMsg);
  1245.                 try{
  1246.                     if( rs != null )
  1247.                         rs.close();
  1248.                 } catch(Exception er) {
  1249.                     // Eccezione SQL.
  1250.                 }
  1251.                 try{
  1252.                     if( pstmt != null )
  1253.                         pstmt.close();
  1254.                 } catch(Exception er) {
  1255.                     // Eccezione SQL.
  1256.                 }
  1257.                 throw new ProtocolException(errorMsg);
  1258.             }
  1259.         }

  1260.         // Validazione altri parametri busta
  1261.         // L'azione di una ricevuta deve essere la stessa di quella della richiesta/risposta
  1262.         if(bustaDaValidare.getAzione()!=null && isRisposta==false){
  1263.             if (bustaDaValidare.getAzione().equals(bustaRichiesta.getAzione()) == false){
  1264.                 String msgErrore = "Azione diverso da quello attesa nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1265.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.AZIONE_NON_VALIDA.
  1266.                         getErroreCooperazione(msgErrore),
  1267.                         true,null,protocolFactory);
  1268.                 this.log.error(msgErrore);
  1269.                 return eccValidazione;
  1270.             }
  1271.         }
  1272.         if (bustaRichiesta.getTipoDestinatario().equals(bustaDaValidare.getTipoMittente()) == false){
  1273.             String msgErrore = "Tipo del mittente diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1274.             Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_MITTENTE_NON_VALIDO.
  1275.                     getErroreCooperazione(msgErrore),
  1276.                     true,null,protocolFactory);
  1277.             this.log.error(msgErrore);
  1278.             return eccValidazione;
  1279.         }
  1280.         if (bustaRichiesta.getDestinatario().equals(bustaDaValidare.getMittente()) == false){
  1281.             String msgErrore = "Mittente diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1282.             Eccezione eccValidazione = new Eccezione(ErroriCooperazione.MITTENTE_NON_VALIDO.
  1283.                     getErroreCooperazione(msgErrore),
  1284.                     true,null,protocolFactory);
  1285.             this.log.error(msgErrore);
  1286.             return eccValidazione;
  1287.         }
  1288.         if (bustaRichiesta.getTipoMittente().equals(bustaDaValidare.getTipoDestinatario()) == false){
  1289.             String msgErrore = "Tipo del destinatario diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1290.             Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_DESTINATARIO_NON_VALIDO.
  1291.                     getErroreCooperazione(msgErrore),
  1292.                     true,null,protocolFactory);
  1293.             this.log.error(msgErrore);
  1294.             return eccValidazione;
  1295.         }
  1296.         if (bustaRichiesta.getMittente().equals(bustaDaValidare.getDestinatario()) == false){
  1297.             String msgErrore = "Destinatario diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Simmetrico";
  1298.             Eccezione eccValidazione = new Eccezione(ErroriCooperazione.DESTINATARIO_NON_VALIDO.
  1299.                     getErroreCooperazione(msgErrore),
  1300.                     true,null,protocolFactory);
  1301.             this.log.error(msgErrore);
  1302.             return eccValidazione;
  1303.         }

  1304.         return null;
  1305.     }

  1306.     /**
  1307.      * Validazione del riferimentoMessaggio di una busta asincrona simmetrica.
  1308.      *
  1309.      * @param riferimentoMessaggio Identificativo.
  1310.      * @return true se esiste una entry nella tabella apposita.
  1311.      *
  1312.      */
  1313.     public boolean asincronoSimmetrico_validazioneRiferimentoMessaggio(String riferimentoMessaggio) throws ProtocolException{
  1314.         StateMessage state = (StateMessage)this.state;
  1315.         Connection connectionDB = state.getConnectionDB();
  1316.         PreparedStatement pstmt = null;
  1317.         ResultSet rs = null;
  1318.         try{
  1319.             StringBuilder query = new StringBuilder();
  1320.             query.append("SELECT ID_MESSAGGIO FROM ");
  1321.             query.append(Costanti.PROFILO_ASINCRONO);
  1322.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  1323.             pstmt = connectionDB.prepareStatement(query.toString());
  1324.             pstmt.setString(1,riferimentoMessaggio);
  1325.             pstmt.setString(2,Costanti.OUTBOX);
  1326.             rs = pstmt.executeQuery();      
  1327.             if(rs == null) {
  1328.                 throw new ProtocolException("RS Null?");            
  1329.             }
  1330.             boolean value = rs.next();

  1331.             rs.close();
  1332.             pstmt.close();

  1333.             RepositoryBuste repositoryBuste = new RepositoryBuste(state,  this.log, this.protocolFactory);
  1334.             return value && repositoryBuste.isRegistrataIntoOutBox(riferimentoMessaggio);

  1335.         }catch(Exception e){    
  1336.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, validazioneRiferimentoMessaggio "+riferimentoMessaggio+": "+e.getMessage();
  1337.             this.log.error(errorMsg);
  1338.             try{
  1339.                 if( rs != null )
  1340.                     rs.close();
  1341.             } catch(Exception er) {
  1342.                 // Eccezione SQL.
  1343.             }
  1344.             try{
  1345.                 if( pstmt != null )
  1346.                     pstmt.close();
  1347.             } catch(Exception er) {
  1348.                 // Eccezione SQL.
  1349.             }
  1350.             throw new ProtocolException(errorMsg,e);
  1351.         }
  1352.     }

  1353.     /**
  1354.      * Validazione della collaborazione di una busta asincrona.
  1355.      *
  1356.      * @param riferimentoMessaggio Identificativo.
  1357.      * @param idCollaborazione Collaborazione
  1358.      * @return true se la collaborazione e' valida
  1359.      *
  1360.      */
  1361.     public boolean asincronoSimmetrico_validazioneCollaborazione_risposta(String riferimentoMessaggio,String idCollaborazione) throws ProtocolException{
  1362.         return asincronoSimmetrico_validazioneCollaborazione(riferimentoMessaggio,idCollaborazione,true);
  1363.     }

  1364.     /**
  1365.      * Validazione della collaborazione di una busta asincrona.
  1366.      *
  1367.      * @param riferimentoMessaggio Identificativo.
  1368.      * @param idCollaborazione Collaborazione
  1369.      * @return true se la collaborazione e' valida
  1370.      *
  1371.      */
  1372.     public boolean asincronoSimmetrico_validazioneCollaborazione_ricevuta(String riferimentoMessaggio,String idCollaborazione) throws ProtocolException{
  1373.         return asincronoSimmetrico_validazioneCollaborazione(riferimentoMessaggio,idCollaborazione,false);
  1374.     }

  1375.     /**
  1376.      * Validazione della collaborazione di una busta asincrona.
  1377.      *
  1378.      * @param riferimentoMessaggio Identificativo.
  1379.      * @param idCollaborazione Collaborazione
  1380.      * @return true se la collaborazione e' valida
  1381.      *
  1382.      */
  1383.     private boolean asincronoSimmetrico_validazioneCollaborazione(String riferimentoMessaggio,String idCollaborazione,boolean isRisposta) throws ProtocolException{
  1384.         StateMessage state = (StateMessage)this.state;
  1385.         Connection connectionDB = state.getConnectionDB();
  1386.         PreparedStatement pstmt = null;
  1387.         ResultSet rs = null;
  1388.         try{
  1389.             StringBuilder query = new StringBuilder();
  1390.             query.append("SELECT ID_COLLABORAZIONE FROM ");
  1391.             query.append(Costanti.PROFILO_ASINCRONO);
  1392.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  1393.             pstmt = connectionDB.prepareStatement(query.toString());

  1394.             // NOTA:
  1395.             //   una busta asincrona RISPOSTA puo avere riferimentoMessaggio o collaborazione
  1396.             if(isRisposta && riferimentoMessaggio==null)
  1397.                 pstmt.setString(1,idCollaborazione);
  1398.             else
  1399.                 pstmt.setString(1,riferimentoMessaggio);
  1400.             pstmt.setString(2,Costanti.OUTBOX);
  1401.             rs = pstmt.executeQuery();      
  1402.             if(rs == null) {
  1403.                 throw new ProtocolException("RS Null?");            
  1404.             }
  1405.             String value = null;
  1406.             if(rs.next()){
  1407.                 value = rs.getString("ID_COLLABORAZIONE");
  1408.             }

  1409.             rs.close();
  1410.             pstmt.close();

  1411.             return idCollaborazione.equals(value);

  1412.         }catch(Exception e){    
  1413.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOSIMMETRICO, validazioneCollaborazione "+riferimentoMessaggio+": "+e.getMessage();
  1414.             this.log.error(errorMsg,e);
  1415.             try{
  1416.                 if( rs != null )
  1417.                     rs.close();
  1418.             } catch(Exception er) {
  1419.                 // Eccezione SQL.
  1420.             }
  1421.             try{
  1422.                 if( pstmt != null )
  1423.                     pstmt.close();
  1424.             } catch(Exception er) {
  1425.                 // Eccezione SQL.
  1426.             }
  1427.             throw new ProtocolException(errorMsg,e);
  1428.         }
  1429.     }














  1430.     /* ********  PROFILO ASINCRONO ASIMMETRICO ******** */

  1431.     /**
  1432.      * Registrazione di una richiesta inviata.
  1433.      * Viene mantenuto nella tabella asincrona una entry con ID_MESSAGGIO, OUTBOX, dataInvio(serve per la respedizione)
  1434.      *
  1435.      * @param id Identificativo della richiesta
  1436.      * @param ricevutaApplicativa Indicazione sull'abilitazione di una ricevuta applicativa
  1437.      */
  1438.     public void asincronoAsimmetrico_registraRichiestaInviata(String id,String idCollaborazione,
  1439.             boolean ricevutaApplicativa,long scadenzaMessaggi)throws ProtocolException{
  1440.        
  1441.         StateMessage state = (StateMessage)this.state;
  1442.         Connection connectionDB = state.getConnectionDB();
  1443.         PreparedStatement pstmt = null;
  1444.         PreparedStatement pstmtUpdate = null;
  1445.         try{    

  1446.             java.sql.Timestamp oraInvio = DateManager.getTimestamp();

  1447.             StringBuilder query = new StringBuilder();
  1448.             query.append("INSERT INTO  ");
  1449.             query.append(Costanti.PROFILO_ASINCRONO);
  1450.             query.append(" (ID_MESSAGGIO,TIPO,ORA_REGISTRAZIONE,RICEVUTA_ASINCRONA,TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO");
  1451.             query.append(",IS_RICHIESTA,ID_ASINCRONO,ID_COLLABORAZIONE,RICEVUTA_APPLICATIVA) ");
  1452.             query.append(" VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?, ?)");

  1453.             pstmt = connectionDB.prepareStatement(query.toString());
  1454.             int index = 1;
  1455.             pstmt.setString(index++,id);
  1456.             pstmt.setString(index++,Costanti.OUTBOX);
  1457.             pstmt.setTimestamp(index++,oraInvio);
  1458.             pstmt.setInt(index++,0); // stato ricevuta: attesa
  1459.             pstmt.setString(index++,null); // servizioCorrelato non conosciuto a priori
  1460.             pstmt.setString(index++,null); // servizioCorrelato non conosciuto a priori
  1461.             pstmt.setNull(index++, java.sql.Types.INTEGER); // servizioCorrelato non conosciuto a priori
  1462.             pstmt.setInt(index++,1); // is richiesta
  1463.             pstmt.setString(index++,id); // idasincrono utilizzato per identificare questa instanza di cooperazione asincrona
  1464.             pstmt.setString(index++,idCollaborazione); // idcollaborazione
  1465.             if(ricevutaApplicativa){
  1466.                 pstmt.setInt(index++,1); // ricevuta applicativa abilitata
  1467.             }else{
  1468.                 pstmt.setInt(index++,0); // ricevuta applicativa non abilitata
  1469.             }

  1470.             //  Add PreparedStatement
  1471.             state.getPreparedStatement().put("INSERT save_RichiestaAsincronaAsimmetricaInviata"+id,pstmt);

  1472.            
  1473.             if(this.state instanceof StatefulMessage) {
  1474.                
  1475.                 // salvo busta per profilo
  1476.                 this.registraBustaInviata(id);
  1477.                
  1478.             }else{
  1479.                
  1480.                 StatelessMessage statelessMessage = (StatelessMessage) this.state;
  1481.                
  1482.                 // Registro proprio la busta
  1483.                 RepositoryBuste repository = new RepositoryBuste(this.state,  this.log, true, this.protocolFactory);
  1484.                 long scadenza = scadenzaMessaggi;
  1485.                 if(scadenza<=0){
  1486.                     scadenza = this.protocolManager.getIntervalloScadenzaBuste();
  1487.                 }
  1488.                 repository.registraBustaIntoOutBox(statelessMessage.getBusta(),scadenza);
  1489.                 this.registraBustaInviata(id);
  1490.                
  1491.                 // salvo busta per profilo
  1492.                 StringBuilder queryUpdate = new StringBuilder();
  1493.                 queryUpdate.append("UPDATE ");
  1494.                 queryUpdate.append(Costanti.REPOSITORY);
  1495.                 queryUpdate.append(" SET ");
  1496.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_ProfiloCollaborazione(true));
  1497.                 queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  1498.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  1499.                 pstmtUpdate.setString(1,id);
  1500.                 pstmtUpdate.setString(2,Costanti.OUTBOX);

  1501.                 // Add PreparedStatement
  1502.                 state.getPreparedStatement().put("UPDATE saveBustaForProfilo"+Costanti.OUTBOX+"_"+id,pstmtUpdate);
  1503.             }  

  1504.         } catch(Exception e) {
  1505.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore di registrazione richiesta inviata "+id+": "+e.getMessage();      
  1506.             this.log.error(errorMsg,e);
  1507.             try{
  1508.                 if( pstmt != null )
  1509.                     pstmt.close();
  1510.             } catch(Exception er) {
  1511.                 // Eccezione SQL.
  1512.             }
  1513.             try{
  1514.                 if( pstmtUpdate != null )
  1515.                     pstmtUpdate.close();
  1516.             } catch(Exception er) {
  1517.                 // Eccezione SQL.
  1518.             }
  1519.             throw new ProtocolException(errorMsg,e);
  1520.         }
  1521.     }

  1522.     /**
  1523.      * Controlla se e' stato precedentemente registrata una richiesta asincrona asimmetrica,
  1524.      * ritornando eventuali dati del servizio di richiesta per la consegna della risposta.
  1525.      *
  1526.      * @param riferimentoMessaggio RiferimentoMessaggio
  1527.      * @return Dati di integrazione per la consegna della risposta
  1528.      *
  1529.      */
  1530.     public IDServizio asincronoAsimmetrico_getDatiConsegnaRisposta(String riferimentoMessaggio) throws ProtocolException{
  1531.         StateMessage state = (StateMessage)this.state;
  1532.         Connection connectionDB = state.getConnectionDB();


  1533.         //       Imposto ricevuta applicativa abilitata: pooling
  1534.         PreparedStatement pstmtPooling = null;
  1535.         try{    

  1536.             StringBuilder query = new StringBuilder();
  1537.             query.append("UPDATE ");
  1538.             query.append(Costanti.PROFILO_ASINCRONO);
  1539.             query.append(" SET RICEVUTA_APPLICATIVA=1 WHERE  ID_MESSAGGIO = ? AND TIPO=?");

  1540.             pstmtPooling = connectionDB.prepareStatement(query.toString());
  1541.             pstmtPooling.setString(1,riferimentoMessaggio);
  1542.             pstmtPooling.setString(2,Costanti.INBOX);

  1543.             //  Add PreparedStatement
  1544.             state.getPreparedStatement().put("UPDATE asincronoAsimmetrico_getDatiConsegnaRisposta "+riferimentoMessaggio,pstmtPooling);

  1545.         } catch(Exception e) {
  1546.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore asincronoAsimmetrico_getDatiConsegnaRisposta, update RICEVUTA_APPLICATIVA "+riferimentoMessaggio+": "+e.getMessage();    
  1547.             this.log.error(errorMsg,e);
  1548.             try{
  1549.                 if( pstmtPooling != null )
  1550.                     pstmtPooling.close();
  1551.             } catch(Exception er) {
  1552.                 // Eccezione SQL.
  1553.             }
  1554.             throw new ProtocolException(errorMsg,e);
  1555.         }

  1556.         try{    
  1557.             // I dati asincroni saranno eliminati quando scadra' la busta asincrona
  1558.             History history = new History(state,this.log);
  1559.             history.registraBustaRicevuta(riferimentoMessaggio);

  1560.             // Prendo i dati di integrazione
  1561.             RepositoryBuste repositoryBuste = new RepositoryBuste(state,  this.log, this.protocolFactory);
  1562.             LetturaParametriBusta parametri = new LetturaParametriBusta();
  1563.             parametri.setDestinatario(true);
  1564.             parametri.setServizio(true);
  1565.             parametri.setAzione(true);
  1566.             Busta busta = repositoryBuste.getSomeValuesFromInBox(riferimentoMessaggio, parametri, true); // leggo dati da database
  1567.             if(busta==null)
  1568.                 throw new Exception("Dati non trovati");
  1569.             else{
  1570.                 IDServizio id = IDServizioFactory.getInstance().getIDServizioFromValues(busta.getTipoServizio(), busta.getServizio(),
  1571.                         busta.getTipoDestinatario(), busta.getDestinatario(),
  1572.                         busta.getVersioneServizio());
  1573.                 id.setAzione(busta.getAzione());
  1574.                 return id;
  1575.             }

  1576.         } catch(Exception e) {
  1577.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore durante la asincronoAsimmetrico_getDatiConsegnaRisposta "+riferimentoMessaggio+": "+e.getMessage();      
  1578.             this.log.error(errorMsg,e);
  1579.             throw new ProtocolException(errorMsg,e);
  1580.         }

  1581.     }

  1582.     /**
  1583.      * Controlla se e' stato precedentemente registrata una richiesta asincrona asimmetrica,
  1584.      * ritornando eventuali dati dell'integrazione per la consegna della ricevuta.
  1585.      *
  1586.      * @return Dati di integrazione per la consegna della risposta
  1587.      *
  1588.      */
  1589.     public Integrazione asincronoAsimmetrico_getDatiConsegnaRicevuta(String riferimentoMessaggio) throws ProtocolException{
  1590.         if(this.state instanceof StatefulMessage) {
  1591.             StatefulMessage stateful = (StatefulMessage)this.state;
  1592.             try{    
  1593.                 // Prendo i dati di integrazione
  1594.                 RepositoryBuste repositoryBuste = new RepositoryBuste(stateful, this.log, this.protocolFactory);
  1595.                 Integrazione integrazione = repositoryBuste.getInfoIntegrazioneFromOutBox(riferimentoMessaggio);
  1596.                 if(integrazione==null)
  1597.                     throw new Exception("Dati di integrazione non trovati");
  1598.                 else
  1599.                     return integrazione;

  1600.             } catch(Exception e) {
  1601.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore durante la asincronoAsimmetrico_getDatiConsegnaRicevuta "+riferimentoMessaggio+": "+e.getMessage();      
  1602.                 this.log.error(errorMsg,e);
  1603.                 throw new ProtocolException(errorMsg,e);
  1604.             }
  1605.         }else{
  1606.             throw new ProtocolException("Metodo invocato con IState non valido");
  1607.         }
  1608.     }

  1609.     /**
  1610.      * Registrazione di una richiesta ricevuta.
  1611.      * Viene mantenuto nella tabella asincrona una entry con ID_MESSAGGIO, INBOX
  1612.      * e ServizioCorrelato inserito nella richiesta.
  1613.      *
  1614.      * @param id Identificativo della richiesta
  1615.      * @param tipoServizioCorrelato Tipo del Servizio Correlato
  1616.      * @param servizioCorrelato Servizio Correlato
  1617.      * @param ricevutaApplicativa Indicazione sull'abilitazione di una ricevuta applicativa
  1618.      */
  1619.     public void asincronoAsimmetrico_registraRichiestaRicevuta(String id,String idCollaborazione,
  1620.             String tipoServizioCorrelato,String servizioCorrelato, Integer versioneServizioCorrelato,
  1621.             boolean ricevutaApplicativa,long scadenzaMessaggi)throws ProtocolException{
  1622.         StateMessage state = (StateMessage)this.state;
  1623.         Connection connectionDB = state.getConnectionDB();
  1624.         PreparedStatement pstmt = null;
  1625.         ResultSet rs = null;
  1626.         PreparedStatement pstmtUpdate = null;
  1627.         try{    

  1628.             java.sql.Timestamp oraRicezione = DateManager.getTimestamp();

  1629.             StringBuilder querySearch = new StringBuilder();
  1630.             querySearch.append("SELECT ID_MESSAGGIO FROM ");
  1631.             querySearch.append(Costanti.PROFILO_ASINCRONO);
  1632.             querySearch.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  1633.             pstmt = connectionDB.prepareStatement(querySearch.toString());
  1634.             pstmt.setString(1,id);
  1635.             pstmt.setString(2,Costanti.INBOX);
  1636.             rs = pstmt.executeQuery();
  1637.             boolean exists = rs.next();
  1638.             rs.close();
  1639.             pstmt.close();


  1640.             StringBuilder query = new StringBuilder();
  1641.             if(exists){
  1642.                 query.append("UPDATE ");
  1643.                 query.append(Costanti.PROFILO_ASINCRONO);
  1644.                 query.append(" SET ID_MESSAGGIO=?,TIPO=?,ORA_REGISTRAZIONE=?,RICEVUTA_ASINCRONA=?,TIPO_SERVIZIO_CORRELATO=?,SERVIZIO_CORRELATO=?,VERSIONE_SERVIZIO_CORRELATO=?," +
  1645.                 "IS_RICHIESTA=?,ID_ASINCRONO=?,ID_COLLABORAZIONE=?,RICEVUTA_APPLICATIVA=? WHERE ID_MESSAGGIO=? AND TIPO=?");
  1646.             }else{
  1647.                 query.append("INSERT INTO  ");
  1648.                 query.append(Costanti.PROFILO_ASINCRONO);
  1649.                 query.append(" (ID_MESSAGGIO,TIPO,ORA_REGISTRAZIONE,RICEVUTA_ASINCRONA,TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO");
  1650.                 query.append(",IS_RICHIESTA,ID_ASINCRONO,ID_COLLABORAZIONE,RICEVUTA_APPLICATIVA) ");
  1651.                 query.append(" VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)");
  1652.             }


  1653.             pstmt = connectionDB.prepareStatement(query.toString());
  1654.             int index = 1;
  1655.             pstmt.setString(index++,id);
  1656.             pstmt.setString(index++,Costanti.INBOX);
  1657.             pstmt.setTimestamp(index++,oraRicezione);
  1658.             pstmt.setInt(index++,1); // stato ricevuta: non attesa
  1659.             pstmt.setString(index++,tipoServizioCorrelato);
  1660.             pstmt.setString(index++,servizioCorrelato);
  1661.             if(versioneServizioCorrelato!=null){
  1662.                 pstmt.setInt(index++,versioneServizioCorrelato);
  1663.             }
  1664.             else{
  1665.                 pstmt.setNull(index++, java.sql.Types.INTEGER);
  1666.             }
  1667.             pstmt.setInt(index++,0); // passo nella fase di ricezione richiesta-stato
  1668.             pstmt.setString(index++,id); // idasincrono utilizzato per identificare questa instanza di cooperazione asincrona
  1669.             pstmt.setString(index++,idCollaborazione); // idCollaborazione
  1670.             if(ricevutaApplicativa){
  1671.                 pstmt.setInt(index++,1); // ricevuta applicativa abilitata
  1672.             }else{
  1673.                 pstmt.setInt(index++,0); // ricevuta applicativa non abilitata
  1674.             }
  1675.             if(exists){
  1676.                 pstmt.setString(index++,id);
  1677.                 pstmt.setString(index++,Costanti.INBOX);
  1678.             }

  1679.             //  Add PreparedStatement
  1680.             if(exists){
  1681.                 state.getPreparedStatement().put("UPDATE save_RichiestaAsincronaAsimmetricaRicevuta"+id,pstmt);
  1682.             }else{
  1683.                 state.getPreparedStatement().put("INSERT save_RichiestaAsincronaAsimmetricaRicevuta"+id,pstmt);
  1684.             }

  1685.             if(this.state instanceof StatefulMessage) {
  1686.                
  1687.                 // salvo busta per profilo
  1688.                 this.registraBustaRicevuta(id);
  1689.                
  1690.             }else{
  1691.                
  1692.                 StatelessMessage statelessMessage = (StatelessMessage) this.state;
  1693.                
  1694.                 long scadenza = scadenzaMessaggi;
  1695.                 if(scadenza<=0){
  1696.                     scadenza = this.protocolManager.getIntervalloScadenzaBuste();
  1697.                 }
  1698.                
  1699.                 // Registro proprio la busta
  1700.                 RepositoryBuste repository = new RepositoryBuste(this.state,  this.log, true,this.protocolFactory);
  1701.                 String key = "INSERT RegistrazioneBustaForHistory"+Costanti.INBOX+"_"+statelessMessage.getBusta().getID();
  1702.                 if(repository.isRegistrataIntoInBox(statelessMessage.getBusta().getID())){
  1703.                     repository.aggiornaBustaIntoInBox(statelessMessage.getBusta(),scadenza);
  1704.                 }
  1705.                 else if(state.getPreparedStatement().containsKey(key)){
  1706.                     repository.aggiornaBustaIntoInBox(statelessMessage.getBusta(),scadenza);
  1707.                 }else{
  1708.                     repository.registraBustaIntoInBox(statelessMessage.getBusta(),scadenza);
  1709.                 }
  1710.                 this.registraBustaInviata(id);
  1711.                
  1712.                 // salvo busta per profilo
  1713.                 StringBuilder queryUpdate = new StringBuilder();
  1714.                 queryUpdate.append("UPDATE ");
  1715.                 queryUpdate.append(Costanti.REPOSITORY);
  1716.                 queryUpdate.append(" SET ");
  1717.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_ProfiloCollaborazione(true));
  1718.                 queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  1719.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  1720.                 pstmtUpdate.setString(1,id);
  1721.                 pstmtUpdate.setString(2,Costanti.INBOX);

  1722.                 // Add PreparedStatement
  1723.                 state.getPreparedStatement().put("UPDATE saveBustaForProfilo"+Costanti.INBOX+"_"+id,pstmtUpdate);
  1724.             }

  1725.         } catch(Exception e) {
  1726.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore di registrazione richiesta ricevuta "+id+": "+e.getMessage();    
  1727.             this.log.error(errorMsg,e);
  1728.             try{
  1729.                 if( rs != null )
  1730.                     rs.close();
  1731.             } catch(Exception er) {
  1732.                 // Eccezione SQL.
  1733.             }
  1734.             try{
  1735.                 if( pstmt != null )
  1736.                     pstmt.close();
  1737.             } catch(Exception er) {
  1738.                 // Eccezione SQL.
  1739.             }
  1740.             try{
  1741.                 if( pstmtUpdate != null )
  1742.                     pstmtUpdate.close();
  1743.             } catch(Exception er) {
  1744.                 // Eccezione SQL.
  1745.             }
  1746.             throw new ProtocolException(errorMsg,e);
  1747.         }
  1748.     }

  1749.     /**
  1750.      * Controlla se e' stato precedentemente registrata una richiesta asincrona asimmetrica,
  1751.      * ritornando eventuale busta da usare con la risposta applicativa.
  1752.      *
  1753.      * @param id Identificativo della richiesta.
  1754.      * @param idRisposta Identificativo della risposta.
  1755.      * @return Dati di integrazione per la consegna della risposta
  1756.      *
  1757.      */
  1758.     public Busta asincronoAsimmetrico_getBustaRisposta(String id,String idRisposta,long scadenzaMessaggi) throws ProtocolException{
  1759.         StateMessage state = (StateMessage)this.state;
  1760.         Connection connectionDB = state.getConnectionDB();
  1761.         // getBustaRicevuta
  1762.         Busta busta = null;
  1763.         try{
  1764.             RepositoryBuste repository = new RepositoryBuste(state,  this.log, this.protocolFactory);
  1765.             LetturaParametriBusta parametri = new LetturaParametriBusta();
  1766.             parametri.setMittente(true);
  1767.             parametri.setDestinatario(true);
  1768.             parametri.setServizioCorrelato(true);
  1769.             busta = repository.getSomeValuesFromOutBox(id, parametri, true); // Ultimo parametro forza la lettura su database

  1770.         }catch(Exception e){
  1771.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore durante la getBusta dal repository "+id+": "+e.getMessage();      
  1772.             this.log.error(errorMsg,e);
  1773.             throw new ProtocolException(errorMsg,e);
  1774.         }

  1775.         // ProfiloDiCollaborazione
  1776.         busta.setProfiloDiCollaborazione(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_ASIMMETRICO);

  1777.         // check eventuali spedizione-risposta precedentemente effettuate
  1778.         PreparedStatement pstmtCheck = null;
  1779.         ResultSet rsCheck = null;
  1780.         String oldIDRisposta = null;
  1781.         String oldTipoRisposta = null;
  1782.         try{
  1783.             StringBuilder query = new StringBuilder();
  1784.             query.append("SELECT ID_MESSAGGIO,TIPO FROM ");
  1785.             query.append(Costanti.PROFILO_ASINCRONO);
  1786.             query.append(" WHERE BACKUP_ID_RICHIESTA=?");

  1787.             pstmtCheck = connectionDB.prepareStatement(query.toString());
  1788.             pstmtCheck.setString(1,id);
  1789.             rsCheck = pstmtCheck.executeQuery();        
  1790.             if(rsCheck == null) {
  1791.                 throw new ProtocolException("RS Check Null?");          
  1792.             }
  1793.             if(rsCheck.next()){
  1794.                 oldIDRisposta = rsCheck.getString("ID_MESSAGGIO");
  1795.                 oldTipoRisposta = rsCheck.getString("TIPO");
  1796.             }      
  1797.             rsCheck.close();
  1798.             pstmtCheck.close();

  1799.         }catch(Exception e){    
  1800.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, asincronoAsimmetrico_getBustaRisposta "+id+": "+e.getMessage();
  1801.             this.log.error(errorMsg,e);
  1802.             try{
  1803.                 if( rsCheck != null )
  1804.                     rsCheck.close();
  1805.             } catch(Exception er) {
  1806.                 // Eccezione SQL.
  1807.             }
  1808.             try{
  1809.                 if( pstmtCheck != null )
  1810.                     pstmtCheck.close();
  1811.             } catch(Exception er) {
  1812.                 // Eccezione SQL.
  1813.             }
  1814.             throw new ProtocolException(errorMsg,e);
  1815.         }

  1816.         //       leggo servizio correlato
  1817.         String tipoServizioCorrelato = null;
  1818.         String servizioCorrelato = null;
  1819.         Integer versioneServizioCorrelato = null;
  1820.         PreparedStatement pstmtRead = null;
  1821.         ResultSet rsRead = null;
  1822.         try{
  1823.             StringBuilder query = new StringBuilder();
  1824.             query.append("SELECT TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO FROM ");
  1825.             query.append(Costanti.PROFILO_ASINCRONO);
  1826.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  1827.             pstmtRead = connectionDB.prepareStatement(query.toString());
  1828.             if(oldIDRisposta!=null && oldTipoRisposta!=null){
  1829.                 pstmtRead.setString(1,oldIDRisposta);
  1830.                 pstmtRead.setString(2,oldTipoRisposta);
  1831.             }else{
  1832.                 pstmtRead.setString(1,id);
  1833.                 pstmtRead.setString(2,Costanti.OUTBOX);
  1834.             }
  1835.             rsRead = pstmtRead.executeQuery();      
  1836.             if(rsRead == null) {
  1837.                 throw new ProtocolException("RS Read Null?");          
  1838.             }
  1839.             if(rsRead.next()){
  1840.                 tipoServizioCorrelato = rsRead.getString("TIPO_SERVIZIO_CORRELATO");
  1841.                 servizioCorrelato = rsRead.getString("SERVIZIO_CORRELATO");
  1842.                 versioneServizioCorrelato = rsRead.getInt("VERSIONE_SERVIZIO_CORRELATO");
  1843.                 if(rsRead.wasNull()){
  1844.                     versioneServizioCorrelato = null;
  1845.                 }
  1846.             }      
  1847.             rsRead.close();
  1848.             pstmtRead.close();

  1849.         }catch(Exception e){    
  1850.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, asincronoAsimmetrico_getBustaRisposta, raccolta servizio correlato, "+id+": "+e.getMessage();
  1851.             this.log.error(errorMsg,e);
  1852.             try{
  1853.                 if( rsRead != null )
  1854.                     rsRead.close();
  1855.             } catch(Exception er) {
  1856.                 // Eccezione SQL.
  1857.             }
  1858.             try{
  1859.                 if( pstmtRead != null )
  1860.                     pstmtRead.close();
  1861.             } catch(Exception er) {
  1862.                 // Eccezione SQL.
  1863.             }
  1864.             throw new ProtocolException(errorMsg,e);
  1865.         }
  1866.         busta.setTipoServizioCorrelato(tipoServizioCorrelato);
  1867.         busta.setServizioCorrelato(servizioCorrelato);
  1868.         busta.setVersioneServizioCorrelato(versioneServizioCorrelato);

  1869.         // Imposto parametri per la consegna della risposta
  1870.         PreparedStatement pstmt = null;
  1871.         try{    

  1872.             java.sql.Timestamp oraInvioRisposta = DateManager.getTimestamp();

  1873.             StringBuilder query = new StringBuilder();
  1874.             query.append("UPDATE ");
  1875.             query.append(Costanti.PROFILO_ASINCRONO);
  1876.             query.append(" SET IS_RICHIESTA=0, RICEVUTA_ASINCRONA=0, ORA_REGISTRAZIONE=?, ID_MESSAGGIO=?, TIPO=?, BACKUP_ID_RICHIESTA=?, RICEVUTA_APPLICATIVA=1 WHERE  ID_MESSAGGIO = ? AND TIPO=?");

  1877.             pstmt = connectionDB.prepareStatement(query.toString());
  1878.             pstmt.setTimestamp(1,oraInvioRisposta);
  1879.             pstmt.setString(2,idRisposta);
  1880.             pstmt.setString(3,Costanti.OUTBOX);
  1881.             pstmt.setString(4,id);
  1882.             if(oldIDRisposta!=null && oldTipoRisposta!=null){
  1883.                 pstmt.setString(5,oldIDRisposta);
  1884.                 pstmt.setString(6,oldTipoRisposta);
  1885.             }else{
  1886.                 pstmt.setString(5,id);
  1887.                 pstmt.setString(6,Costanti.OUTBOX);
  1888.             }

  1889.             //  Add PreparedStatement
  1890.             state.getPreparedStatement().put("UPDATE save_RispostaAsincronaAsimmetricaInviata"+id,pstmt);

  1891.         } catch(Exception e) {
  1892.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore di registrazione risposta inviata "+id+": "+e.getMessage();      
  1893.             this.log.error(errorMsg,e);
  1894.             try{
  1895.                 if( pstmt != null )
  1896.                     pstmt.close();
  1897.             } catch(Exception er) {
  1898.                 // Eccezione SQL.
  1899.             }
  1900.             throw new ProtocolException(errorMsg,e);
  1901.         }

  1902.         History history = new History(state,this.log);

  1903.         // Registro la richiesta nell'history
  1904.         history.registraBustaInviata(id);

  1905.         // Registro la richiesta stato nell'history con il nuovo id
  1906.         if(this.state instanceof StatefulMessage) {
  1907.            
  1908.             // salvo busta per profilo
  1909.             this.registraBustaInviata(idRisposta);
  1910.            
  1911.         }else{
  1912.            
  1913.             StatelessMessage statelessMessage = (StatelessMessage) this.state;
  1914.            
  1915.             long scadenza = scadenzaMessaggi;
  1916.             if(scadenza<=0){
  1917.                 scadenza = this.protocolManager.getIntervalloScadenzaBuste();
  1918.             }
  1919.            
  1920.             // Registro proprio la busta
  1921.             RepositoryBuste repository = new RepositoryBuste(this.state,  this.log, true,this.protocolFactory);
  1922.             repository.registraBustaIntoOutBox(statelessMessage.getBusta(),scadenza);
  1923.             this.registraBustaInviata(idRisposta);
  1924.            
  1925.             // salvo busta per profilo
  1926.             PreparedStatement pstmtUpdate = null;
  1927.             try{
  1928.                 StringBuilder queryUpdate = new StringBuilder();
  1929.                 queryUpdate.append("UPDATE ");
  1930.                 queryUpdate.append(Costanti.REPOSITORY);
  1931.                 queryUpdate.append(" SET ");
  1932.                 queryUpdate.append(this.gestoreRepositoryBuste.createSQLSet_ProfiloCollaborazione(true));
  1933.                 queryUpdate.append(" WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  1934.                 pstmtUpdate = connectionDB.prepareStatement(queryUpdate.toString());
  1935.                 pstmtUpdate.setString(1,idRisposta);
  1936.                 pstmtUpdate.setString(2,Costanti.OUTBOX);

  1937.                 // Add PreparedStatement
  1938.                 state.getPreparedStatement().put("UPDATE saveBustaForProfilo"+Costanti.OUTBOX+"_"+idRisposta,pstmtUpdate);
  1939.                
  1940.             } catch(Exception e) {
  1941.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore di aggiornamento busta di risposta "+idRisposta+": "+e.getMessage();      
  1942.                 this.log.error(errorMsg,e);
  1943.                 try{
  1944.                     if( pstmtUpdate != null )
  1945.                         pstmtUpdate.close();
  1946.                 } catch(Exception er) {
  1947.                     // Eccezione SQL.
  1948.                 }
  1949.                 throw new ProtocolException(errorMsg,e);
  1950.             }
  1951.         }  
  1952.        

  1953.         //  I dati asincroni saranno eliminati quando scadra' la richiesta-stato asincrona
  1954.         history.registraBustaInviata(idRisposta);

  1955.         //  delete vecchia risposta
  1956.         if(oldIDRisposta!=null && oldTipoRisposta!=null){
  1957.             this.eliminaBusta(oldIDRisposta,oldTipoRisposta,true);
  1958.             history.eliminaBusta(oldIDRisposta,oldTipoRisposta,true);
  1959.         }

  1960.         return busta;
  1961.     }

  1962.     /**
  1963.      * Controlla se e' stato precedentemente registrata una richiesta asincrona simmetrica,
  1964.      * ritornando eventuale busta da usare con la ricevuta applicativa.
  1965.      *
  1966.      * @param id Identificativo della richiesta asincrona.
  1967.      * @param rifMsgRicevuta Riferimento Messaggio da applicare alla ricevuta.
  1968.      * @param isRichiesta Indicazione se si desidera la busta per una ricevuta ad una richiesta o risposta
  1969.      * @return Busta da utilizzare per la ricevuta
  1970.      *
  1971.      */
  1972.     public Busta asincronoAsimmetrico_getBustaRicevuta(String id,String rifMsgRicevuta,boolean isRichiesta,boolean generazioneAttributiAsincroni,TipoOraRegistrazione tipoTempo) throws ProtocolException{
  1973.         StateMessage state = (StateMessage)this.state;
  1974.         Connection connectionDB = state.getConnectionDB();
  1975.         // leggo servizio correlato
  1976.         String tipoServizioCorrelato = null;
  1977.         String servizioCorrelato = null;
  1978.         Integer versioneServizioCorrelato = null;
  1979.         PreparedStatement pstmtRead = null;
  1980.         ResultSet rsRead = null;
  1981.         try{
  1982.             StringBuilder query = new StringBuilder();
  1983.             query.append("SELECT TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO FROM ");
  1984.             query.append(Costanti.PROFILO_ASINCRONO);
  1985.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  1986.             pstmtRead = connectionDB.prepareStatement(query.toString());
  1987.             pstmtRead.setString(1,id);
  1988.             pstmtRead.setString(2,Costanti.INBOX);
  1989.             rsRead = pstmtRead.executeQuery();      
  1990.             if(rsRead == null) {
  1991.                 throw new ProtocolException("RS Read Null?");          
  1992.             }
  1993.             if(rsRead.next()){
  1994.                 tipoServizioCorrelato = rsRead.getString("TIPO_SERVIZIO_CORRELATO");
  1995.                 servizioCorrelato = rsRead.getString("SERVIZIO_CORRELATO");
  1996.                 versioneServizioCorrelato = rsRead.getInt("VERSIONE_SERVIZIO_CORRELATO");
  1997.                 if(rsRead.wasNull()){
  1998.                     versioneServizioCorrelato = null;
  1999.                 }
  2000.             }      
  2001.             rsRead.close();
  2002.             pstmtRead.close();

  2003.         }catch(Exception e){    
  2004.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, asincronoAsimmetrico_getBustaRicevuta, raccolta servizio correlato, "+id+": "+e.getMessage();
  2005.             this.log.error(errorMsg,e);
  2006.             try{
  2007.                 if( rsRead != null )
  2008.                     rsRead.close();
  2009.             } catch(Exception er) {
  2010.                 // Eccezione SQL.
  2011.             }
  2012.             try{
  2013.                 if( pstmtRead != null )
  2014.                     pstmtRead.close();
  2015.             } catch(Exception er) {
  2016.                 // Eccezione SQL.
  2017.             }
  2018.             throw new ProtocolException(errorMsg,e);
  2019.         }



  2020.         Busta busta = null;
  2021.         try{
  2022.             RepositoryBuste repository = new RepositoryBuste(state,  this.log, this.protocolFactory);
  2023.             LetturaParametriBusta parametri = new LetturaParametriBusta();
  2024.             parametri.setMittente(true);
  2025.             parametri.setDestinatario(true);
  2026.             parametri.setServizio(true);
  2027.             parametri.setAzione(true);
  2028.             parametri.setCollaborazione(true);
  2029.             parametri.setProfiloTrasmissione(true);
  2030.             parametri.setIndirizziTelematici(this.protocolConfiguration.isSupportoIndirizzoRisposta());
  2031.             busta = repository.getSomeValuesFromInBox(id, parametri, true); // prendo dati dal database

  2032.             if(isRichiesta==false){

  2033.                 // elimino busta per profilo
  2034.                 this.eliminaBustaRicevuta(id, true);
  2035.             }

  2036.             // costruzione busta di risposta  

  2037.             // profilo di collaborazione
  2038.             busta.setProfiloDiCollaborazione(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_ASIMMETRICO);

  2039.             // inverto mitt con dest
  2040.             String mitt = busta.getMittente();
  2041.             String tipoMitt = busta.getTipoMittente();
  2042.             String portaMitt = busta.getIdentificativoPortaMittente();
  2043.             String indMitt = busta.getIndirizzoMittente();
  2044.             busta.setMittente(busta.getDestinatario());
  2045.             busta.setTipoMittente(busta.getTipoDestinatario());
  2046.             busta.setIdentificativoPortaMittente(busta.getIdentificativoPortaDestinatario());
  2047.             busta.setIndirizzoMittente(busta.getIndirizzoDestinatario());
  2048.             busta.setDestinatario(mitt);
  2049.             busta.setTipoDestinatario(tipoMitt);
  2050.             busta.setIdentificativoPortaDestinatario(portaMitt);
  2051.             busta.setIndirizzoDestinatario(indMitt);

  2052.             if(isRichiesta){
  2053.                 // PRODUZIONE tipo e nome Servizio Correlato
  2054.                 if(generazioneAttributiAsincroni){
  2055.                     busta.setTipoServizioCorrelato(tipoServizioCorrelato);
  2056.                     busta.setServizioCorrelato(servizioCorrelato);
  2057.                     busta.setVersioneServizioCorrelato(versioneServizioCorrelato);
  2058.                 }
  2059.             }
  2060.             else{
  2061.                 busta.setTipoServizio(tipoServizioCorrelato);
  2062.                 busta.setServizio(servizioCorrelato);
  2063.                 busta.setVersioneServizio(versioneServizioCorrelato);
  2064.             }

  2065.             busta.setRiferimentoMessaggio(rifMsgRicevuta);
  2066.             busta.setOraRegistrazione(DateManager.getDate());
  2067.             busta.setTipoOraRegistrazione(tipoTempo,this.protocolTraduttore.toString(tipoTempo));

  2068.         }catch(Exception e){
  2069.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore durante la asincronoAsimmetrico_getBustaRicevuta dal repository "+id+": "+e.getMessage();    
  2070.             this.log.error(errorMsg,e);
  2071.             throw new ProtocolException(errorMsg,e);
  2072.         }

  2073.         return busta;

  2074.     }

  2075.     /**
  2076.      * Validazione della busta, che sia coerente con la precedente richiesta asincrona asimmetrica.
  2077.      *
  2078.      * @param bustaDaValidare Busta da controllare
  2079.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  2080.      *
  2081.      */
  2082.     public Eccezione asincronoAsimmetrico_validazioneCorrelazione_ricevutaRichiesta(Busta bustaDaValidare, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  2083.         return asincronoAsimmetrico_validazioneCorrelazione(bustaDaValidare,true,false,false,protocolFactory);
  2084.     }  

  2085.     /**
  2086.      * Validazione della busta, che sia coerente con la precedente richiesta asincrona asimmetrica.
  2087.      *
  2088.      * @param bustaDaValidare Busta da controllare
  2089.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  2090.      *
  2091.      */
  2092.     public Eccezione asincronoAsimmetrico_validazioneCorrelazione_richiestaStato(Busta bustaDaValidare, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  2093.         return asincronoAsimmetrico_validazioneCorrelazione(bustaDaValidare,false,true,false,protocolFactory);
  2094.     }  

  2095.     /**
  2096.      * Validazione della busta, che sia coerente con la precedente richiesta asincrona asimmetrica.
  2097.      *
  2098.      * @param bustaDaValidare Busta da controllare
  2099.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  2100.      *
  2101.      */
  2102.     public Eccezione asincronoAsimmetrico_validazioneCorrelazione_ricevutaRichiestaStato(Busta bustaDaValidare, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  2103.         return asincronoAsimmetrico_validazioneCorrelazione(bustaDaValidare,false,false,true,protocolFactory);
  2104.     }  


  2105.     /**
  2106.      * Validazione della busta, che sia coerente con la precedente richiesta asincrona asimmetrica.
  2107.      *
  2108.      * @param bustaDaValidare Busta da controllare
  2109.      * @param isRicevutaRichiesta Ricevuta della Richiesta
  2110.      * @param isRichiestaStato RichiestaStato
  2111.      * @param isRicevutaRichiestaStato Ricevuta della Risposta
  2112.      * @return una Eccezione se la validazione fallisce, null altrimenti.
  2113.      *
  2114.      */
  2115.     private Eccezione asincronoAsimmetrico_validazioneCorrelazione(Busta bustaDaValidare,boolean isRicevutaRichiesta,boolean isRichiestaStato,
  2116.             boolean isRicevutaRichiestaStato, IProtocolFactory<?> protocolFactory) throws ProtocolException{
  2117.         StateMessage state = (StateMessage)this.state;
  2118.         Connection connectionDB = state.getConnectionDB();
  2119.         Busta bustaRichiesta = null;
  2120.         try{
  2121.             RepositoryBuste repository = new RepositoryBuste(state,  this.log, this.protocolFactory);
  2122.             LetturaParametriBusta parametri = new LetturaParametriBusta();
  2123.             parametri.setMittente(true);
  2124.             parametri.setDestinatario(true);
  2125.             parametri.setServizio(true);
  2126.             parametri.setAzione(true);
  2127.             if(isRichiestaStato){
  2128.                 // NOTA:
  2129.                 //   una busta asincrona RISPOSTA puo avere riferimentoMessaggio o collaborazione
  2130.                 if(bustaDaValidare.getRiferimentoMessaggio()==null)
  2131.                     bustaRichiesta = repository.getSomeValuesFromInBox(bustaDaValidare.getCollaborazione(),parametri,true); // deve leggere sempre da database
  2132.                 else
  2133.                     bustaRichiesta = repository.getSomeValuesFromInBox(bustaDaValidare.getRiferimentoMessaggio(),parametri,true); // deve leggere sempre da database
  2134.             }else
  2135.                 bustaRichiesta = repository.getSomeValuesFromOutBox(bustaDaValidare.getRiferimentoMessaggio(),parametri,true); // deve leggere sempre da database
  2136.         }catch(Exception e){
  2137.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, Errore durante la validazioneCorrelazione, get dal repository RifMsg("+bustaDaValidare.getRiferimentoMessaggio()+") Collab("+bustaDaValidare.getCollaborazione()+"): "+e.getMessage();
  2138.             this.log.error(errorMsg,e);
  2139.             throw new ProtocolException(errorMsg,e);
  2140.         }

  2141.         // Validazione Servizio (Tipo e Nome)
  2142.         // Obbligatoria per una risposta, opzionale per una ricevuta
  2143.         if( isRicevutaRichiesta ){
  2144.             if(bustaDaValidare.getServizio()!=null && bustaDaValidare.getTipoServizio()!=null){
  2145.                 if (bustaRichiesta.getTipoServizio().equals(bustaDaValidare.getTipoServizio())==false){
  2146.                     String msgErrore = "Tipo di servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2147.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_SERVIZIO_NON_VALIDO.
  2148.                             getErroreCooperazione(msgErrore),
  2149.                             true,null,protocolFactory);
  2150.                     this.log.error(msgErrore);
  2151.                     return eccValidazione;
  2152.                 }
  2153.                 if (bustaRichiesta.getServizio().equals(bustaDaValidare.getServizio())==false){
  2154.                     String msgErrore = "Servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2155.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.SERVIZIO_NON_VALIDO.
  2156.                             getErroreCooperazione(msgErrore),
  2157.                             true,null,protocolFactory);
  2158.                     this.log.error(msgErrore);
  2159.                     return eccValidazione;
  2160.                 }
  2161.             }
  2162.         }
  2163.         else if(  (isRichiestaStato) || (isRicevutaRichiestaStato && bustaDaValidare.getServizio()!=null && bustaDaValidare.getTipoServizio()!=null) ) {

  2164.             // Validazione Servizio (Tipo e Nome)
  2165.             PreparedStatement pstmt = null;
  2166.             ResultSet rs = null;
  2167.             try{
  2168.                 StringBuilder query = new StringBuilder();
  2169.                 query.append("SELECT TIPO_SERVIZIO_CORRELATO,SERVIZIO_CORRELATO,VERSIONE_SERVIZIO_CORRELATO FROM ");
  2170.                 query.append(Costanti.PROFILO_ASINCRONO);
  2171.                 query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  2172.                 pstmt = connectionDB.prepareStatement(query.toString());

  2173.                 // NOTA:
  2174.                 //   una busta asincrona RISPOSTA puo avere riferimentoMessaggio o collaborazione
  2175.                 if(isRichiestaStato && bustaDaValidare.getRiferimentoMessaggio()==null)
  2176.                     pstmt.setString(1,bustaDaValidare.getCollaborazione());
  2177.                 else
  2178.                     pstmt.setString(1,bustaDaValidare.getRiferimentoMessaggio());          

  2179.                 if(isRichiestaStato)
  2180.                     pstmt.setString(2,Costanti.INBOX);
  2181.                 else
  2182.                     pstmt.setString(2,Costanti.OUTBOX);
  2183.                 rs = pstmt.executeQuery();      
  2184.                 if(rs == null) {
  2185.                     throw new ProtocolException("RS Null?");            
  2186.                 }
  2187.                 String tipoServizioCorrelatoRegistrato = null;
  2188.                 String servizioCorrelatoRegistrato = null;
  2189.                 Integer versioneServizioCorrelatoRegistrato = null;
  2190.                 if(rs.next()){
  2191.                     tipoServizioCorrelatoRegistrato = rs.getString("TIPO_SERVIZIO_CORRELATO");
  2192.                     servizioCorrelatoRegistrato = rs.getString("SERVIZIO_CORRELATO");
  2193.                     versioneServizioCorrelatoRegistrato = rs.getInt("VERSIONE_SERVIZIO_CORRELATO");
  2194.                 }
  2195.                 rs.close();
  2196.                 pstmt.close();

  2197.                 if (bustaDaValidare.getTipoServizio().equals(tipoServizioCorrelatoRegistrato) == false){
  2198.                     String msgErrore = "Tipo di servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2199.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_SERVIZIO_NON_VALIDO.
  2200.                             getErroreCooperazione(msgErrore),
  2201.                             true,null,protocolFactory);
  2202.                     this.log.error(msgErrore);
  2203.                     return eccValidazione;
  2204.                 }
  2205.                 if (bustaDaValidare.getServizio().equals(servizioCorrelatoRegistrato) == false){
  2206.                     String msgErrore = "Servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2207.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.SERVIZIO_NON_VALIDO.
  2208.                             getErroreCooperazione(msgErrore),
  2209.                             true,null,protocolFactory);
  2210.                     this.log.error(msgErrore);
  2211.                     return eccValidazione;
  2212.                 }
  2213.                 if(versioneServizioCorrelatoRegistrato==null){
  2214.                     versioneServizioCorrelatoRegistrato = -1; //valore errato inserito appositamente
  2215.                 }
  2216.                 if (bustaDaValidare.getVersioneServizio().intValue() != versioneServizioCorrelatoRegistrato.intValue()){
  2217.                     String msgErrore = "Versione del servizio diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2218.                     Eccezione eccValidazione = new Eccezione(ErroriCooperazione.VERSIONE_SERVIZIO_NON_VALIDO.
  2219.                             getErroreCooperazione(msgErrore),
  2220.                             true,null,protocolFactory);
  2221.                     this.log.error(msgErrore);
  2222.                     return eccValidazione;
  2223.                 }


  2224.             }catch(Exception e){    
  2225.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, validazioneCorrelazione RifMsg("+bustaDaValidare.getRiferimentoMessaggio()+") Collab("+bustaDaValidare.getCollaborazione()+"): "+e.getMessage();
  2226.                 this.log.error(errorMsg,e);
  2227.                 try{
  2228.                     if( rs != null )
  2229.                         rs.close();
  2230.                 } catch(Exception er) {
  2231.                     // Eccezione SQL.
  2232.                 }
  2233.                 try{
  2234.                     if( pstmt != null )
  2235.                         pstmt.close();
  2236.                 } catch(Exception er) {
  2237.                     // Eccezione SQL.
  2238.                 }
  2239.                 throw new ProtocolException(errorMsg,e);
  2240.             }
  2241.         }

  2242.         // Validazione altri parametri busta
  2243.         // L'azione di una ricevuta deve essere la stessa di quella della richiesta/richiestaStato
  2244.         if(bustaDaValidare.getAzione()!=null && isRichiestaStato==false){
  2245.             if (bustaDaValidare.getAzione().equals(bustaRichiesta.getAzione()) == false){
  2246.                 String msgErrore = "Azione diversa da quello attesa nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2247.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.AZIONE_NON_VALIDA.
  2248.                         getErroreCooperazione(msgErrore),
  2249.                         true,null,protocolFactory);
  2250.                 this.log.error(msgErrore);
  2251.                 return eccValidazione;
  2252.             }
  2253.         }
  2254.         if(isRichiestaStato){
  2255.             if (bustaRichiesta.getTipoMittente().equals(bustaDaValidare.getTipoMittente()) == false){
  2256.                 String msgErrore = "Tipo del mittente diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2257.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_MITTENTE_NON_VALIDO.
  2258.                         getErroreCooperazione(msgErrore),
  2259.                         true,null,protocolFactory);
  2260.                 this.log.error(msgErrore);
  2261.                 return eccValidazione;
  2262.             }
  2263.             if (bustaRichiesta.getMittente().equals(bustaDaValidare.getMittente()) == false){
  2264.                 String msgErrore = "Mittente diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2265.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.MITTENTE_NON_VALIDO.
  2266.                         getErroreCooperazione(msgErrore),
  2267.                         true,null,protocolFactory);
  2268.                 this.log.error(msgErrore);
  2269.                 return eccValidazione;
  2270.             }
  2271.             if (bustaRichiesta.getTipoDestinatario().equals(bustaDaValidare.getTipoDestinatario()) == false){
  2272.                 String msgErrore = "Tipo del destinatario diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2273.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_DESTINATARIO_NON_VALIDO.
  2274.                         getErroreCooperazione(msgErrore),
  2275.                         true,null,protocolFactory);
  2276.                 this.log.error(msgErrore);
  2277.                 return eccValidazione;
  2278.             }
  2279.             if (bustaRichiesta.getDestinatario().equals(bustaDaValidare.getDestinatario()) == false){
  2280.                 String msgErrore = "Destinatario diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2281.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.DESTINATARIO_NON_VALIDO.
  2282.                         getErroreCooperazione(msgErrore),
  2283.                         true,null,protocolFactory);
  2284.                 this.log.error(msgErrore);
  2285.                 return eccValidazione;
  2286.             }
  2287.         }else{
  2288.             if (bustaRichiesta.getTipoDestinatario().equals(bustaDaValidare.getTipoMittente()) == false){
  2289.                 String msgErrore = "Tipo del mittente diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2290.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_MITTENTE_NON_VALIDO.
  2291.                         getErroreCooperazione(msgErrore),
  2292.                         true,null,protocolFactory);
  2293.                 this.log.error(msgErrore);
  2294.                 return eccValidazione;
  2295.             }
  2296.             if (bustaRichiesta.getDestinatario().equals(bustaDaValidare.getMittente()) == false){
  2297.                 String msgErrore = "Mittente diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2298.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.MITTENTE_NON_VALIDO.
  2299.                         getErroreCooperazione(msgErrore),
  2300.                         true,null,protocolFactory);
  2301.                 this.log.error(msgErrore);
  2302.                 return eccValidazione;
  2303.             }
  2304.             if (bustaRichiesta.getTipoMittente().equals(bustaDaValidare.getTipoDestinatario()) == false){
  2305.                 String msgErrore = "Tipo del destinatario diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2306.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.TIPO_DESTINATARIO_NON_VALIDO.
  2307.                         getErroreCooperazione(msgErrore),
  2308.                         true,null,protocolFactory);
  2309.                 this.log.error(msgErrore);
  2310.                 return eccValidazione;
  2311.             }
  2312.             if (bustaRichiesta.getMittente().equals(bustaDaValidare.getDestinatario()) == false){
  2313.                 String msgErrore = "Destinatario diverso da quello atteso nella gestione del profilo di collaborazione Asincrono Asimmetrico";
  2314.                 Eccezione eccValidazione = new Eccezione(ErroriCooperazione.DESTINATARIO_NON_VALIDO.
  2315.                         getErroreCooperazione(msgErrore),
  2316.                         true,null,protocolFactory);
  2317.                 this.log.error(msgErrore);
  2318.                 return eccValidazione;
  2319.             }
  2320.         }
  2321.         return null;
  2322.     }

  2323.     /**
  2324.      * Validazione del riferimentoMessaggio di una busta asincrona asimmetrica.
  2325.      *
  2326.      * @param riferimentoMessaggio Identificativo.
  2327.      * @return true se esiste una entry nella tabella apposita.
  2328.      *
  2329.      */
  2330.     public boolean asincronoAsimmetrico_validazioneRiferimentoMessaggio_richiestaStato(String riferimentoMessaggio) throws ProtocolException{
  2331.         return asincronoAsimmetrico_validazioneRiferimentoMessaggio(riferimentoMessaggio,true);
  2332.     }

  2333.     /**
  2334.      * Validazione del riferimentoMessaggio di una busta asincrona asimmetrica.
  2335.      *
  2336.      * @param riferimentoMessaggio Identificativo.
  2337.      * @return true se esiste una entry nella tabella apposita.
  2338.      *
  2339.      */
  2340.     public boolean asincronoAsimmetrico_validazioneRiferimentoMessaggio_ricevuta(String riferimentoMessaggio) throws ProtocolException{
  2341.         return asincronoAsimmetrico_validazioneRiferimentoMessaggio(riferimentoMessaggio,false);
  2342.     }

  2343.     /**
  2344.      * Validazione del riferimentoMessaggio di una busta asincrona asimmetrica.
  2345.      *
  2346.      * @param riferimentoMessaggio Identificativo.
  2347.      * @param isRichiestaStato Indicazione se la busta da validare e' una richiesta stato
  2348.      * @return true se esiste una entry nella tabella apposita.
  2349.      *
  2350.      */
  2351.     private boolean asincronoAsimmetrico_validazioneRiferimentoMessaggio(String riferimentoMessaggio,boolean isRichiestaStato) throws ProtocolException{
  2352.         StateMessage state = (StateMessage)this.state;
  2353.         Connection connectionDB = state.getConnectionDB();
  2354.         PreparedStatement pstmt = null;
  2355.         ResultSet rs = null;
  2356.         try{
  2357.             StringBuilder query = new StringBuilder();
  2358.             query.append("SELECT ID_MESSAGGIO FROM ");
  2359.             query.append(Costanti.PROFILO_ASINCRONO);
  2360.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  2361.             pstmt = connectionDB.prepareStatement(query.toString());
  2362.             pstmt.setString(1,riferimentoMessaggio);
  2363.             if(isRichiestaStato)
  2364.                 pstmt.setString(2,Costanti.INBOX);
  2365.             else
  2366.                 pstmt.setString(2,Costanti.OUTBOX);
  2367.             rs = pstmt.executeQuery();      
  2368.             if(rs == null) {
  2369.                 throw new ProtocolException("RS Null?");            
  2370.             }
  2371.             boolean value = rs.next();

  2372.             rs.close();
  2373.             pstmt.close();

  2374.             RepositoryBuste repositoryBuste = new RepositoryBuste(state, this.log, this.protocolFactory);
  2375.             if(isRichiestaStato)
  2376.                 return value && repositoryBuste.isRegistrataIntoInBox(riferimentoMessaggio);
  2377.             else
  2378.                 return value && repositoryBuste.isRegistrataIntoOutBox(riferimentoMessaggio);

  2379.         }catch(Exception e){    
  2380.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, validazioneRiferimentoMessaggio "+riferimentoMessaggio+": "+e.getMessage();
  2381.             this.log.error(errorMsg,e);
  2382.             try{
  2383.                 if( rs != null )
  2384.                     rs.close();
  2385.             } catch(Exception er) {
  2386.                 // Eccezione SQL.
  2387.             }
  2388.             try{
  2389.                 if( pstmt != null )
  2390.                     pstmt.close();
  2391.             } catch(Exception er) {
  2392.                 // Eccezione SQL.
  2393.             }
  2394.             throw new ProtocolException(errorMsg,e);
  2395.         }
  2396.     }

  2397.     /**
  2398.      * Validazione della collaborazione di una busta asincrona.
  2399.      *
  2400.      * @param riferimentoMessaggio Identificativo.
  2401.      * @param idCollaborazione Collaborazione
  2402.      * @return true se la collaborazione e' valida
  2403.      *
  2404.      */
  2405.     public boolean asincronoAsimmetrico_validazioneCollaborazione_richiestaStato(String riferimentoMessaggio,String idCollaborazione) throws ProtocolException{
  2406.         return asincronoAsimmetrico_validazioneCollaborazione(riferimentoMessaggio,idCollaborazione,true);
  2407.     }

  2408.     /**
  2409.      * Validazione della collaborazione di una busta asincrona.
  2410.      *
  2411.      * @param riferimentoMessaggio Identificativo.
  2412.      * @param idCollaborazione Collaborazione
  2413.      * @return true se la collaborazione e' valida
  2414.      *
  2415.      */
  2416.     public boolean asincronoAsimmetrico_validazioneCollaborazione_ricevuta(String riferimentoMessaggio,String idCollaborazione) throws ProtocolException{
  2417.         return asincronoAsimmetrico_validazioneCollaborazione(riferimentoMessaggio,idCollaborazione,false);
  2418.     }

  2419.     /**
  2420.      * Validazione della collaborazione di una busta asincrona.
  2421.      *
  2422.      * @param riferimentoMessaggio Identificativo.
  2423.      * @param idCollaborazione Collaborazione
  2424.      * @param isRichiestaStato Indicazione se la busta da validare e' una richiesta stato
  2425.      * @return true se la collaborazione e' valida
  2426.      *
  2427.      */
  2428.     private boolean asincronoAsimmetrico_validazioneCollaborazione(String riferimentoMessaggio,String idCollaborazione,boolean isRichiestaStato) throws ProtocolException{
  2429.         StateMessage state = (StateMessage)this.state;
  2430.         Connection connectionDB = state.getConnectionDB();
  2431.         PreparedStatement pstmt = null;
  2432.         ResultSet rs = null;
  2433.         try{
  2434.             StringBuilder query = new StringBuilder();
  2435.             query.append("SELECT ID_COLLABORAZIONE FROM ");
  2436.             query.append(Costanti.PROFILO_ASINCRONO);
  2437.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  2438.             pstmt = connectionDB.prepareStatement(query.toString());

  2439.             // NOTA:
  2440.             //   una busta asincrona RISPOSTA puo avere riferimentoMessaggio o collaborazione
  2441.             if(isRichiestaStato && riferimentoMessaggio==null)
  2442.                 pstmt.setString(1,idCollaborazione);
  2443.             else
  2444.                 pstmt.setString(1,riferimentoMessaggio);

  2445.             if(isRichiestaStato)
  2446.                 pstmt.setString(2,Costanti.INBOX);
  2447.             else
  2448.                 pstmt.setString(2,Costanti.OUTBOX);
  2449.             rs = pstmt.executeQuery();      
  2450.             if(rs == null) {
  2451.                 throw new ProtocolException("RS Null?");            
  2452.             }
  2453.             String value = null;
  2454.             if(rs.next()){
  2455.                 value = rs.getString("ID_COLLABORAZIONE");
  2456.             }

  2457.             rs.close();
  2458.             pstmt.close();

  2459.             return idCollaborazione.equals(value);

  2460.         }catch(Exception e){    
  2461.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONOASIMMETRICO, validazioneCollaborazione "+riferimentoMessaggio+": "+e.getMessage();
  2462.             this.log.error(errorMsg,e);
  2463.             try{
  2464.                 if( rs != null )
  2465.                     rs.close();
  2466.             } catch(Exception er) {
  2467.                 // Eccezione SQL.
  2468.             }
  2469.             try{
  2470.                 if( pstmt != null )
  2471.                     pstmt.close();
  2472.             } catch(Exception er) {
  2473.                 // Eccezione SQL.
  2474.             }
  2475.             throw new ProtocolException(errorMsg,e);
  2476.         }
  2477.     }


  2478.    
  2479.    
  2480.    
  2481.    
  2482.    
  2483.    
  2484.    
  2485.    
  2486.    

  2487.     /* ********  PROFILO ASINCRONO ******** */

  2488.     /**
  2489.      * In caso esista nella tabella asincrona buste inviate che non sono state ringraziate da una ricevuta dopo un intervallo di tempo,
  2490.      * si occupa di ritornare un array di buste da reinviare, aggiornando le loro date di registrazione.
  2491.      *
  2492.      * @param timeout Minuti dopo il quale una data risulta scaduta.
  2493.      * @return un List di {@link org.openspcoop2.protocol.sdk.Busta} contenente le informazioni necessarie per il re-invio delle buste,
  2494.      *         se esistono buste non ringraziate.
  2495.      * @deprecated utilizzare la versione non serializable
  2496.      */
  2497.     @Deprecated
  2498.     public List<Busta> asincrono_getBusteAsincronePerUlterioreInoltro_serializable(long timeout)throws ProtocolException{
  2499.         return this.asincrono_getBusteAsincronePerUlterioreInoltro_serializable(timeout,60l,100);
  2500.     }

  2501.     /**
  2502.      * In caso esista nella tabella asincrona buste inviate che non sono state ringraziate da una ricevuta dopo un intervallo di tempo,
  2503.      * si occupa di ritornare un array di buste da reinviare, aggiornando le loro date di registrazione.
  2504.      *
  2505.      * @param timeout Minuti dopo il quale una data risulta scaduta.
  2506.      * @param attesaAttiva AttesaAttiva per la gestione del livello di serializable
  2507.      * @param checkInterval Intervallo di check per la gestione  del livello di serializable
  2508.      * @return un List di {@link org.openspcoop2.protocol.sdk.Busta} contenente le informazioni necessarie per il re-invio delle buste,
  2509.      *         se esistono buste non ringraziate.
  2510.      * @deprecated utilizzare la versione non serializable
  2511.      */
  2512.     @Deprecated
  2513.     public List<Busta> asincrono_getBusteAsincronePerUlterioreInoltro_serializable(long timeout,long attesaAttiva,int checkInterval)throws ProtocolException{
  2514.         if(this.state instanceof StatefulMessage) {
  2515.             StatefulMessage stateful = (StatefulMessage)this.state;
  2516.             Connection connectionDB = stateful.getConnectionDB();

  2517.             /*
  2518.              * Viene realizzato con livello di isolamento SERIALIZABLE, per essere sicuri
  2519.              *  di leggere solo le indicazioni di richieste asincrone committate,
  2520.              * e comunque rispedira' anche le buste eliminate, ma non committate.
  2521.              */
  2522.             // setAutoCommit e livello Isolamento
  2523.             int oldTransactionIsolation = -1;
  2524.             try{
  2525.                 oldTransactionIsolation = connectionDB.getTransactionIsolation();
  2526.                 connectionDB.setAutoCommit(false);
  2527.                 JDBCUtilities.setTransactionIsolationSerializable(Configurazione.getSqlQueryObjectType(), connectionDB);
  2528.             } catch(Exception er) {
  2529.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, Errore durante la getBusteAsincronePerUlterioreInoltro(setIsolation): "+er.getMessage();        
  2530.                 this.log.error(errorMsg,er);
  2531.                 throw new ProtocolException(errorMsg,er);
  2532.             }

  2533.             boolean getBusteOK = false;
  2534.             java.util.List<Busta> busteNonRingraziate = new java.util.ArrayList<Busta>();  

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

  2536.             while(getBusteOK==false && DateManager.getTimeMillis() < scadenzaWhile){

  2537.                 PreparedStatement pstmt = null;
  2538.                 ResultSet rs = null;
  2539.                 java.util.List<String> IDBuste = new java.util.ArrayList<>();
  2540.                 try{    

  2541.                     long nowTime = DateManager.getTimeMillis() - (timeout * 60 * 1000);
  2542.                     java.sql.Timestamp scadenzaRingraziamento = new java.sql.Timestamp(nowTime);

  2543.                     StringBuilder query = new StringBuilder();
  2544.                     query.append("SELECT ID_MESSAGGIO FROM ");
  2545.                     query.append(Costanti.PROFILO_ASINCRONO);
  2546.                     query.append(" WHERE ORA_REGISTRAZIONE < ? AND TIPO=? AND RICEVUTA_ASINCRONA=0 AND RICEVUTA_APPLICATIVA=0 FOR UPDATE");

  2547.                     pstmt = connectionDB.prepareStatement(query.toString());
  2548.                     pstmt.setTimestamp(1,scadenzaRingraziamento);  
  2549.                     pstmt.setString(2,Costanti.OUTBOX);

  2550.                     // Esecuzione comando SQL
  2551.                     rs = pstmt.executeQuery();      
  2552.                     if(rs == null) {
  2553.                         pstmt.close();
  2554.                         return null;
  2555.                     }      
  2556.                     while(rs.next()){
  2557.                         String id = rs.getString("ID_MESSAGGIO");
  2558.                         IDBuste.add(id);
  2559.                     }
  2560.                     rs.close();
  2561.                     pstmt.close();
  2562.                     if(IDBuste.size() > 0){
  2563.                         RepositoryBuste repositoryBuste = new RepositoryBuste(stateful, this.log, this.protocolFactory);
  2564.                         for(int i=0; i<IDBuste.size();i++){
  2565.                             String id = IDBuste.get(i);
  2566.                             try{
  2567.                                 Busta busta = repositoryBuste.getBustaFromOutBox(id);
  2568.                                 busteNonRingraziate.add(busta);
  2569.                             }catch(Exception e){
  2570.                                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, Errore durante la getBusteAsincronePerUlterioreInoltro (read busta ["+id+"]): "+e.getMessage();    
  2571.                                 this.log.error(errorMsg);
  2572.                             }
  2573.                         }
  2574.                     }
  2575.                     // Chiusura Transazione
  2576.                     connectionDB.commit();

  2577.                     // ID Costruito
  2578.                     getBusteOK = true;

  2579.                 } catch(Exception e) {
  2580.                     //log.error("ERROR GET BUSTA ASINCRONA PER ULTERIORE INOLTRO ["+e.getMessage()+"]");
  2581.                     try{
  2582.                         if( pstmt != null )
  2583.                             pstmt.close();
  2584.                     } catch(Exception er) {
  2585.                         // close
  2586.                     }
  2587.                     try{
  2588.                         if( rs != null )
  2589.                             rs.close();
  2590.                     } catch(Exception er) {
  2591.                         // close
  2592.                     }
  2593.                     try{
  2594.                         connectionDB.rollback();
  2595.                     } catch(Exception er) {
  2596.                         // ignore
  2597.                     }
  2598.                 }

  2599.                 if(getBusteOK == false){
  2600.                     // Per aiutare ad evitare conflitti
  2601.                     try{
  2602.                         Utilities.sleep(ProtocolRandomUtilities.getRandom().nextInt(checkInterval)); // random da 0ms a checkIntervalms
  2603.                     }catch(Exception eRandom){
  2604.                         // ignore
  2605.                     }
  2606.                 }
  2607.             }

  2608.             // Ripristino Transazione
  2609.             try{
  2610.                 connectionDB.setTransactionIsolation(oldTransactionIsolation);
  2611.                 connectionDB.setAutoCommit(true);
  2612.             } catch(Exception er) {
  2613.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, Errore durante la getBusteAsincronePerUlterioreInoltro(ripristinoIsolation): "+er.getMessage();    
  2614.                 this.log.error(errorMsg,er);
  2615.                 throw new ProtocolException(errorMsg,er);
  2616.             }
  2617.             return busteNonRingraziate;
  2618.         }else if (this.state instanceof StatelessMessage){
  2619.             //CHECKME
  2620.             throw new ProtocolException("Metodo non invocabile in modalita Stateless");
  2621.         }else{
  2622.             throw new ProtocolException("Metodo invocato con IState non valido");
  2623.         }
  2624.     }


  2625.     /**
  2626.      * In caso esista nella tabella asincrona buste inviate che non sono state ringraziate da una ricevuta dopo un intervallo di tempo,
  2627.      * si occupa di ritornare un array di buste da reinviare, aggiornando le loro date di registrazione.
  2628.      *
  2629.      * @param timeout Minuti dopo il quale una data risulta scaduta.
  2630.      * @return un List di {@link org.openspcoop2.protocol.sdk.Busta} contenente le informazioni necessarie per il re-invio delle buste,
  2631.      *         se esistono buste non ringraziate.
  2632.      */
  2633.     public List<BustaNonRiscontrata> asincrono_getBusteAsincronePerUlterioreInoltro(long timeout,int limit,int offset,boolean logQuery)throws ProtocolException{
  2634.         if(this.state instanceof StatefulMessage) {
  2635.             StatefulMessage stateful = (StatefulMessage)this.state;
  2636.             Connection connectionDB = stateful.getConnectionDB();
  2637.            
  2638.             PreparedStatement pstmt = null;
  2639.             ResultSet rs = null;
  2640.             java.util.List<String> IDBuste = new java.util.ArrayList<>();
  2641.             String queryString = null;
  2642.             try{    

  2643.                 long nowTime = DateManager.getTimeMillis()- (timeout * 60 * 1000);
  2644.                 java.sql.Timestamp scadenzaRingraziamento = new java.sql.Timestamp(nowTime);
  2645.                 IGestoreRepository gestoreRepositoryBuste = Configurazione.getGestoreRepositoryBuste();
  2646.                
  2647.                 if(Configurazione.getSqlQueryObjectType()==null){
  2648.                     StringBuilder query = new StringBuilder();
  2649.                     query.append("SELECT ID_MESSAGGIO FROM ");
  2650.                     query.append(Costanti.PROFILO_ASINCRONO);
  2651.                     query.append(" WHERE ORA_REGISTRAZIONE < ? AND TIPO=? AND RICEVUTA_ASINCRONA=0 AND RICEVUTA_APPLICATIVA=0");
  2652.                     // Nuovo AND per la gestione stateless
  2653.                     // Le ricevute asincrone non devono cmq appartenere a buste ormai eliminate
  2654.                     query.append(" AND NOT EXISTS (SELECT ID_MESSAGGIO FROM ");
  2655.                     query.append(Costanti.REPOSITORY);
  2656.                     query.append(" WHERE ");
  2657.                     query.append(Costanti.REPOSITORY);
  2658.                     query.append(".TIPO=");
  2659.                     query.append(Costanti.PROFILO_ASINCRONO);
  2660.                     query.append(".TIPO");
  2661.                     query.append(" AND ");
  2662.                     query.append(Costanti.REPOSITORY);
  2663.                     query.append(".ID_MESSAGGIO=");
  2664.                     query.append(Costanti.PROFILO_ASINCRONO);
  2665.                     query.append(".ID_MESSAGGIO");
  2666.                     query.append(" AND ");
  2667.                     query.append(gestoreRepositoryBuste.createSQLCondition_PdD(false));
  2668.                     query.append(" AND ");
  2669.                     query.append(gestoreRepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  2670.                     query.append(" ) ");
  2671.                    
  2672.                     queryString = query.toString();
  2673.                 }else{
  2674.                     ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  2675.                     sqlQueryObject.addSelectField("ID_MESSAGGIO");
  2676.                     sqlQueryObject.addSelectField("ORA_REGISTRAZIONE");
  2677.                     sqlQueryObject.addSelectField("TIPO");
  2678.                     sqlQueryObject.addSelectField("RICEVUTA_ASINCRONA");
  2679.                     sqlQueryObject.addSelectField("RICEVUTA_APPLICATIVA");
  2680.                     sqlQueryObject.addFromTable(Costanti.PROFILO_ASINCRONO);
  2681.                     sqlQueryObject.addWhereCondition("ORA_REGISTRAZIONE < ?");
  2682.                     sqlQueryObject.addWhereCondition("TIPO=?");
  2683.                     sqlQueryObject.addWhereCondition("RICEVUTA_ASINCRONA=0");
  2684.                     sqlQueryObject.addWhereCondition("RICEVUTA_APPLICATIVA=0");
  2685.                    
  2686.                     // Nuovo AND per la gestione stateless
  2687.                     // Le ricevute asincrone non devono cmq appartenere a buste ormai eliminate
  2688.                     ISQLQueryObject sqlQueryObjectNotExists = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  2689.                     sqlQueryObjectNotExists.addFromTable(Costanti.REPOSITORY);
  2690.                     sqlQueryObjectNotExists.addSelectField(Costanti.REPOSITORY,"ID_MESSAGGIO");
  2691.                     sqlQueryObjectNotExists.addWhereCondition(Costanti.REPOSITORY+".TIPO="+Costanti.PROFILO_ASINCRONO+".TIPO");
  2692.                     sqlQueryObjectNotExists.addWhereCondition(Costanti.REPOSITORY+".ID_MESSAGGIO="+Costanti.PROFILO_ASINCRONO+".ID_MESSAGGIO");
  2693.                     sqlQueryObjectNotExists.addWhereCondition(gestoreRepositoryBuste.createSQLCondition_PdD(false));
  2694.                     sqlQueryObjectNotExists.addWhereCondition(gestoreRepositoryBuste.createSQLCondition_ProfiloCollaborazione(false));
  2695.                     sqlQueryObjectNotExists.setANDLogicOperator(true);
  2696.                     sqlQueryObject.addWhereExistsCondition(true, sqlQueryObjectNotExists);
  2697.                    
  2698.                     sqlQueryObject.setANDLogicOperator(true);
  2699.                     sqlQueryObject.addOrderBy("ORA_REGISTRAZIONE"); // order by e' obbligatorio essendoci l'offset
  2700.                     sqlQueryObject.setSortType(true);
  2701.                     sqlQueryObject.setLimit(limit);
  2702.                     sqlQueryObject.setOffset(offset);
  2703.                     queryString = sqlQueryObject.createSQLQuery();
  2704.                 }

  2705.                 //System.out.println("QUERY ASINCRONO IS: ["+queryString+"] 1["+scadenzaRingraziamento+"] 2["+Costanti.OUTBOX+"]");

  2706.                 pstmt = connectionDB.prepareStatement(queryString);
  2707.                 pstmt.setTimestamp(1,scadenzaRingraziamento);  
  2708.                 pstmt.setString(2,Costanti.OUTBOX);

  2709.                 // Esecuzione comando SQL
  2710.                 long startDateSQLCommand = DateManager.getTimeMillis();
  2711.                 if(logQuery)
  2712.                     this.log.debug("[QUERY] (RicevuteAsincrone) ["+queryString+"] 1["+scadenzaRingraziamento+"] 2["+Costanti.OUTBOX+"]...");
  2713.                 rs = pstmt.executeQuery();  
  2714.                 long endDateSQLCommand = DateManager.getTimeMillis();
  2715.                 long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  2716.                 if(logQuery)
  2717.                     this.log.debug("[QUERY] (RicevuteAsincrone) ["+queryString+"] 1["+scadenzaRingraziamento+"] 2["+Costanti.OUTBOX+"] effettuata in "+secondSQLCommand+" secondi");

  2718.                 if(rs == null) {
  2719.                     pstmt.close();
  2720.                     return null;
  2721.                 }  
  2722.                 int countLimit = 0;
  2723.                 int countOffset = 0;
  2724.                 while(rs.next()){
  2725.                     if(Configurazione.getSqlQueryObjectType()==null){
  2726.                         // OFFSET APPLICATIVO
  2727.                         if( countOffset>=offset ){
  2728.                             String id = rs.getString("ID_MESSAGGIO");
  2729.                             IDBuste.add(id);
  2730.                             // LIMIT Applicativo
  2731.                             countLimit++;
  2732.                             if(countLimit==limit)
  2733.                                 break;
  2734.                         }
  2735.                         else{
  2736.                             countOffset++;
  2737.                         }
  2738.                     }else{
  2739.                         String id = rs.getString("ID_MESSAGGIO");
  2740.                         IDBuste.add(id);
  2741.                     }
  2742.                 }
  2743.                 rs.close();
  2744.                 pstmt.close();

  2745.             } catch(Exception e) {
  2746.                 try{
  2747.                     if( rs != null )
  2748.                         rs.close();
  2749.                 } catch(Exception er) {
  2750.                     // close
  2751.                 }
  2752.                 try{
  2753.                     if( pstmt != null )
  2754.                         pstmt.close();
  2755.                 } catch(Exception er) {
  2756.                     // close
  2757.                 }
  2758.                 String errorMsg = "[ProfiloDiCollaborazione.asincrono_getBusteAsincronePerUlterioreInoltro] errore, queryString["+queryString+"]: "+e.getMessage();
  2759.                 this.log.error(errorMsg,e);
  2760.                 throw new  ProtocolException(errorMsg,e);
  2761.             }

  2762.             List<BustaNonRiscontrata> listaBustaNonRiscontrata = new ArrayList<BustaNonRiscontrata>();
  2763.             for (int i = 0; i < IDBuste.size(); i++) {
  2764.                 BustaNonRiscontrata bustaNonRiscontrata = new BustaNonRiscontrata();
  2765.                 bustaNonRiscontrata.setIdentificativo(IDBuste.get(i));
  2766.                 PreparedStatement pstmtReadProfilo = null;
  2767.                 ResultSet rsReadProfilo = null;
  2768.                 try{
  2769.                    
  2770.                     if(Configurazione.getSqlQueryObjectType()==null){
  2771.                         StringBuilder query = new StringBuilder();
  2772.                         query.append("SELECT PROFILO_DI_COLLABORAZIONE FROM ");
  2773.                         query.append(Costanti.REPOSITORY);
  2774.                         query.append(" WHERE ID_MESSAGGIO=? AND TIPO=? ");
  2775.                         queryString = query.toString();
  2776.                     }
  2777.                     else{
  2778.                         ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  2779.                         sqlQueryObject.addSelectField("PROFILO_DI_COLLABORAZIONE");
  2780.                         sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  2781.                         sqlQueryObject.addWhereCondition("ID_MESSAGGIO=?");
  2782.                         sqlQueryObject.addWhereCondition("TIPO=?");
  2783.                         sqlQueryObject.setANDLogicOperator(true);
  2784.                         queryString = sqlQueryObject.createSQLQuery();
  2785.                     }
  2786.                    
  2787.                     pstmtReadProfilo = connectionDB.prepareStatement(queryString);
  2788.                     pstmtReadProfilo.setString(1,bustaNonRiscontrata.getIdentificativo());  
  2789.                     pstmtReadProfilo.setString(2,Costanti.OUTBOX);
  2790.                     rsReadProfilo = pstmtReadProfilo.executeQuery();    
  2791.                    
  2792.                     if(rsReadProfilo.next())
  2793.                         bustaNonRiscontrata.setProfiloCollaborazione(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.toProfiloDiCollaborazione(rsReadProfilo.getString("PROFILO_DI_COLLABORAZIONE")));
  2794.                    
  2795.                     listaBustaNonRiscontrata.add(bustaNonRiscontrata);
  2796.                    
  2797.                 } catch(Exception e) {
  2798.                     String errorMsg = "[ProfiloDiCollaborazione.asincrono_getBusteAsincronePerUlterioreInoltro] errore, queryString["+queryString+"]: "+e.getMessage();
  2799.                     this.log.error(errorMsg,e);
  2800.                     throw new  ProtocolException(errorMsg,e);
  2801.                 }
  2802.                 finally{
  2803.                     try{
  2804.                         if( rsReadProfilo != null )
  2805.                             rsReadProfilo.close();
  2806.                     } catch(Exception er) {
  2807.                         // close
  2808.                     }
  2809.                     try{
  2810.                         if( pstmtReadProfilo != null )
  2811.                             pstmtReadProfilo.close();
  2812.                     } catch(Exception er) {
  2813.                         // close
  2814.                     }
  2815.                 }
  2816.             }
  2817.            
  2818.             return listaBustaNonRiscontrata;
  2819.         }else if (this.state instanceof StatelessMessage){
  2820.             throw new ProtocolException("Metodo non invocabile in modalita stateless");
  2821.         }else{
  2822.             throw new ProtocolException("Metodo invocato con IState non valido");
  2823.         }
  2824.     }



  2825.     /**
  2826.      * Indicazione se la busta e' una ricevuta asincrona di una richiesta
  2827.      *
  2828.      * @param riferimentoMessaggio Riferimento Messaggio della ricevuta
  2829.      */
  2830.     public boolean asincrono_isRicevutaRichiesta(String riferimentoMessaggio)throws ProtocolException{
  2831.         return asincrono_isRicevuta(riferimentoMessaggio,true);
  2832.     }

  2833.     /**
  2834.      * Indicazione se la busta e' una ricevuta asincrona di una richiestaStato/Risposta
  2835.      *
  2836.      * @param riferimentoMessaggio Riferimento Messaggio della ricevuta
  2837.      */
  2838.     public boolean asincrono_isRicevutaRisposta(String riferimentoMessaggio)throws ProtocolException{
  2839.         return asincrono_isRicevuta(riferimentoMessaggio,false);
  2840.     }


  2841.     /**
  2842.      * Indicazione se la busta e' una ricevuta asincrona
  2843.      *
  2844.      * @param riferimentoMessaggio Riferimento Messaggio della ricevuta
  2845.      * @param isRicevutaRichiesta Se il check deve controllare che sia una ricevuta di una richiesta
  2846.      */
  2847.     private boolean asincrono_isRicevuta(String riferimentoMessaggio,boolean isRicevutaRichiesta)throws ProtocolException{
  2848.         StateMessage state = (StateMessage)this.state;
  2849.         Connection connectionDB = state.getConnectionDB();
  2850.         PreparedStatement pstmt = null;
  2851.         ResultSet rs = null;
  2852.         try{    

  2853.             StringBuilder query = new StringBuilder();
  2854.             query.append("SELECT ID_ASINCRONO FROM ");
  2855.             query.append(Costanti.PROFILO_ASINCRONO);
  2856.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=? AND RICEVUTA_ASINCRONA=0");

  2857.             pstmt = connectionDB.prepareStatement(query.toString());
  2858.             pstmt.setString(1,riferimentoMessaggio);
  2859.             pstmt.setString(2,Costanti.OUTBOX);
  2860.             rs = pstmt.executeQuery();      
  2861.             if(rs == null) {
  2862.                 throw new ProtocolException("RS Null?");            
  2863.             }
  2864.             boolean value = false;
  2865.             if(rs.next()){
  2866.                 if(riferimentoMessaggio.equals(rs.getString("ID_ASINCRONO"))){
  2867.                     value = isRicevutaRichiesta;
  2868.                 }else{
  2869.                     value = !isRicevutaRichiesta;
  2870.                 }
  2871.             }

  2872.             rs.close();
  2873.             pstmt.close();

  2874.             return value;

  2875.         } catch(Exception e) {
  2876.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, isRicevutaAsincrono "+riferimentoMessaggio+": "+e.getMessage();    
  2877.             this.log.error(errorMsg,e);
  2878.             try{
  2879.                 if( rs != null )
  2880.                     rs.close();
  2881.             } catch(Exception er) {
  2882.                 // Eccezione SQL.
  2883.             }
  2884.             try{
  2885.                 if( pstmt != null )
  2886.                     pstmt.close();
  2887.             } catch(Exception er) {
  2888.                 // Eccezione SQL.
  2889.             }
  2890.             throw new ProtocolException(errorMsg,e);
  2891.         }
  2892.     }

  2893.     /**
  2894.      * Valida una ricevuta asincrona, identificato dall'identificativo della busta.
  2895.      * In caso di validazione della ricevuta, l'entry nella tabella PROFILO Asincrono
  2896.      * viene aggiornata con RICEVUTA_ASINCRONA=1 se IS_RICHIESTA=1, altrimenti viene eliminata
  2897.      *
  2898.      * @param ricevuta busta da validare.
  2899.      * @deprecated utilizzare la versione non serializable
  2900.      *
  2901.      */
  2902.     @Deprecated
  2903.     public void asincrono_valdazioneRicevuta_serializable(Busta ricevuta) throws ProtocolException{
  2904.         asincrono_validazioneRicevuta_serializable(ricevuta,60l,100);
  2905.     }


  2906.     /**
  2907.      * Valida una ricevuta asincrona, identificato dall'identificativo della busta.
  2908.      * In caso di validazione della ricevuta, l'entry nella tabella PROFILO Asincrono
  2909.      * viene aggiornata con RICEVUTA_ASINCRONA=1 se IS_RICHIESTA=1, altrimenti viene eliminata
  2910.      *
  2911.      * @param ricevuta busta da validare.
  2912.      * @param attesaAttiva AttesaAttiva per la gestione del livello di serializable
  2913.      * @param checkInterval Intervallo di check per la gestione  del livello di serializable
  2914.      * @deprecated utilizzare la versione non serializable
  2915.      */
  2916.     @Deprecated
  2917.     public void asincrono_validazioneRicevuta_serializable(Busta ricevuta,long attesaAttiva,int checkInterval) throws ProtocolException{
  2918.         if(this.state instanceof StatefulMessage) {
  2919.             StatefulMessage stateful = (StatefulMessage)this.state;
  2920.             Connection connectionDB = stateful.getConnectionDB();
  2921.             String idRicevuta = ricevuta.getRiferimentoMessaggio();

  2922.             /*
  2923.              * Viene realizzato con livello di isolamento SERIALIZABLE, per essere sicuri
  2924.              *  di leggere solo le indicazioni di richieste asincrone committate,
  2925.              * e comunque rispedira' anche le buste eliminate, ma non committate.
  2926.              */
  2927.             // setAutoCommit e livello Isolamento
  2928.             int oldTransactionIsolation = -1;
  2929.             try{
  2930.                 oldTransactionIsolation = connectionDB.getTransactionIsolation();
  2931.                 connectionDB.setAutoCommit(false);
  2932.                 JDBCUtilities.setTransactionIsolationSerializable(Configurazione.getSqlQueryObjectType(), connectionDB);
  2933.             } catch(Exception er) {
  2934.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, Errore durante la validazioneRicevutaAsincrona "+idRicevuta+"(setIsolation): "+er.getMessage();    
  2935.                 this.log.error(errorMsg,er);
  2936.                 throw new ProtocolException(errorMsg,er);
  2937.             }


  2938.             boolean validazioneRicevutaOK = false;

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

  2940.             while(validazioneRicevutaOK==false && DateManager.getTimeMillis() < scadenzaWhile){

  2941.                 PreparedStatement pstmtValidazione = null;
  2942.                 PreparedStatement pstmt = null;
  2943.                 ResultSet rs = null;
  2944.                 try{

  2945.                     // Check flusso asincrono: richiesta/ricevuta  o  risposta(richiestaStato)/ricevuta(Risposta)
  2946.                     StringBuilder query = new StringBuilder();
  2947.                     query.append("SELECT IS_RICHIESTA,RICEVUTA_ASINCRONA,ID_ASINCRONO FROM ");
  2948.                     query.append(Costanti.PROFILO_ASINCRONO);
  2949.                     query.append(" WHERE ID_MESSAGGIO=? AND TIPO=? FOR UPDATE");
  2950.                     pstmt = connectionDB.prepareStatement(query.toString());
  2951.                     pstmt.setString(1,idRicevuta);
  2952.                     pstmt.setString(2,Costanti.OUTBOX);

  2953.                     // Esecuzione comando SQL
  2954.                     rs = pstmt.executeQuery();      
  2955.                     if(rs == null) {
  2956.                         throw new ProtocolException("RS Null?");    
  2957.                     }
  2958.                     boolean isRichiesta = false;
  2959.                     boolean validaRicevuta = false;
  2960.                     String idCollaborazione = null;
  2961.                     if(rs.next()==false){
  2962.                         rs.close();
  2963.                         pstmt.close();
  2964.                         return; // l'entry non e' presente...
  2965.                     }else{
  2966.                         if(rs.getInt("IS_RICHIESTA")==1)
  2967.                             isRichiesta = true;
  2968.                         if(rs.getInt("RICEVUTA_ASINCRONA")==0)
  2969.                             validaRicevuta = true;
  2970.                         idCollaborazione = rs.getString("ID_ASINCRONO");
  2971.                     }
  2972.                     rs.close();
  2973.                     pstmt.close();

  2974.                     if(validaRicevuta==false){
  2975.                         String tipoRicevuta = "ricevuta di una richiesta asincrona";
  2976.                         if(isRichiesta == false)
  2977.                             tipoRicevuta = "ricevuta di una risposta asincrona";
  2978.                         this.log.warn("Validazione "+tipoRicevuta+" non effettuata, poiche' inutile: ricevuta precedentemente gia' analizzata.");
  2979.                     }

  2980.                     if(isRichiesta){
  2981.                         // Aggiorno valore ricevuta
  2982.                         query.delete(0,query.length());
  2983.                         query.append("UPDATE ");
  2984.                         query.append(Costanti.PROFILO_ASINCRONO);
  2985.                         if(ricevuta.getServizioCorrelato()!=null && org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_ASIMMETRICO.equals(ricevuta.getProfiloDiCollaborazione())){
  2986.                             query.append(" SET RICEVUTA_ASINCRONA=1,IS_RICHIESTA=0,TIPO_SERVIZIO_CORRELATO=?,SERVIZIO_CORRELATO=?,VERSIONE_SERVIZIO_CORRELATO=? WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  2987.                             pstmtValidazione = connectionDB.prepareStatement(query.toString());
  2988.                             pstmtValidazione.setString(1,ricevuta.getTipoServizioCorrelato());
  2989.                             pstmtValidazione.setString(2,ricevuta.getServizioCorrelato());
  2990.                             if(ricevuta.getVersioneServizioCorrelato()!=null){
  2991.                                 pstmt.setInt(3,ricevuta.getVersioneServizioCorrelato());
  2992.                             }
  2993.                             else{
  2994.                                 pstmt.setNull(3, java.sql.Types.INTEGER);
  2995.                             }
  2996.                             pstmtValidazione.setString(4,idRicevuta);
  2997.                             pstmtValidazione.setString(5,Costanti.OUTBOX);
  2998.                         }else{
  2999.                             query.append(" SET RICEVUTA_ASINCRONA=1,IS_RICHIESTA=0 WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  3000.                             pstmtValidazione = connectionDB.prepareStatement(query.toString());
  3001.                             pstmtValidazione.setString(1,idRicevuta);
  3002.                             pstmtValidazione.setString(2,Costanti.OUTBOX);
  3003.                         }
  3004.                         pstmtValidazione.execute();
  3005.                         pstmtValidazione.close();
  3006.                     }else{

  3007.                         // la busta ricevuta/inviata, come richiesta, necessaria per l'invio della risposta, non serve piu'.
  3008.                         if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO.equals(ricevuta.getProfiloDiCollaborazione())){
  3009.                             this.eliminaBustaRicevuta(idCollaborazione);
  3010.                         }else{
  3011.                             this.eliminaBustaInviata(idCollaborazione);
  3012.                         }  

  3013.                         // Elimino entry solo per il profilo asincrono simmetrico
  3014.                         if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO.equals(ricevuta.getProfiloDiCollaborazione())){
  3015.                             query.delete(0,query.capacity());
  3016.                             query.append("DELETE FROM ");
  3017.                             query.append(Costanti.PROFILO_ASINCRONO);
  3018.                             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  3019.                             pstmtValidazione = connectionDB.prepareStatement(query.toString());
  3020.                             pstmtValidazione.setString(1,idRicevuta);
  3021.                             pstmtValidazione.setString(2,Costanti.OUTBOX);
  3022.                             pstmtValidazione.execute();
  3023.                             pstmtValidazione.close();
  3024.                         }

  3025.                         // Eliminazione accesso_profilo per l'invio della busta di risposta/richiesta stato
  3026.                         this.eliminaBustaInviata(idRicevuta);

  3027.                         stateful.executePreparedStatement();
  3028.                     }

  3029.                     // Chiusura Transazione
  3030.                     connectionDB.commit();

  3031.                     // ID Costruito
  3032.                     validazioneRicevutaOK = true;

  3033.                 } catch(Throwable e) {
  3034.                     try{
  3035.                         if( rs != null  )
  3036.                             rs.close();
  3037.                     } catch(Exception er) {
  3038.                         // close
  3039.                     }
  3040.                     try{
  3041.                         if( pstmt != null  )
  3042.                             pstmt.close();
  3043.                     } catch(Exception er) {
  3044.                         // close
  3045.                     }
  3046.                     try{
  3047.                         if( pstmtValidazione != null  )
  3048.                             pstmtValidazione.close();
  3049.                     } catch(Exception er) {
  3050.                         // close
  3051.                     }
  3052.                     try{
  3053.                         connectionDB.rollback();
  3054.                     } catch(Exception er) {
  3055.                         // ignore
  3056.                     }
  3057.                 }

  3058.                 if(validazioneRicevutaOK == false){
  3059.                     // Per aiutare ad evitare conflitti
  3060.                     try{
  3061.                         Utilities.sleep(ProtocolRandomUtilities.getRandom().nextInt(checkInterval)); // random da 0ms a checkIntervalms
  3062.                     }catch(Exception eRandom){
  3063.                         // ignore
  3064.                     }
  3065.                 }
  3066.             }

  3067.             // Ripristino Transazione
  3068.             try{
  3069.                 connectionDB.setTransactionIsolation(oldTransactionIsolation);
  3070.                 connectionDB.setAutoCommit(true);
  3071.             } catch(Exception er) {
  3072.                 String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, Errore durante la validazioneRicevutaAsincrona "+idRicevuta+"(ripristinoIsolation): "+er.getMessage();      
  3073.                 this.log.error(errorMsg,er);
  3074.                 throw new ProtocolException(errorMsg,er);
  3075.             }
  3076.         }else{
  3077.             throw new ProtocolException("Metodo invocato con IState non valido");
  3078.         }
  3079.     }  

  3080.     /**
  3081.      * Valida una ricevuta asincrona, identificato dall'identificativo della busta.
  3082.      * In caso di validazione della ricevuta, l'entry nella tabella PROFILO Asincrono
  3083.      * viene aggiornata con RICEVUTA_ASINCRONA=1 se IS_RICHIESTA=1, altrimenti viene eliminata
  3084.      *
  3085.      * @param ricevuta busta da validare.
  3086.      *
  3087.      */
  3088.     public void asincrono_valdazioneRicevuta(Busta ricevuta) throws ProtocolException{
  3089.         StateMessage state = (StateMessage)this.state;
  3090.         Connection connectionDB = state.getConnectionDB();
  3091.         String idRicevuta = ricevuta.getRiferimentoMessaggio();

  3092.         PreparedStatement pstmtValidazione = null;
  3093.         PreparedStatement pstmt = null;
  3094.         ResultSet rs = null;
  3095.         try{

  3096.             // Check flusso asincrono: richiesta/ricevuta  o  risposta(richiestaStato)/ricevuta(Risposta)
  3097.             StringBuilder query = new StringBuilder();
  3098.             query.append("SELECT IS_RICHIESTA,RICEVUTA_ASINCRONA,ID_ASINCRONO FROM ");
  3099.             query.append(Costanti.PROFILO_ASINCRONO);
  3100.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  3101.             pstmt = connectionDB.prepareStatement(query.toString());
  3102.             pstmt.setString(1,idRicevuta);
  3103.             pstmt.setString(2,Costanti.OUTBOX);

  3104.             // Esecuzione comando SQL
  3105.             rs = pstmt.executeQuery();      
  3106.             if(rs == null) {
  3107.                 throw new ProtocolException("RS Null?");    
  3108.             }
  3109.             boolean isRichiesta = false;
  3110.             boolean validaRicevuta = false;
  3111.             String idCollaborazione = null;
  3112.             if(rs.next()==false){
  3113.                 rs.close();
  3114.                 pstmt.close();
  3115.                 return; // l'entry non e' presente...
  3116.             }else{
  3117.                 if(rs.getInt("IS_RICHIESTA")==1)
  3118.                     isRichiesta = true;
  3119.                 if(rs.getInt("RICEVUTA_ASINCRONA")==0)
  3120.                     validaRicevuta = true;
  3121.                 idCollaborazione = rs.getString("ID_ASINCRONO");
  3122.             }
  3123.             rs.close();
  3124.             pstmt.close();

  3125.             if(validaRicevuta==false){
  3126.                 String tipoRicevuta = "ricevuta di una richiesta asincrona";
  3127.                 if(isRichiesta == false)
  3128.                     tipoRicevuta = "ricevuta di una risposta asincrona";
  3129.                 this.log.warn("Validazione "+tipoRicevuta+" non effettuata, poiche' inutile: ricevuta precedentemente gia' analizzata.");
  3130.             }

  3131.             if(isRichiesta){
  3132.                 // Aggiorno valore ricevuta
  3133.                 query.delete(0,query.length());
  3134.                 query.append("UPDATE ");
  3135.                 query.append(Costanti.PROFILO_ASINCRONO);
  3136.                 if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_ASIMMETRICO.equals(ricevuta.getProfiloDiCollaborazione())){
  3137.                     String tipoServizioCorrelato = ricevuta.getTipoServizioCorrelato();
  3138.                     String servizioCorrelato = ricevuta.getServizioCorrelato();
  3139.                     Integer versioneServizioCorrelato = ricevuta.getVersioneServizioCorrelato();
  3140.                     if(servizioCorrelato==null || tipoServizioCorrelato==null || versioneServizioCorrelato==null){
  3141.                         IDSoggetto fruitore = new IDSoggetto(ricevuta.getTipoDestinatario(),ricevuta.getDestinatario());
  3142.                         IDServizio servizio = IDServizioFactory.getInstance().getIDServizioFromValues(ricevuta.getTipoServizio(),ricevuta.getServizio(),
  3143.                                 ricevuta.getTipoMittente(),ricevuta.getMittente(),
  3144.                                 ricevuta.getVersioneServizio());
  3145.                         servizio.setAzione(ricevuta.getAzione());
  3146.                         RisultatoValidazione validazione = RegistroServiziManager.getInstance(state).validaServizio(fruitore,servizio,null);
  3147.                         if( (validazione==null) || (validazione.getServizioRegistrato()==false))
  3148.                             throw new Exception("Servizio ["+servizio.toString()+"] non esiste nel registro dei servizi");
  3149.                         if( (validazione.getServizioCorrelato()==null) || (validazione.getTipoServizioCorrelato()==null) || (validazione.getVersioneServizioCorrelato()==null) )
  3150.                             throw new Exception("Servizio ["+servizio.toString()+"] non possiede un servizio correlato associato");
  3151.                         tipoServizioCorrelato = validazione.getTipoServizioCorrelato();
  3152.                         servizioCorrelato = validazione.getServizioCorrelato();
  3153.                         versioneServizioCorrelato = validazione.getVersioneServizioCorrelato();
  3154.                     }
  3155.                     query.append(" SET RICEVUTA_ASINCRONA=1,IS_RICHIESTA=0,TIPO_SERVIZIO_CORRELATO=?,SERVIZIO_CORRELATO=?,VERSIONE_SERVIZIO_CORRELATO=? WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  3156.                     pstmtValidazione = connectionDB.prepareStatement(query.toString());
  3157.                     pstmtValidazione.setString(1,tipoServizioCorrelato);
  3158.                     pstmtValidazione.setString(2,servizioCorrelato);
  3159.                     if(versioneServizioCorrelato!=null){
  3160.                         pstmtValidazione.setInt(3,versioneServizioCorrelato);
  3161.                     }
  3162.                     else{
  3163.                         pstmtValidazione.setNull(3, java.sql.Types.INTEGER);
  3164.                     }
  3165.                     pstmtValidazione.setString(4,idRicevuta);
  3166.                     pstmtValidazione.setString(5,Costanti.OUTBOX);
  3167.                 }
  3168.                 else{
  3169.                     query.append(" SET RICEVUTA_ASINCRONA=1,IS_RICHIESTA=0 WHERE  ID_MESSAGGIO = ? AND TIPO=?");
  3170.                     pstmtValidazione = connectionDB.prepareStatement(query.toString());
  3171.                     pstmtValidazione.setString(1,idRicevuta);
  3172.                     pstmtValidazione.setString(2,Costanti.OUTBOX);
  3173.                 }

  3174.                 //  Add PreparedStatement
  3175.                 state.getPreparedStatement().put("UPDATE validazioneRicevutaRichiestaAsincrona_"+idRicevuta,pstmtValidazione);

  3176.             }else{

  3177.                 // la busta ricevuta/inviata, come richiesta, necessaria per l'invio della risposta, non serve piu'.
  3178.                 if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO.equals(ricevuta.getProfiloDiCollaborazione())){
  3179.                     this.eliminaBustaRicevuta(idCollaborazione,true);
  3180.                 }else{
  3181.                     this.eliminaBustaInviata(idCollaborazione,true);
  3182.                 }  

  3183.                 // Elimino entry solo per il profilo asincrono simmetrico
  3184.                 if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO.equals(ricevuta.getProfiloDiCollaborazione())){
  3185.                     query.delete(0,query.capacity());
  3186.                     query.append("DELETE FROM ");
  3187.                     query.append(Costanti.PROFILO_ASINCRONO);
  3188.                     query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");
  3189.                     pstmtValidazione =  connectionDB.prepareStatement(query.toString());
  3190.                     pstmtValidazione.setString(1,idRicevuta);
  3191.                     pstmtValidazione.setString(2,Costanti.OUTBOX);

  3192.                     //  Add PreparedStatement
  3193.                     state.getPreparedStatement().put("UPDATE validazioneRicevutaRispostaAsincrona_"+idRicevuta,pstmtValidazione);
  3194.                 }

  3195.                 // Eliminazione accesso_profilo per l'invio della busta di risposta/richiesta stato
  3196.                 this.eliminaBustaInviata(idRicevuta,true);

  3197.             }

  3198.         } catch(Exception e) {
  3199.             try{
  3200.                 if( rs != null  )
  3201.                     rs.close();
  3202.             } catch(Exception er) {
  3203.                 // close
  3204.             }
  3205.             try{
  3206.                 if( pstmt != null  )
  3207.                     pstmt.close();
  3208.             } catch(Exception er) {
  3209.                 // close
  3210.             }
  3211.             try{
  3212.                 if( pstmtValidazione != null  )
  3213.                     pstmtValidazione.close();
  3214.             } catch(Exception er) {
  3215.                 // close
  3216.             }
  3217.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, Errore durante la validazioneRicevutaAsincrona "+idRicevuta+": "+e.getMessage();        
  3218.             this.log.error(errorMsg,e);
  3219.             throw new ProtocolException(errorMsg,e);
  3220.         }

  3221.     }


  3222.     /**
  3223.      * Ritorna lo stato di una gestione asincrona, true se e' legittimo gestire una richiesta-stato/Risposta, false altrimenti.
  3224.      *
  3225.      * @param busta busta da controllare
  3226.      * @return true se e' una risposta asincrona.
  3227.      *
  3228.      */
  3229.     public boolean asincrono_isRisposta(Busta busta) throws ProtocolException{
  3230.         StateMessage state = (StateMessage)this.state;
  3231.         Connection connectionDB = state.getConnectionDB();
  3232.         PreparedStatement pstmt = null;
  3233.         ResultSet rs = null;
  3234.         try{

  3235.             // NOTA:
  3236.             //   una busta asincrona RISPOSTA puo avere riferimentoMessaggio o collaborazione

  3237.             if(busta.getRiferimentoMessaggio()==null && busta.getCollaborazione()==null)
  3238.                 return false;

  3239.             StringBuilder query = new StringBuilder();
  3240.             query.append("SELECT * FROM ");
  3241.             query.append(Costanti.PROFILO_ASINCRONO);
  3242.             query.append(" WHERE ");
  3243.             if(busta.getRiferimentoMessaggio()!=null && busta.getCollaborazione()!=null){
  3244.                 query.append(" (ID_MESSAGGIO=? OR ID_MESSAGGIO=?) ");
  3245.             }else {
  3246.                 query.append(" ID_MESSAGGIO=? ");
  3247.             }
  3248.             query.append(" AND TIPO=?");

  3249.             String tipo = null;
  3250.             if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO.equals(busta.getProfiloDiCollaborazione())){
  3251.                 // asincrono simmetrico
  3252.                 tipo=Costanti.OUTBOX;
  3253.             }else{
  3254.                 // asincrono asimmetrico
  3255.                 tipo=Costanti.INBOX;
  3256.             }

  3257.             pstmt = connectionDB.prepareStatement(query.toString());
  3258.             if(busta.getRiferimentoMessaggio()!=null && busta.getCollaborazione()!=null){
  3259.                 pstmt.setString(1,busta.getRiferimentoMessaggio());
  3260.                 pstmt.setString(2,busta.getCollaborazione());
  3261.                 pstmt.setString(3,tipo);
  3262.             }else if(busta.getRiferimentoMessaggio()!=null){
  3263.                 pstmt.setString(1,busta.getRiferimentoMessaggio());
  3264.                 pstmt.setString(2,tipo);
  3265.             }else{
  3266.                 pstmt.setString(1,busta.getCollaborazione());
  3267.                 pstmt.setString(2,tipo);
  3268.             }

  3269.             rs = pstmt.executeQuery();  
  3270.             if(rs == null) {
  3271.                 throw new ProtocolException("RS Null?");            
  3272.             }
  3273.             boolean value = false;
  3274.             if(rs.next()){
  3275.                 if( (rs.getInt("IS_RICHIESTA")==0) &&
  3276.                         (rs.getInt("RICEVUTA_ASINCRONA")==1) &&
  3277.                         (rs.getString("TIPO_SERVIZIO_CORRELATO")!=null) &&
  3278.                         (rs.getString("TIPO_SERVIZIO_CORRELATO").equals(busta.getTipoServizio())) &&
  3279.                         (rs.getString("SERVIZIO_CORRELATO")!=null) &&
  3280.                         (rs.getString("SERVIZIO_CORRELATO").equals(busta.getServizio())) &&
  3281.                         (rs.getInt("VERSIONE_SERVIZIO_CORRELATO") == busta.getVersioneServizio().intValue())
  3282.                 )
  3283.                     value = true;
  3284.             }

  3285.             rs.close();
  3286.             pstmt.close();

  3287.             return value;

  3288.         }catch(Exception e){    
  3289.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, asincrono_isRisposta "+busta.getRiferimentoMessaggio()+": "+e.getMessage();
  3290.             this.log.error(errorMsg,e);
  3291.             try{
  3292.                 if( rs != null )
  3293.                     rs.close();
  3294.             } catch(Exception er) {
  3295.                 // Eccezione SQL.
  3296.             }
  3297.             try{
  3298.                 if( pstmt != null )
  3299.                     pstmt.close();
  3300.             } catch(Exception er) {
  3301.                 // Eccezione SQL.
  3302.             }
  3303.             throw new ProtocolException(errorMsg,e);
  3304.         }
  3305.     }

  3306.     /**
  3307.      * Ritorna l'indicazione se la gestione di una ricevuta applicativa e' abilitata o meno
  3308.      *
  3309.      * @param id ID per la gestione del profilo Asincrono
  3310.      * @return true se la ricevuta applicativa e' abilitato.
  3311.      *
  3312.      */
  3313.     public boolean asincrono_ricevutaApplicativaAbilitata(String id) throws ProtocolException{
  3314.         StateMessage state = (StateMessage)this.state;
  3315.         Connection connectionDB = state.getConnectionDB();
  3316.         PreparedStatement pstmt = null;
  3317.         ResultSet rs = null;
  3318.         try{
  3319.             StringBuilder query = new StringBuilder();
  3320.             query.append("SELECT * FROM ");
  3321.             query.append(Costanti.PROFILO_ASINCRONO);
  3322.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  3323.             pstmt = connectionDB.prepareStatement(query.toString());
  3324.             pstmt.setString(1,id);
  3325.             pstmt.setString(2,Costanti.OUTBOX);
  3326.             rs = pstmt.executeQuery();      
  3327.             if(rs == null) {
  3328.                 throw new ProtocolException("RS Null?");            
  3329.             }
  3330.             if(rs.next()){
  3331.                 if( rs.getInt("RICEVUTA_APPLICATIVA")==0 ){
  3332.                     rs.close();
  3333.                     pstmt.close();
  3334.                     return false;
  3335.                 }
  3336.                 else{
  3337.                     rs.close();
  3338.                     pstmt.close();
  3339.                     return true;
  3340.                 }
  3341.             }

  3342.             throw new Exception("?Valore non trovato nella tabella asincrona?");

  3343.         }catch(Exception e){    
  3344.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, asincrono_ricevutaApplicativaAbilitata "+id+": "+e.getMessage();
  3345.             this.log.error(errorMsg,e);
  3346.             try{
  3347.                 if( rs != null )
  3348.                     rs.close();
  3349.             } catch(Exception er) {
  3350.                 // Eccezione SQL.
  3351.             }
  3352.             try{
  3353.                 if( pstmt != null )
  3354.                     pstmt.close();
  3355.             } catch(Exception er) {
  3356.                 // Eccezione SQL.
  3357.             }
  3358.             throw new ProtocolException(errorMsg,e);
  3359.         }
  3360.     }

  3361.     /**
  3362.      * Ritorna l'indicazione se e' in corso la gestione di una richiesta asincrona
  3363.      *
  3364.      * @param id ID per la gestione del profilo Asincrono
  3365.      * @return true se la ricevuta applicativa e' abilitato.
  3366.      *
  3367.      */
  3368.     public boolean asincrono_spedizioneRichiestaInCorso(String id) throws ProtocolException{
  3369.         StateMessage state = (StateMessage)this.state;
  3370.         Connection connectionDB = state.getConnectionDB();
  3371.         PreparedStatement pstmt = null;
  3372.         ResultSet rs = null;
  3373.         try{
  3374.             StringBuilder query = new StringBuilder();
  3375.             query.append("SELECT IS_RICHIESTA,RICEVUTA_ASINCRONA FROM ");
  3376.             query.append(Costanti.PROFILO_ASINCRONO);
  3377.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  3378.             pstmt = connectionDB.prepareStatement(query.toString());
  3379.             pstmt.setString(1,id);
  3380.             pstmt.setString(2,Costanti.OUTBOX);
  3381.             rs = pstmt.executeQuery();      
  3382.             if(rs == null) {
  3383.                 throw new ProtocolException("RS Null?");            
  3384.             }
  3385.             if(rs.next()){
  3386.                 if( rs.getInt("IS_RICHIESTA")==1 &&
  3387.                         rs.getInt("RICEVUTA_ASINCRONA")==0  ){
  3388.                     rs.close();
  3389.                     pstmt.close();
  3390.                     return true;
  3391.                 }
  3392.                 else{
  3393.                     rs.close();
  3394.                     pstmt.close();
  3395.                     return false;
  3396.                 }
  3397.             }

  3398.             rs.close();
  3399.             pstmt.close();
  3400.             return false;

  3401.         }catch(Exception e){    
  3402.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, asincrono_spedizioneRichiestaInCorso "+id+": "+e.getMessage();
  3403.             this.log.error(errorMsg,e);
  3404.             try{
  3405.                 if( rs != null )
  3406.                     rs.close();
  3407.             } catch(Exception er) {
  3408.                 // Eccezione SQL.
  3409.             }
  3410.             try{
  3411.                 if( pstmt != null )
  3412.                     pstmt.close();
  3413.             } catch(Exception er) {
  3414.                 // Eccezione SQL.
  3415.             }
  3416.             throw new ProtocolException(errorMsg,e);
  3417.         }
  3418.     }

  3419.     /**
  3420.      * Ritorna l'indicazione se e' in corso la gestione di una risposta asincrona
  3421.      *
  3422.      * @param id ID per la gestione del profilo Asincrono
  3423.      * @return true se la ricevuta applicativa e' abilitato.
  3424.      *
  3425.      */
  3426.     public boolean asincrono_spedizioneRispostaInCorso(String id) throws ProtocolException{

  3427.         StateMessage state = (StateMessage)this.state;
  3428.         Connection connectionDB = state.getConnectionDB();
  3429.         PreparedStatement pstmt = null;
  3430.         ResultSet rs = null;
  3431.         try{
  3432.             StringBuilder query = new StringBuilder();
  3433.             query.append("SELECT IS_RICHIESTA,RICEVUTA_ASINCRONA FROM ");
  3434.             query.append(Costanti.PROFILO_ASINCRONO);
  3435.             query.append(" WHERE ID_MESSAGGIO=? AND TIPO=?");

  3436.             pstmt = connectionDB.prepareStatement(query.toString());
  3437.             pstmt.setString(1,id);
  3438.             pstmt.setString(2,Costanti.OUTBOX);
  3439.             rs = pstmt.executeQuery();      
  3440.             if(rs == null) {
  3441.                 throw new ProtocolException("RS Null?");            
  3442.             }
  3443.             if(rs.next()){
  3444.                 if( rs.getInt("IS_RICHIESTA")==0 &&
  3445.                         rs.getInt("RICEVUTA_ASINCRONA")==0  ){
  3446.                     rs.close();
  3447.                     pstmt.close();
  3448.                     return true;
  3449.                 }
  3450.                 else{
  3451.                     rs.close();
  3452.                     pstmt.close();
  3453.                     return false;
  3454.                 }
  3455.             }

  3456.             rs.close();
  3457.             pstmt.close();
  3458.             return false;

  3459.         }catch(Exception e){    
  3460.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, asincrono_spedizioneRispostaInCorso "+id+": "+e.getMessage();
  3461.             this.log.error(errorMsg,e);
  3462.             try{
  3463.                 if( rs != null )
  3464.                     rs.close();
  3465.             } catch(Exception er) {
  3466.                 // Eccezione SQL.
  3467.             }
  3468.             try{
  3469.                 if( pstmt != null )
  3470.                     pstmt.close();
  3471.             } catch(Exception er) {
  3472.                 // Eccezione SQL.
  3473.             }
  3474.             throw new ProtocolException(errorMsg,e);
  3475.         }
  3476.     }

  3477.     /**
  3478.      * Elimina i dati salvati per la gestione di un profilo asicrono.
  3479.      *
  3480.      * @param id Identificativo.
  3481.      * @param tipoBusta INBOX/OUTBOX
  3482.      *
  3483.      */
  3484.     public void asincrono_eliminaRegistrazione(String id,String tipoBusta, Date data) throws ProtocolException{
  3485.         StateMessage state = (StateMessage)this.state;
  3486.         Connection connectionDB = state.getConnectionDB();
  3487.         PreparedStatement pstmt = null;
  3488.         try{    
  3489.             StringBuilder query = new StringBuilder();
  3490.             query.append("DELETE FROM ");
  3491.             query.append(Costanti.PROFILO_ASINCRONO);
  3492.             query.append(" WHERE ID_MESSAGGIO = ? AND TIPO=?");
  3493.             if(data!=null) {
  3494.                 query.append(" AND ORA_REGISTRAZIONE<=?");
  3495.             }
  3496.             pstmt = connectionDB.prepareStatement(query.toString());
  3497.             pstmt.setString(1,id);
  3498.             pstmt.setString(2,tipoBusta);
  3499.             java.sql.Timestamp nowT = null;
  3500.             if(data!=null) {
  3501.                 nowT = new java.sql.Timestamp(data.getTime());
  3502.                 pstmt.setTimestamp(3,nowT);
  3503.             }
  3504.            
  3505.             //  Add PreparedStatement
  3506.             state.getPreparedStatement().put("DELETE delete_datiAsincroni"+id,pstmt);

  3507.         } catch(Exception e) {
  3508.             String errorMsg = "PROFILO_DI_COLLABORAZIONE_ASINCRONO, Errore durante l'asincrono_eliminaRegistrazione "+id+": "+e.getMessage();      
  3509.             this.log.error(errorMsg,e);
  3510.             try{
  3511.                 if( pstmt != null )
  3512.                     pstmt.close();
  3513.             } catch(Exception er) {
  3514.                 // Eccezione SQL.
  3515.             }
  3516.             throw new ProtocolException(errorMsg,e);
  3517.         }
  3518.     }

  3519. }