ConsegnaInOrdine.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 org.slf4j.Logger;
  25. import org.openspcoop2.protocol.engine.Configurazione;
  26. import org.openspcoop2.protocol.engine.constants.Costanti;
  27. import org.openspcoop2.protocol.sdk.Busta;
  28. import org.openspcoop2.protocol.sdk.Eccezione;
  29. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  30. import org.openspcoop2.protocol.sdk.ProtocolException;
  31. import org.openspcoop2.protocol.sdk.constants.ErroriCooperazione;
  32. import org.openspcoop2.protocol.sdk.state.IState;
  33. import org.openspcoop2.protocol.sdk.state.StateMessage;
  34. import org.openspcoop2.protocol.sdk.state.StatefulMessage;
  35. import org.openspcoop2.utils.LoggerWrapperFactory;
  36. import org.openspcoop2.utils.Utilities;
  37. import org.openspcoop2.utils.date.DateManager;
  38. import org.openspcoop2.utils.jdbc.JDBCUtilities;
  39. import org.openspcoop2.utils.sql.ISQLQueryObject;
  40. import org.openspcoop2.utils.sql.SQLObjectFactory;

  41. /**
  42.  * Sono inclusi i metodi per la gestione della consegna in ordine (sequenza).
  43.  *
  44.  *
  45.  * @author Poli Andrea (apoli@link.it)
  46.  * @author Tronci Fabio (tronci@link.it)
  47.  * @author $Author$
  48.  * @version $Rev$, $Date$
  49.  */

  50. public class ConsegnaInOrdine  {



  51.     /** Logger utilizzato per debug. */
  52.     private Logger log = null;

  53.     /** Se IState e' un'istanza di StatefulMessage possiede una Connessione SQL in autoCommit mode su cui effettuare query
  54.      *  Altrimenti, e' un'istanza di StatelessMessage e nn necessita di connessioni */
  55.     private IState state;
  56.    
  57.     private IProtocolFactory<?> protocolFactory;

  58.    

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

  60.     /**
  61.      * Costruttore.
  62.      *
  63.      * @param state Oggetto che rappresenta lo stato di una busta
  64.      *
  65.      */
  66.     public ConsegnaInOrdine(IState state,IProtocolFactory<?> protocolFactory){
  67.         this(state,Configurazione.getLibraryLog(),protocolFactory);
  68.     }
  69.     /**
  70.      * Costruttore.
  71.      *
  72.      * @param state Oggetto che rappresenta lo stato di una busta
  73.      *
  74.      */
  75.     public ConsegnaInOrdine(IState state, Logger alog,IProtocolFactory<?> protocolFactory){
  76.         this.state = state;
  77.         if(alog!=null){
  78.             this.log = alog;
  79.         }else{
  80.             this.log = LoggerWrapperFactory.getLogger(ConsegnaInOrdine.class.getName());
  81.         }
  82.         this.protocolFactory = protocolFactory;
  83.     }
  84.    
  85.     /**
  86.      * Aggiorna lo stato della Busta
  87.      * Utilizzato per reimpostare la connessione ??
  88.      *
  89.      */
  90.     public void updateState(IState state){
  91.         this.state = state;
  92.     }

  93.     private static final String NOT_USED = ""; // azione null


  94.     /**
  95.      * Ritorna l'identificativo di una collaborazione identificata da mittente/destinatario/servizio/azione.
  96.      * In caso la collaborazione non esiste, viene creata.
  97.      *  
  98.      * @param busta Busta su cui impostare la sequenza
  99.      *
  100.      */
  101.     public void setNextSequenza_daInviare(Busta busta)throws ProtocolException{

  102.         if(this.state instanceof StateMessage) {
  103.            
  104.             StateMessage stateful = (StateMessage)this.state;
  105.             Connection connectionDB = stateful.getConnectionDB();

  106.             PreparedStatement pstmt = null;
  107.             ResultSet rs = null;
  108.             PreparedStatement pstmtInsert = null;
  109.             String idCollaborazione = null;
  110.             long sequenza = -1;
  111.             try{    

  112.                 StringBuilder query = new StringBuilder();
  113.                 query.append("SELECT ID_COLLABORAZIONE,PROSSIMA_SEQUENZA FROM ");
  114.                 query.append(Costanti.SEQUENZA_DA_INVIARE);
  115.                 query.append(" WHERE MITTENTE=? AND TIPO_MITTENTE=? AND DESTINATARIO=? AND TIPO_DESTINATARIO=? AND SERVIZIO=? AND TIPO_SERVIZIO=? AND AZIONE=?");
  116.                 pstmt = connectionDB.prepareStatement(query.toString());
  117.                 pstmt.setString(1,busta.getMittente());
  118.                 pstmt.setString(2,busta.getTipoMittente());
  119.                 pstmt.setString(3,busta.getDestinatario());
  120.                 pstmt.setString(4,busta.getTipoDestinatario());
  121.                 pstmt.setString(5,busta.getServizio());
  122.                 pstmt.setString(6,busta.getTipoServizio());
  123.                 if(busta.getAzione()!=null)
  124.                     pstmt.setString(7,busta.getAzione());
  125.                 else
  126.                     pstmt.setString(7,NOT_USED);

  127.                 // Esecuzione comando SQL
  128.                 rs = pstmt.executeQuery();      
  129.                 if(rs == null) {
  130.                     pstmt.close();
  131.                     throw new ProtocolException("RS NULL?");
  132.                 }      
  133.                 if(rs.next()){
  134.                     // Collaborazione preesistente
  135.                     idCollaborazione = rs.getString("ID_COLLABORAZIONE");
  136.                     sequenza=rs.getLong("PROSSIMA_SEQUENZA");

  137.                     // devo aggiornare il next sequence

  138.                     long next_sequenza = sequenza + 1;
  139.                     if(next_sequenza > Costanti.MAX_VALUE_SEQUENZA_COUNTER){
  140.                         next_sequenza = 1;
  141.                     }

  142.                     rs.close();
  143.                     pstmt.close();

  144.                     // aggiornamento sequenza
  145.                     StringBuilder queryInsert = new StringBuilder();
  146.                     queryInsert.append("UPDATE ");
  147.                     queryInsert.append(Costanti.SEQUENZA_DA_INVIARE);
  148.                     queryInsert.append(" SET PROSSIMA_SEQUENZA = ? WHERE MITTENTE=? AND TIPO_MITTENTE=? AND DESTINATARIO=? AND TIPO_DESTINATARIO=? AND SERVIZIO=? AND TIPO_SERVIZIO=? AND AZIONE=?");
  149.                     pstmtInsert = connectionDB.prepareStatement(queryInsert.toString());
  150.                     int index = 1;
  151.                     pstmtInsert.setLong(index++,next_sequenza);
  152.                     pstmtInsert.setString(index++,busta.getMittente());
  153.                     pstmtInsert.setString(index++,busta.getTipoMittente());
  154.                     pstmtInsert.setString(index++,busta.getDestinatario());
  155.                     pstmtInsert.setString(index++,busta.getTipoDestinatario());
  156.                     pstmtInsert.setString(index++,busta.getServizio());
  157.                     pstmtInsert.setString(index++,busta.getTipoServizio());
  158.                     if(busta.getAzione()!=null){
  159.                         pstmtInsert.setString(index++,busta.getAzione());
  160.                     }else{
  161.                         pstmtInsert.setString(index++,NOT_USED);
  162.                     }

  163.                     stateful.getPreparedStatement().put("UPDATE setNextSequenza_daInviare"+busta.getCollaborazione(), pstmtInsert);


  164.                 }else{

  165.                     // Nuova collaborazione
  166.                     idCollaborazione = busta.getID();
  167.                     sequenza=1;

  168.                     rs.close();
  169.                     pstmt.close();              

  170.                     StringBuilder queryInsert = new StringBuilder();
  171.                     queryInsert.append("INSERT INTO  ");
  172.                     queryInsert.append(Costanti.SEQUENZA_DA_INVIARE);
  173.                     queryInsert.append(" VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? )");
  174.                     pstmtInsert = connectionDB.prepareStatement(queryInsert.toString());
  175.                     int index = 1;
  176.                     pstmtInsert.setString(index++,busta.getMittente());
  177.                     pstmtInsert.setString(index++,busta.getTipoMittente());
  178.                     pstmtInsert.setString(index++,busta.getDestinatario());
  179.                     pstmtInsert.setString(index++,busta.getTipoDestinatario());
  180.                     pstmtInsert.setString(index++,busta.getServizio());
  181.                     pstmtInsert.setString(index++,busta.getTipoServizio());
  182.                     if(busta.getAzione()!=null){
  183.                         pstmtInsert.setString(index++,busta.getAzione());
  184.                     }else{
  185.                         pstmtInsert.setString(index++,NOT_USED);
  186.                     }
  187.                     pstmtInsert.setLong(index++,2); // next sequence is 2
  188.                     pstmtInsert.setString(index++,busta.getID()); // idCollaborazione is idRequest
  189.                     pstmtInsert.setTimestamp(index++, DateManager.getTimestamp());

  190.                     stateful.getPreparedStatement().put("INSERT setNextSequenza_daInviare"+busta.getCollaborazione(), pstmtInsert);


  191.                 }

  192.                 // impostazione busta
  193.                 busta.setSequenza(sequenza);
  194.                 busta.setCollaborazione(idCollaborazione);


  195.             } catch(Exception e) {
  196.                 String errorMsg = "ConsegnaInOrdine, Errore durante la setNextSequenza_daInviare: "+e.getMessage();    
  197.                 try{
  198.                     if( rs != null )
  199.                         rs.close();
  200.                 } catch(Exception er) {
  201.                     // close
  202.                 }
  203.                 try{
  204.                     if( pstmt != null )
  205.                         pstmt.close();
  206.                 } catch(Exception er) {
  207.                     // close
  208.                 }
  209.                 try{
  210.                     if( pstmtInsert != null )
  211.                         pstmtInsert.close();
  212.                 } catch(Exception er) {
  213.                     // close
  214.                 }
  215.                 this.log.error(errorMsg,e);
  216.                 throw new ProtocolException(errorMsg,e);
  217.             }

  218.         }else{
  219.             throw new ProtocolException("Metodo invocato con IState non valido");
  220.         }
  221.     }










  222.     /**
  223.      * Ritorna true se la busta contiene una sequenza/collaborazione valida
  224.      *  
  225.      * @param busta Busta su cui effettuare la validazione
  226.      * @return una eccezione se la busta contiene una sequenza/collaborazione non valida
  227.      *
  228.      */
  229.     public Eccezione validazioneDatiConsegnaInOrdine(Busta busta, IProtocolFactory<?> protocolFactory)throws ProtocolException{
  230.         if(this.state instanceof StateMessage) {
  231.            
  232.             StateMessage stateful = (StateMessage)this.state;
  233.             Connection connectionDB = stateful.getConnectionDB();
  234.            
  235.             // Check stateless
  236.             boolean connessioneValida = false;
  237.             try{
  238.                 if(stateful instanceof StatefulMessage)
  239.                     connessioneValida = true;
  240.                 else
  241.                     connessioneValida = ( (connectionDB!=null) && (!connectionDB.isClosed()) );
  242.             }catch(Exception e){
  243.                 // ignore
  244.             }
  245.                    
  246.             if(connessioneValida && busta.getSequenza()!=-1 && busta.getCollaborazione()!=null){

  247.                 PreparedStatement pstmt = null;
  248.                 ResultSet rs = null;
  249.                 try{    

  250.                     if(busta.getID().equals(busta.getCollaborazione())){
  251.                         // busta Capostipite
  252.                         if(busta.getSequenza()!=1){
  253.                             this.log.debug("Riscontrato numero di sequenza diverso da 1, in una busta capostipite di una sequenza");
  254.                             return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_FUORI_SEQUENZA.getErroreCooperazione(), protocolFactory);
  255.                         }
  256.                     }
  257.                     else{
  258.                         // busta non capostipite
  259.                         StringBuilder query = new StringBuilder();
  260.                         query.append("SELECT * FROM ");
  261.                         query.append(Costanti.SEQUENZA_DA_RICEVERE);
  262.                         query.append(" WHERE ID_COLLABORAZIONE=?");
  263.                         pstmt = connectionDB.prepareStatement(query.toString());
  264.                         pstmt.setString(1,busta.getCollaborazione());

  265.                         //  Esecuzione comando SQL
  266.                         rs = pstmt.executeQuery();      
  267.                         if(rs == null) {
  268.                             throw new ProtocolException("RS NULL?");
  269.                         }  
  270.                         if(rs.next()){
  271.                             String tipoMittente = rs.getString("TIPO_MITTENTE");
  272.                             String mittente = rs.getString("MITTENTE");
  273.                             String tipoDestinatario = rs.getString("TIPO_DESTINATARIO");
  274.                             String destinatario = rs.getString("DESTINATARIO");
  275.                             String tipoServizio = rs.getString("TIPO_SERVIZIO");
  276.                             String servizio = rs.getString("SERVIZIO");
  277.                             String azione = rs.getString("AZIONE");

  278.                             //  Check di coerenza
  279.                             if( tipoMittente.equals(busta.getTipoMittente())==false){
  280.                                 this.log.debug("Il tipo di mittente non rispetta quello atteso nella gestione della collaborazione con consegna in ordine.");
  281.                                 return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_TIPO_MITTENTE_NON_VALIDO.getErroreCooperazione(), protocolFactory);
  282.                             }
  283.                             if( mittente.equals(busta.getMittente())==false){
  284.                                 this.log.debug("Il mittente non rispetta quello atteso nella gestione della collaborazione con consegna in ordine.");
  285.                                 return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_MITTENTE_NON_VALIDO.getErroreCooperazione(), protocolFactory);
  286.                             }
  287.                             if( tipoDestinatario.equals(busta.getTipoDestinatario())==false){
  288.                                 this.log.debug("Il tipo di destinatario non rispetta quello atteso nella gestione della collaborazione con consegna in ordine.");
  289.                                 return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_TIPO_DESTINATARIO_NON_VALIDO.getErroreCooperazione(), protocolFactory);
  290.                             }
  291.                             if( destinatario.equals(busta.getDestinatario())==false){
  292.                                 this.log.debug("Il destinatario non rispetta quello atteso nella gestione della collaborazione con consegna in ordine.");
  293.                                 return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_DESTINATARIO_NON_VALIDO.getErroreCooperazione(),protocolFactory);
  294.                             }
  295.                             if( tipoServizio.equals(busta.getTipoServizio())==false){
  296.                                 this.log.debug("Il tipo di servizio non rispetta quello atteso nella gestione della collaborazione con consegna in ordine.");
  297.                                 return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_TIPO_SERVIZIO_NON_VALIDO.getErroreCooperazione(), protocolFactory);
  298.                             }
  299.                             if( servizio.equals(busta.getServizio())==false){
  300.                                 this.log.debug("Il servizio non rispetta quello atteso nella gestione della collaborazione con consegna in ordine.");
  301.                                 return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_SERVIZIO_NON_VALIDO.getErroreCooperazione(), protocolFactory);
  302.                             }
  303.                             if( (azione==null && busta.getAzione()!=null) ||
  304.                                     (azione!=null && azione.equals(busta.getAzione())==false) ){
  305.                                 this.log.debug("L'azione non rispetta quello attesa nella gestione della collaborazione con consegna in ordine.");
  306.                                 return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_AZIONE_NON_VALIDA.getErroreCooperazione(), protocolFactory);
  307.                             }
  308.                         }else{
  309.                             this.log.debug("Busta non capostipite che richiede funzionalità di consegna in ordine presenta una collaborazione non registrata per le funzioni di consegna in ordine");
  310.                             return Eccezione.getEccezioneValidazione(ErroriCooperazione.CONSEGNA_IN_ORDINE_COLLABORAZIONE_IN_BUSTA_NON_CAPOSTIPITE_SCONOSCIUTA.getErroreCooperazione(), protocolFactory);
  311.                         }

  312.                     }

  313.                 } catch(Exception e) {
  314.                     this.log.error("ERROR validazioneDatiConsegnaInOrdine ["+e.getMessage()+"]",e);
  315.                     throw new ProtocolException("ERROR validazioneDatiConsegnaInOrdine ["+e.getMessage()+"]",e);
  316.                 }
  317.                 finally {
  318.                     try{
  319.                         if( rs != null )
  320.                             rs.close();
  321.                     } catch(Exception er) {
  322.                         // close
  323.                     }
  324.                     try{
  325.                         if( pstmt != null )
  326.                             pstmt.close();
  327.                     } catch(Exception er) {
  328.                         // close
  329.                     }
  330.                 }

  331.             }

  332.             return null;
  333.         }else{
  334.             throw new ProtocolException("Metodo invocato con IState non valido");
  335.         }
  336.     }
  337.    
  338.    
  339.    
  340.    
  341.     /**
  342.      * Ritorna true se la consegna deve essere effettuata, false altrimenti
  343.      *  
  344.      * @param busta Busta su cui gestire la sequenza
  345.      * @return true se la consegna deve essere effettuata, false altrimenti
  346.      *
  347.      */
  348.     public boolean isConsegnaInOrdine(Busta busta)throws ProtocolException{
  349.         return isConsegnaInOrdine(busta, 60l, 100);
  350.     }
  351.     /**
  352.      * Ritorna true se la consegna deve essere effettuata, false altrimenti
  353.      *  
  354.      * @param busta Busta su cui gestire la sequenza
  355.      * @param attesaAttiva AttesaAttiva per la gestione del livello di serializable
  356.      * @param checkInterval Intervallo di check per la gestione  del livello di serializable
  357.      * @return true se la consegna deve essere effettuata, false altrimenti
  358.      *
  359.      */
  360.     private long sequenzaAttesa = -1;
  361.     public long getSequenzaAttesa() {
  362.         return this.sequenzaAttesa;
  363.     }
  364.     public boolean isConsegnaInOrdine(Busta busta, long attesaAttiva, int checkInterval) throws ProtocolException{

  365.         if(this.state instanceof StateMessage) {
  366.            
  367.             StateMessage stateMsg = (StateMessage)this.state;
  368.             Connection connectionDB = stateMsg.getConnectionDB();

  369.             //controllo che non abbia gia' gestito un numero di sequenza per la busta
  370.             RepositoryBuste repository = new RepositoryBuste(stateMsg, this.log, true, this.protocolFactory);
  371.             long sequenzaGestita = repository.getSequenzaFromInBox(busta.getID());
  372.             if(sequenzaGestita == -2){
  373.                 return true; // posso consegnare, sicuramente l'ho gia' consegnata prima.
  374.             }


  375.             /*
  376.         Viene realizzato con livello di isolamento SERIALIZABLE, per essere sicuri
  377.         di creare sequenza crescenti.
  378.              */
  379.             // setAutoCommit e livello Isolamento
  380.             int oldTransactionIsolation = -1;
  381.             try{
  382.                 oldTransactionIsolation = connectionDB.getTransactionIsolation();
  383.                 connectionDB.setAutoCommit(false);
  384.                 JDBCUtilities.setTransactionIsolationSerializable(Configurazione.getSqlQueryObjectType(), connectionDB);
  385.             } catch(Exception er) {
  386.                 String errorMsg = "ConsegnaInOrdine, errore durante isConsegnaInOrdine(setIsolation): "+er.getMessage();        
  387.                 this.log.error(errorMsg,er);
  388.                 throw new ProtocolException(errorMsg,er);
  389.             }


  390.             boolean nextSequenceOK = false;
  391.             boolean bustaInOrdine = false;

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

  393.             while(nextSequenceOK==false && DateManager.getTimeMillis() < scadenzaWhile){

  394.                 PreparedStatement pstmt = null;
  395.                 ResultSet rs = null;
  396.                 try{    

  397.                     if(busta.getID().equals(busta.getCollaborazione())){
  398.                         // busta Capostipite

  399.                         bustaInOrdine = true;

  400.                     }else{
  401.                         // busta da controllare

  402.                         StringBuilder query = new StringBuilder();
  403.                         if(Configurazione.getSqlQueryObjectType()!=null){
  404.                             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  405.                             sqlQueryObject.addSelectField("SEQUENZA_ATTESA");
  406.                             sqlQueryObject.addFromTable(Costanti.SEQUENZA_DA_RICEVERE);
  407.                             sqlQueryObject.addWhereCondition("ID_COLLABORAZIONE=?");
  408.                             sqlQueryObject.setANDLogicOperator(true);
  409.                             sqlQueryObject.setSelectForUpdate(true);
  410.                             query.append(sqlQueryObject.createSQLQuery());
  411.                         }
  412.                         else{
  413.                             query.append("SELECT SEQUENZA_ATTESA FROM ");
  414.                             query.append(Costanti.SEQUENZA_DA_RICEVERE);
  415.                             query.append(" WHERE ID_COLLABORAZIONE=? FOR UPDATE");
  416.                         }
  417.                         pstmt =  connectionDB.prepareStatement(query.toString());
  418.                         pstmt.setString(1,busta.getCollaborazione());

  419.                         //  Esecuzione comando SQL
  420.                         rs = pstmt.executeQuery();      
  421.                         if(rs == null) {
  422.                             pstmt.close();
  423.                             throw new ProtocolException("RS NULL?");
  424.                         }  
  425.                         if(rs.next()==false){
  426.                             throw new Exception("Informazioni su consegna in ordine non trovate, durante il check di una busta non capostipite");
  427.                         }

  428.                         this.sequenzaAttesa = rs.getLong("SEQUENZA_ATTESA");
  429.                         rs.close();
  430.                         pstmt.close();

  431.                         // se non e' la sequenza attesa, vado in congelamento
  432.                         if(this.sequenzaAttesa!=busta.getSequenza()){
  433.                             bustaInOrdine = false;
  434.                         }else{
  435.                             bustaInOrdine = true;
  436.                         }
  437.                     }

  438.                     // Chiusura Transazione
  439.                     connectionDB.commit();

  440.                     // ID Costruito
  441.                     nextSequenceOK = true;

  442.                 } catch(Exception e) {
  443.                     this.log.error("ERROR isConsegnaInOrdine ["+e.getMessage()+"]");
  444.                     try{
  445.                         if( rs != null )
  446.                             rs.close();
  447.                     } catch(Exception er) {
  448.                         // close
  449.                     }
  450.                     try{
  451.                         if( pstmt != null )
  452.                             pstmt.close();
  453.                     } catch(Exception er) {
  454.                         // close
  455.                     }
  456.                     try{
  457.                         connectionDB.rollback();
  458.                     } catch(Exception er) {
  459.                         // ignore
  460.                     }
  461.                 }

  462.                 if(nextSequenceOK == false){
  463.                     // Per aiutare ad evitare conflitti
  464.                     try{
  465.                         Utilities.sleep(ProtocolRandomUtilities.getRandom().nextInt(checkInterval)); // random da 0ms a checkIntervalms
  466.                     }catch(Exception eRandom){
  467.                         // ignore
  468.                     }
  469.                 }
  470.             }

  471.             // Ripristino Transazione
  472.             try{
  473.                 connectionDB.setTransactionIsolation(oldTransactionIsolation);
  474.                 connectionDB.setAutoCommit(true);
  475.             } catch(Exception er) {
  476.                 String errorMsg = "ConsegnaInOrdine, Errore durante la isConsegnaInOrdine(ripristinoIsolation): "+er.getMessage();      
  477.                 this.log.error(errorMsg,er);
  478.                 throw new ProtocolException(errorMsg,er);
  479.             }


  480.             if(nextSequenceOK==false){
  481.                 throw new ProtocolException("Controllo sequenza per gestione funzionalita' di consegna in ordine non riuscita");
  482.             }

  483.             return bustaInOrdine;
  484.         }else{
  485.             throw new ProtocolException("Metodo invocato con IState non valido");
  486.         }
  487.     }
  488.    
  489.    
  490.    
  491.    





  492.     /**
  493.      * Aggiorna la sequenza
  494.      *
  495.      * @param busta Busta su cui gestire la sequenza
  496.      *
  497.      */
  498.     public void setNextSequenza_daRicevere(Busta busta)throws ProtocolException{
  499.         if(this.state instanceof StateMessage) {
  500.            
  501.             StateMessage stateful = (StateMessage)this.state;
  502.             Connection connectionDB = stateful.getConnectionDB();
  503.             // controllo che non abbia gia' gestito il numero di sequenza per la busta
  504.             RepositoryBuste repository = new RepositoryBuste(stateful, this.log, true, this.protocolFactory);
  505.             long sequenzaGestita = repository.getSequenzaFromInBox(busta.getID());
  506.             if(sequenzaGestita == -2){
  507.                 return; // gia gestita
  508.             }

  509.             PreparedStatement pstmtInsert = null;
  510.             try{    

  511.                 if(busta.getID().equals(busta.getCollaborazione())){
  512.                     // busta Capostipite

  513.                     StringBuilder queryInsert = new StringBuilder();
  514.                     queryInsert.append("INSERT INTO  ");
  515.                     queryInsert.append(Costanti.SEQUENZA_DA_RICEVERE);
  516.                     queryInsert.append(" VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? )");
  517.                     pstmtInsert =  connectionDB.prepareStatement(queryInsert.toString());
  518.                     int index = 1;
  519.                     pstmtInsert.setString(index++,busta.getCollaborazione());
  520.                     pstmtInsert.setLong(index++,(busta.getSequenza()+1)); //prossima sequenza attesa
  521.                     pstmtInsert.setString(index++,busta.getMittente());
  522.                     pstmtInsert.setString(index++,busta.getTipoMittente());
  523.                     pstmtInsert.setString(index++,busta.getDestinatario());
  524.                     pstmtInsert.setString(index++,busta.getTipoDestinatario());
  525.                     pstmtInsert.setString(index++,busta.getServizio());
  526.                     pstmtInsert.setString(index++,busta.getTipoServizio());
  527.                     pstmtInsert.setString(index++,busta.getAzione());
  528.                     pstmtInsert.setTimestamp(index++, DateManager.getTimestamp());

  529.                 }else{
  530.                     // aggiorno prossima sequenza attesa
  531.                     StringBuilder queryInsert = new StringBuilder();
  532.                     queryInsert.append("UPDATE ");
  533.                     queryInsert.append(Costanti.SEQUENZA_DA_RICEVERE);
  534.                     queryInsert.append(" SET SEQUENZA_ATTESA = ? WHERE ID_COLLABORAZIONE=? ");
  535.                     pstmtInsert =  connectionDB.prepareStatement(queryInsert.toString());

  536.                     long next_sequenza = busta.getSequenza() + 1;
  537.                     if(next_sequenza > Costanti.MAX_VALUE_SEQUENZA_COUNTER){
  538.                         next_sequenza = 1;
  539.                     }
  540.                     pstmtInsert.setLong(1,next_sequenza);
  541.                     pstmtInsert.setString(2,busta.getCollaborazione());
  542.                 }
  543.                 stateful.getPreparedStatement().put("INSERT setNextSequenza_daRicevere"+busta.getCollaborazione(), pstmtInsert);

  544.                 // imposto gestione della sequenza per la busta effettuata
  545.                 repository.aggiornaSequenzaIntoInBox(busta.getID(),-2);

  546.             } catch(Exception e) {
  547.                 String errorMsg = "ConsegnaInOrdine, Errore durante la setNextSequenza_daRicevere: "+e.getMessage();        
  548.                 try{
  549.                     if( pstmtInsert != null )
  550.                         pstmtInsert.close();
  551.                 } catch(Exception er) {
  552.                     // close
  553.                 }
  554.                 this.log.error(errorMsg,e);
  555.                 throw new ProtocolException(errorMsg,e);
  556.             }


  557.         }else{
  558.             throw new ProtocolException("Metodo invocato con IState non valido");
  559.         }
  560.     }

  561. }