GestoreCorrelazioneApplicativa.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */



  20. package org.openspcoop2.pdd.core;

  21. import java.io.ByteArrayOutputStream;
  22. import java.sql.Connection;
  23. import java.sql.PreparedStatement;
  24. import java.sql.ResultSet;
  25. import java.sql.SQLException;
  26. import java.util.ArrayList;
  27. import java.util.HashMap;
  28. import java.util.List;
  29. import java.util.Map;

  30. import javax.servlet.http.HttpServletRequest;
  31. import javax.xml.soap.SOAPEnvelope;

  32. import org.apache.commons.lang.StringUtils;
  33. import org.openspcoop2.core.commons.CoreException;
  34. import org.openspcoop2.core.config.CorrelazioneApplicativa;
  35. import org.openspcoop2.core.config.CorrelazioneApplicativaElemento;
  36. import org.openspcoop2.core.config.CorrelazioneApplicativaRisposta;
  37. import org.openspcoop2.core.config.CorrelazioneApplicativaRispostaElemento;
  38. import org.openspcoop2.core.config.PortaApplicativa;
  39. import org.openspcoop2.core.config.PortaDelegata;
  40. import org.openspcoop2.core.config.Proprieta;
  41. import org.openspcoop2.core.config.constants.CostantiConfigurazione;
  42. import org.openspcoop2.core.id.IDPortaApplicativa;
  43. import org.openspcoop2.core.id.IDPortaDelegata;
  44. import org.openspcoop2.core.id.IDServizio;
  45. import org.openspcoop2.core.id.IDSoggetto;
  46. import org.openspcoop2.core.registry.Resource;
  47. import org.openspcoop2.message.MessageUtils;
  48. import org.openspcoop2.message.OpenSPCoop2Message;
  49. import org.openspcoop2.message.constants.MessageType;
  50. import org.openspcoop2.message.constants.ServiceBinding;
  51. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  52. import org.openspcoop2.pdd.config.CostantiProprieta;
  53. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  54. import org.openspcoop2.pdd.core.behaviour.conditional.ConditionalUtils;
  55. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  56. import org.openspcoop2.pdd.core.dynamic.ErrorHandler;
  57. import org.openspcoop2.pdd.core.dynamic.MessageContent;
  58. import org.openspcoop2.pdd.core.dynamic.Template;
  59. import org.openspcoop2.pdd.core.integrazione.HeaderIntegrazione;
  60. import org.openspcoop2.pdd.core.transazioni.Transaction;
  61. import org.openspcoop2.pdd.services.connector.FormUrlEncodedHttpServletRequest;
  62. import org.openspcoop2.protocol.engine.Configurazione;
  63. import org.openspcoop2.protocol.sdk.Busta;
  64. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  65. import org.openspcoop2.protocol.sdk.ProtocolException;
  66. import org.openspcoop2.protocol.sdk.constants.CodiceErroreIntegrazione;
  67. import org.openspcoop2.protocol.sdk.constants.ErroreIntegrazione;
  68. import org.openspcoop2.protocol.sdk.constants.ErroriIntegrazione;
  69. import org.openspcoop2.protocol.sdk.state.IState;
  70. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  71. import org.openspcoop2.protocol.sdk.state.StateMessage;
  72. import org.openspcoop2.protocol.sdk.state.URLProtocolContext;
  73. import org.openspcoop2.utils.LoggerWrapperFactory;
  74. import org.openspcoop2.utils.MapKey;
  75. import org.openspcoop2.utils.date.DateManager;
  76. import org.openspcoop2.utils.regexp.RegularExpressionEngine;
  77. import org.openspcoop2.utils.sql.ISQLQueryObject;
  78. import org.openspcoop2.utils.sql.SQLObjectFactory;
  79. import org.openspcoop2.utils.sql.SQLQueryObjectException;
  80. import org.openspcoop2.utils.transport.http.HttpServletTransportRequestContext;
  81. import org.openspcoop2.utils.xml.AbstractXPathExpressionEngine;
  82. import org.openspcoop2.utils.xml2json.JsonXmlPathExpressionEngine;
  83. import org.slf4j.Logger;
  84. import org.w3c.dom.Comment;
  85. import org.w3c.dom.Element;
  86. import org.w3c.dom.Node;
  87. import org.w3c.dom.NodeList;
  88. import org.w3c.dom.Text;

  89. /**
  90.  * Gestione della correlazione applicativa con gli id
  91.  *
  92.  * @author Andrea Poli (apoli@link.it)
  93.  * @author $Author$
  94.  * @version $Rev$, $Date$
  95.  */

  96. public class GestoreCorrelazioneApplicativa {

  97.     /** Logger utilizzato per debug. */
  98.     protected Logger log = null;


  99.     /* ********  F I E L D S    S T A T I C    P U B L I C  ******** */
  100.     /** Tabella che mantiene i messaggi da consegnare ai servizi applicativi*/
  101.     public static final String CORRELAZIONE_APPLICATIVA  = "CORRELAZIONE_APPLICATIVA";

  102.     /* Colonne della tabella */
  103.     public static final String CORRELAZIONE_APPLICATIVA_COLUMN_ID_APPLICATIVO  = "ID_APPLICATIVO";
  104.     public static final String CORRELAZIONE_APPLICATIVA_COLUMN_ID_MESSAGGIO  = "ID_MESSAGGIO";
  105.    
  106.     /** Salvataggio in context */
  107.     public static final MapKey<String> CONTEXT_CORRELAZIONE_APPLICATIVA_RICHIESTA = org.openspcoop2.utils.Map.newMapKey("CONTEXT_CORRELAZIONE_APPLICATIVA_RICHIESTA");
  108.     public static final MapKey<String> CONTEXT_CORRELAZIONE_APPLICATIVA_RISPOSTA = org.openspcoop2.utils.Map.newMapKey("CONTEXT_CORRELAZIONE_APPLICATIVA_RISPOSTA");
  109.    
  110.     /** Se IState e' un'istanza di StatefulMessage possiede una Connessione SQL in autoCommit mode su cui effettuare query
  111.      *  Altrimenti, e' un'istanza di StatelessMessage e nn necessita di connessioni
  112.      * */
  113.     protected IState state;

  114.     /** id precedentemente associato alla correlazione */
  115.     private String idBustaCorrelato;
  116.     /** id Correlazione Applicativo */
  117.     private String idCorrelazione;
  118.     /** errore */
  119.     protected ErroreIntegrazione errore;
  120.     /** SoggettoFruitore */
  121.     protected IDSoggetto soggettoFruitore;
  122.     /** Servizio */
  123.     protected IDServizio idServizio;
  124.     /** Busta */
  125.     private Busta busta;
  126.     /** Resource REST */
  127.     private Resource restResource;
  128.     /** Servizio Applicativo */
  129.     protected String servizioApplicativo;
  130.     /** Scadenza correlazione applicativa */
  131.     //private long scadenzaDefault; e' stata aggiunta l'ora di registrazione per differenziare la gestione tra quelle con scadenza e quelle senza.
  132.     /** Indicazione se deve essere effettuato riuso id */
  133.     private boolean riusoIdentificativo = false;
  134.     /** ProtocolFactory */
  135.     protected IProtocolFactory<?> protocolFactory = null;
  136.     /** Transaction */
  137.     private Transaction transaction;
  138.     /** PddContext */
  139.     private PdDContext pddContext;
  140.     /** RequestInfo */
  141.     private RequestInfo requestInfo;
  142.    
  143.     /** Porta */
  144.     private PortaDelegata pd;
  145.     private PortaApplicativa pa;
  146.    
  147.     private int maxLengthCorrelazioneApplicativa = 255;
  148.     private int maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateRequest = -1;
  149.     private int maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateRequest = -1;
  150.     private int maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateResponse = -1;
  151.     private int maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateResponse = -1;
  152.    
  153.     private boolean isRichiestaIdentificativoEstrattoIsNullThrowError = false;
  154.     private boolean isRispostaIdentificativoEstrattoIsNullThrowError = false;
  155.    
  156.     private boolean isRichiestaIdentificativoEstrattoIsEmptyThrowError = false;
  157.     private boolean isRispostaIdentificativoEstrattoIsEmptyThrowError = false;
  158.    
  159.     private boolean isRichiestaRegolaCorrelazioneNonTrovataBlocca = false;
  160.     private boolean isRispostaRegolaCorrelazioneNonTrovataBlocca = false;

  161.     public boolean isRiusoIdentificativo() {
  162.         return this.riusoIdentificativo;
  163.     }
  164.    
  165.     /* ********  C O S T R U T T O R E  ******** */
  166.     /**
  167.      * Costruttore.
  168.      *
  169.      */
  170.     public GestoreCorrelazioneApplicativa(GestoreCorrelazioneApplicativaConfig config){    
  171.         this.state = config.getState();
  172.         if(config.getAlog()!=null){
  173.             this.log = config.getAlog();
  174.         }else{
  175.             this.log = LoggerWrapperFactory.getLogger(GestoreCorrelazioneApplicativa.class);
  176.         }
  177.         this.soggettoFruitore = config.getSoggettoFruitore();
  178.         this.idServizio = config.getIdServizio();
  179.         this.busta = config.getBusta();
  180.         this.servizioApplicativo = config.getServizioApplicativo();
  181.         this.protocolFactory = config.getProtocolFactory();
  182.         this.transaction = config.getTransaction();
  183.         this.pddContext = config.getPddContext();
  184.         if(this.pddContext!=null && this.pddContext.containsKey(org.openspcoop2.core.constants.Costanti.REQUEST_INFO)) {
  185.             this.requestInfo = (RequestInfo) this.pddContext.getObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO);
  186.         }
  187.        
  188.         List<Proprieta> proprieta = null;
  189.         if(config.getPd()!=null) {
  190.             this.pd = config.getPd();
  191.             proprieta = this.pd.getProprietaList();
  192.         }
  193.         else if(config.getPa()!=null) {
  194.             this.pa = config.getPa();
  195.             proprieta = this.pa.getProprietaList();
  196.         }
  197.        
  198.         OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  199.         this.maxLengthCorrelazioneApplicativa = op2Properties.getMaxLengthCorrelazioneApplicativa();
  200.         try {
  201.             if(CostantiProprieta.isCorrelazioneApplicativaRichiestaIdentificazioneFallitaBloccaTruncate(proprieta, op2Properties.isMaxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncate())) {
  202.                 this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateRequest = op2Properties.getMaxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncate();
  203.             }
  204.         }catch(Exception e) {
  205.             this.log.error("[isCorrelazioneApplicativaRichiesta_identificazioneFallita_blocca_truncate] failed: "+e.getMessage(),e);
  206.         }
  207.         try {
  208.             if(CostantiProprieta.isCorrelazioneApplicativaRispostaIdentificazioneFallitaBloccaTruncate(proprieta, op2Properties.isMaxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncate())) {
  209.                 this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateResponse = op2Properties.getMaxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncate();
  210.             }
  211.         }catch(Exception e) {
  212.             this.log.error("[isCorrelazioneApplicativaRisposta_identificazioneFallita_blocca_truncate] failed: "+e.getMessage(),e);
  213.         }
  214.         try {
  215.             if(CostantiProprieta.isCorrelazioneApplicativaRichiestaIdentificazioneFallitaAccettaTruncate(proprieta, op2Properties.isMaxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncate())) {
  216.                 this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateRequest = op2Properties.getMaxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncate();
  217.             }
  218.         }catch(Exception e) {
  219.             this.log.error("[isCorrelazioneApplicativaRichiesta_identificazioneFallita_accetta_truncate] failed: "+e.getMessage(),e);
  220.         }
  221.         try {
  222.             if(CostantiProprieta.isCorrelazioneApplicativaRispostaIdentificazioneFallitaAccettaTruncate(proprieta, op2Properties.isMaxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncate())) {
  223.                 this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateResponse = op2Properties.getMaxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncate();
  224.             }
  225.         }catch(Exception e) {
  226.             this.log.error("[isCorrelazioneApplicativaRisposta_identificazioneFallita_accetta_truncate] failed: "+e.getMessage(),e);
  227.         }
  228.    
  229.         try {
  230.             this.isRichiestaIdentificativoEstrattoIsNullThrowError = CostantiProprieta.isCorrelazioneApplicativaRichiestaIdentificativoEstrattoIsNullTerminaTransazioneConErrore(proprieta,
  231.                     op2Properties.isRepositoryCorrelazioneApplicativaRichiestaIdentificativoEstrattoIsNullConsideraErrore());
  232.         }catch(Exception e) {
  233.             this.log.error("[isCorrelazioneApplicativaRichiesta_identificativoEstrattoIsNull_terminaTransazioneConErrore] failed: "+e.getMessage(),e);
  234.         }
  235.         try {
  236.             this.isRispostaIdentificativoEstrattoIsNullThrowError = CostantiProprieta.isCorrelazioneApplicativaRispostaIdentificativoEstrattoIsNullTerminaTransazioneConErrore(proprieta,
  237.                     op2Properties.isRepositoryCorrelazioneApplicativaRispostaIdentificativoEstrattoIsNullConsideraErrore());
  238.         }catch(Exception e) {
  239.             this.log.error("[isCorrelazioneApplicativaRisposta_identificativoEstrattoIsNull_terminaTransazioneConErrore] failed: "+e.getMessage(),e);
  240.         }
  241.        
  242.         try {
  243.             this.isRichiestaIdentificativoEstrattoIsEmptyThrowError = CostantiProprieta.isCorrelazioneApplicativaRichiestaIdentificativoEstrattoIsEmptyTerminaTransazioneConErrore(proprieta,
  244.                     op2Properties.isRepositoryCorrelazioneApplicativaRichiestaIdentificativoEstrattoIsEmptyConsideraErrore());
  245.         }catch(Exception e) {
  246.             this.log.error("[isCorrelazioneApplicativaRichiesta_identificativoEstrattoIsEmpty_terminaTransazioneConErrore] failed: "+e.getMessage(),e);
  247.         }
  248.         try {
  249.             this.isRispostaIdentificativoEstrattoIsEmptyThrowError = CostantiProprieta.isCorrelazioneApplicativaRispostaIdentificativoEstrattoIsEmptyTerminaTransazioneConErrore(proprieta,
  250.                     op2Properties.isRepositoryCorrelazioneApplicativaRispostaIdentificativoEstrattoIsEmptyConsideraErrore());
  251.         }catch(Exception e) {
  252.             this.log.error("[isCorrelazioneApplicativaRisposta_identificativoEstrattoIsEmpty_terminaTransazioneConErrore] failed: "+e.getMessage(),e);
  253.         }
  254.        
  255.         try {
  256.             this.isRichiestaRegolaCorrelazioneNonTrovataBlocca = CostantiProprieta.isCorrelazioneApplicativaRichiestaRegolaNonTrovataTerminaTransazioneConErrore(proprieta,
  257.                     op2Properties.isRepositoryCorrelazioneApplicativaRichiestaRegolaCorrelazioneNonTrovataBlocca());
  258.         }catch(Exception e) {
  259.             this.log.error("[isCorrelazioneApplicativaRichiesta_regolaNonTrovata_terminaTransazioneConErrore] failed: "+e.getMessage(),e);
  260.         }
  261.         try {
  262.             this.isRispostaRegolaCorrelazioneNonTrovataBlocca = CostantiProprieta.isCorrelazioneApplicativaRispostaRegolaNonTrovataTerminaTransazioneConErrore(proprieta,
  263.                     op2Properties.isRepositoryCorrelazioneApplicativaRispostaRegolaCorrelazioneNonTrovataBlocca());
  264.         }catch(Exception e) {
  265.             this.log.error("[isCorrelazioneApplicativaRisposta_regolaNonTrovata_terminaTransazioneConErrore] failed: "+e.getMessage(),e);
  266.         }
  267.        
  268.     }

  269.     public void updateState(IState state){
  270.         this.state = state;
  271.     }
  272.    
  273.     private static final String ERRORE_IDENTIFICAZIONE_MESSAGE = "errore durante l'analisi dell'elementName: ";
  274.     private static final String ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO = "identificativo di correlazione applicativa non identificato nell'elemento [";
  275.     private static final String ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_URL_BASED = "] con modalita' di acquisizione urlBased (Pattern:";
  276.     private static final String ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_HEADER_BASED = "] con modalita' di acquisizione headerBased (Header:";
  277.     private static final String ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_CONTENT_BASED = "] con modalita' di acquisizione contentBased (Pattern:";
  278.     private static final String ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_TEMPLATE_BASED = "] con modalita' di acquisizione "; // usato per template, freemarkerTemplate e velocityTemplate
  279.     private static final String ERRORE_IDENTIFICAZIONE_PER_ELEMENTO = "identificativo di correlazione applicativa per l'elemento [";
  280.     private static final String ERRORE_IDENTIFICAZIONE_PER_ELEMENTO_MODALITA_INPUT_BASED = "con modalita' di acquisizione inputBased non presente tra le informazioni di integrazione";

  281.     private String buildErroreLunghezzaIdentificativo(String idCorrelazioneApplicativa) {
  282.         return "Identificativo di correlazione applicativa identificato possiede una lunghezza ("+idCorrelazioneApplicativa.length()+") superiore ai "+this.maxLengthCorrelazioneApplicativa+" caratteri consentiti";
  283.     }
  284.    
  285.     private void checkExtractedIdentifierIsNull(String idCorrelazioneApplicativa, boolean request) throws GestoreMessaggiException {
  286.         boolean identificativoEstrattoIsNullThrowError = request ? this.isRichiestaIdentificativoEstrattoIsNullThrowError : this.isRispostaIdentificativoEstrattoIsNullThrowError;
  287.         if(idCorrelazioneApplicativa==null && identificativoEstrattoIsNullThrowError) {
  288.             throw new GestoreMessaggiException("extracted identifier is null");
  289.         }
  290.     }
  291.     private void checkExtractedIdentifierIsEmpty(String idCorrelazioneApplicativa, boolean request) throws GestoreMessaggiException {
  292.         boolean identificativoEstrattoIsEmptyThrowError = request ? this.isRichiestaIdentificativoEstrattoIsEmptyThrowError : this.isRispostaIdentificativoEstrattoIsEmptyThrowError;
  293.         if(StringUtils.isEmpty(idCorrelazioneApplicativa) && identificativoEstrattoIsEmptyThrowError) {
  294.             throw new GestoreMessaggiException("extracted identifier is empty");
  295.         }
  296.     }
  297.    
  298.    
  299.    
  300.     /* *********** GESTIONE CORRELAZIONE APPLICATIVA (RICHIESTA) ************ */

  301.     public void verificaCorrelazione(CorrelazioneApplicativa correlazioneApplicativa,
  302.             URLProtocolContext urlProtocolContext,OpenSPCoop2Message message,HeaderIntegrazione headerIntegrazione,boolean readFirstHeaderIntegrazione) throws GestoreMessaggiException, ProtocolException{
  303.         if(this.transaction!=null) {
  304.             this.transaction.getTempiElaborazione().startCorrelazioneApplicativaRichiesta();
  305.         }
  306.         try {
  307.             this.verificaCorrelazioneEngine(correlazioneApplicativa, urlProtocolContext, message, headerIntegrazione, readFirstHeaderIntegrazione);
  308.         }
  309.         finally {
  310.             if(this.transaction!=null) {
  311.                 this.transaction.getTempiElaborazione().endCorrelazioneApplicativaRichiesta();
  312.             }
  313.         }
  314.     }
  315.     public boolean verificaCorrelazioneIdentificativoRichiesta() throws GestoreMessaggiException{
  316.         try {
  317.             return this.verificaCorrelazioneIdentificativoRichiestaEngine();
  318.         }
  319.         finally {
  320.             if(this.transaction!=null) {
  321.                 this.transaction.getTempiElaborazione().endCorrelazioneApplicativaRichiesta(); // sovrascrivo precedente data
  322.             }
  323.         }
  324.     }
  325.     private void verificaCorrelazioneEngine(CorrelazioneApplicativa correlazioneApplicativa,
  326.             URLProtocolContext urlProtocolContext,OpenSPCoop2Message message,HeaderIntegrazione headerIntegrazione,boolean readFirstHeaderIntegrazione) throws GestoreMessaggiException, ProtocolException{

  327.         if(correlazioneApplicativa==null){
  328.             this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  329.                     getErrore416_CorrelazioneApplicativaRichiesta("dati per l'identificazione dell'id di correlazione non presenti");
  330.             throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  331.         }

  332.         if(message==null) {
  333.             this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  334.                     getErrore416_CorrelazioneApplicativaRichiesta("messaggio non presente");
  335.             throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  336.         }
  337.        
  338.         Element element = null;
  339.         String elementJson = null;
  340.         try{
  341.             String idTransazione = null;
  342.             if(this.pddContext!=null) {
  343.                 idTransazione = (String)this.pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  344.             }
  345.             boolean bufferMessageReadOnly =  OpenSPCoop2Properties.getInstance().isReadByPathBufferEnabled();
  346.             boolean checkSoapBodyEmpty = false; // devo poter fare xpath anche su soapBody empty
  347.             element = MessageUtils.getContentElement(message, checkSoapBodyEmpty, bufferMessageReadOnly, idTransazione);
  348.             elementJson = MessageUtils.getContentString(message, bufferMessageReadOnly, idTransazione);
  349.         }catch(Exception e){
  350.             throw new GestoreMessaggiException(e.getMessage(),e);
  351.         }
  352.        
  353.         /** Fase di identificazione dell'id di correlazione */
  354.        
  355.         boolean checkElementoInTransito = false;
  356.         if(correlazioneApplicativa.sizeElementoList()>1){
  357.             checkElementoInTransito = true;
  358.         }
  359.         else{
  360.             if(correlazioneApplicativa.sizeElementoList()>0){
  361.                 CorrelazioneApplicativaElemento elemento = correlazioneApplicativa.getElemento(0);
  362.                 if( (elemento.getNome()!=null) && !"".equals(elemento.getNome()) ){
  363.                     checkElementoInTransito = true;
  364.                 }
  365.             }
  366.         }
  367.         List<Node> nList = null;
  368.         if(checkElementoInTransito){
  369.             try{
  370.                 if(ServiceBinding.SOAP.equals(message.getServiceBinding())){
  371.                     SOAPEnvelope envelope = (SOAPEnvelope) element;
  372.                     if(envelope==null){
  373.                         throw new CoreException("Envelope non presente nel messaggio Soap");
  374.                     }
  375.                     if(envelope.getBody()==null || !envelope.getBody().hasChildNodes()){
  376.                         throw new CoreException("Body applicativo non presente nel messaggio Soap");
  377.                     }
  378.                     NodeList nListSoapBody = envelope.getBody().getChildNodes();
  379.                     if(nListSoapBody==null || nListSoapBody.getLength()==0){
  380.                         throw new CoreException("Elementi del Body non presenti?");
  381.                     }
  382.                     nList = new ArrayList<>();
  383.                     for (int elem=0; elem<nListSoapBody.getLength(); elem++){
  384.                         Node nodeInEsame =  nListSoapBody.item(elem);
  385.                         if(nodeInEsame instanceof Text || nodeInEsame instanceof Comment){
  386.                             continue;
  387.                         }
  388.                         nList.add(nodeInEsame);
  389.                     }
  390.                 }
  391.                 else{
  392.                     if(MessageType.XML.equals(message.getMessageType()) ||
  393.                             MessageType.MIME_MULTIPART.equals(message.getMessageType()) // viene prelevato il primo xml trovato
  394.                             ){
  395.                         /** Nei GET il messaggio e' vuoto
  396.                         if(element==null){
  397.                             throw new Exception("Contenuto non presente nel messaggio");
  398.                         }*/
  399.                         if(element!=null){
  400.                             nList = new ArrayList<>();
  401.                             nList.add(element);
  402.                         }
  403.                     }
  404.                     else{
  405.                         checkElementoInTransito = false;
  406.                     }
  407.                 }
  408.             }catch(Exception e){
  409.                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  410.                         getErrore416_CorrelazioneApplicativaRichiesta(ERRORE_IDENTIFICAZIONE_MESSAGE+e.getMessage());
  411.                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  412.             }
  413.         }

  414.         // XPathExpressionEngine
  415.         AbstractXPathExpressionEngine xPathEngine = new org.openspcoop2.message.xml.XPathExpressionEngine(message.getFactory());
  416.        
  417.         /** Gestioni correlazioni, in modo da avere lo '*' in fondo */
  418.         java.util.List<CorrelazioneApplicativaElemento> c = new java.util.ArrayList<>();
  419.         int posizioneElementoQualsiasi = -1;
  420.         for(int i=0; i<correlazioneApplicativa.sizeElementoList(); i++){
  421.             CorrelazioneApplicativaElemento elemento = correlazioneApplicativa.getElemento(i);
  422.             if( (elemento.getNome()==null) || "".equals(elemento.getNome()) ){
  423.                 if(posizioneElementoQualsiasi!=-1){
  424.                     this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  425.                             getErrore416_CorrelazioneApplicativaRichiesta("errore durante l'analisi dell'elementName: piu' di un elemento '*' non puo' essere definito");
  426.                     throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  427.                 }else{
  428.                     posizioneElementoQualsiasi = i;
  429.                 }
  430.             }else{
  431.                 c.add(elemento);
  432.             }
  433.         }
  434.         if(posizioneElementoQualsiasi>=0){
  435.             // deve essere analizzato per ultimo
  436.             c.add(correlazioneApplicativa.getElemento(posizioneElementoQualsiasi));
  437.         }
  438.        

  439.         /** Fase di identificazione dell'id di correlazione */
  440.         boolean findCorrelazione = false;
  441.         boolean correlazioneNonRiuscitaDaAccettare = false;
  442.         String idCorrelazioneApplicativa = null;
  443.        
  444.         // Calcolo posizione ultimo nodo "buono"
  445.         int posizioneUltimoNodo = -1;
  446.         if(checkElementoInTransito && nList!=null){
  447.             for (int elem=0; elem<nList.size(); elem++){
  448.                 Node nodeInEsame =  nList.get(elem);
  449.                 if(nodeInEsame instanceof Text || nodeInEsame instanceof Comment){
  450.                     continue;
  451.                 }
  452.                 posizioneUltimoNodo = elem;
  453.             }
  454.         }
  455.         else{
  456.             posizioneUltimoNodo = 0;
  457.         }
  458.        
  459.         // Calcolo nomi
  460.         List<String> nomiPresentiBody = new ArrayList<>();
  461.         if(checkElementoInTransito && nList!=null){
  462.             for (int elem=0; elem<nList.size(); elem++){
  463.                 String elementName = null;
  464.                 Node nodeInEsame =  nList.get(elem);
  465.                 if( (!(nodeInEsame instanceof Text)) && (!(nodeInEsame instanceof Comment)) ){
  466.                     try{
  467.                         elementName = nodeInEsame.getLocalName();
  468.                     }catch(Exception e){
  469.                         this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  470.                                 getErrore416_CorrelazioneApplicativaRichiesta(ERRORE_IDENTIFICAZIONE_MESSAGE+e.getMessage());
  471.                         throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  472.                     }
  473.                     if(elementName==null){
  474.                         continue;
  475.                     }
  476.                     nomiPresentiBody.add(elementName);
  477.                 }
  478.             }
  479.         }
  480.         else{
  481.             nomiPresentiBody.add("PresenteSoloRegola*");
  482.         }
  483.        
  484.         for (int elem=0; elem<nomiPresentiBody.size(); elem++){

  485.             String elementName = nomiPresentiBody.get(elem);
  486.            
  487.             if(findCorrelazione)
  488.                 break;
  489.            
  490.             for(int i=0; i<c.size(); i++){
  491.                
  492.                 CorrelazioneApplicativaElemento elemento = c.get(i);
  493.                                
  494.                 boolean bloccaIdentificazioneNonRiuscita = true;
  495.                 if(CostantiConfigurazione.ACCETTA.equals(elemento.getIdentificazioneFallita()))
  496.                     bloccaIdentificazioneNonRiuscita = false;
  497.                
  498.                 // Il nome dell'elemento di una correlazione applicativa puo' essere:
  499.                 // non definito: significa per qualsiasi richiesta
  500.                 // nome: il nome può rappresentare:
  501.                 // - nome dell'identificativo dell'azione
  502.                 // - nome dell'elemento radice dell'xml
  503.                 // xpath o json expression: per identificare il nome dell'elemento radice XML
  504.                 boolean matchNodePerCorrelazioneApplicativa = false;
  505.                 String nomeElemento = null;
  506.                 if( (elemento.getNome()==null) || "".equals(elemento.getNome()) ){
  507.                     matchNodePerCorrelazioneApplicativa = true;
  508.                     nomeElemento = "*";
  509.                    
  510.                     // Devo applicare lo '*' solo se ho prima guardato tutti i nodi radice e sono ad esaminare l'ultimo nodo radice.
  511.                     // L'ordine delle correlazioni mi garantira' che lo '*' sara' esaminato per ultimo
  512.                     if( elem!=posizioneUltimoNodo )
  513.                         continue;
  514.                    
  515.                 }
  516.                 else if(
  517.                             (
  518.                                 // Ricerco per match sull'azione
  519.                                 this.idServizio!=null && this.idServizio.getAzione()!=null &&
  520.                                 this.idServizio.getAzione().equals(elemento.getNome())
  521.                             )
  522.                         ||
  523.                             (
  524.                                 // Ricerco per match sul localName dell'elemento (se XML)
  525.                                 elementName.equals(elemento.getNome())  
  526.                             )
  527.                         ) {
  528.                    
  529.                     matchNodePerCorrelazioneApplicativa = true;
  530.                     nomeElemento = elemento.getNome();
  531.                 }
  532.                 else{
  533.                    
  534.                     // se siamo in REST provo a cercare per metodo e path
  535.                     boolean isResourceRest = false;
  536.                     if(ServiceBinding.REST.equals(message.getServiceBinding())){
  537.                         isResourceRest = isMatchResourceRest(elemento.getNome());
  538.                     }
  539.                     if(isResourceRest) {
  540.                         matchNodePerCorrelazioneApplicativa = true;
  541.                         nomeElemento = elemento.getNome();
  542.                     }
  543.                     else {
  544.                        
  545.                         // Ricerco elemento con una espressione
  546.                         try{
  547.                             if(element==null && elementJson==null){
  548.                                 throw new CoreException("Contenuto non disponibile su cui effettuare un match");
  549.                             }
  550.                             if(element!=null) {
  551.                                 nomeElemento = AbstractXPathExpressionEngine.extractAndConvertResultAsString(element, xPathEngine, elemento.getNome(), this.log);
  552.                             }
  553.                             else {
  554.                                 nomeElemento = JsonXmlPathExpressionEngine.extractAndConvertResultAsString(elementJson, elemento.getNome(), this.log);
  555.                             }
  556.                             if(nomeElemento!=null) {
  557.                                 matchNodePerCorrelazioneApplicativa = true;
  558.                             }
  559.                         }catch(Exception e){
  560.                             String error = "Calcolo (contentBased) non riuscito ["+elementName+"] ["+elemento.getNome()+"]: "+e.getMessage();
  561.                             this.log.info(error);
  562.                         }
  563.                         // Ricerco tramuite espressione regolare sulla url
  564.                         if(!matchNodePerCorrelazioneApplicativa) {
  565.                             try{
  566.                                 nomeElemento = RegularExpressionEngine.getStringMatchPattern(urlProtocolContext.getUrlInvocazione_formBased(),
  567.                                         elemento.getNome());
  568.                                 if(nomeElemento!=null) {
  569.                                     matchNodePerCorrelazioneApplicativa = true;
  570.                                 }
  571.                             }catch(Exception e){
  572.                                 String error = "Calcolo (urlBased) non riuscito ["+elementName+"] ["+elemento.getNome()+"]: "+e.getMessage();
  573.                                 this.log.info(error);
  574.                             }
  575.                         }
  576.                     }
  577.                 }


  578.                 // Correlazione
  579.                 this.riusoIdentificativo = CostantiConfigurazione.ABILITATO.equals(elemento.getRiusoIdentificativo());
  580.                 if( matchNodePerCorrelazioneApplicativa ){

  581.                     // Puo' darsi che questo elemento identificato non abbia bisogna effettuare correlazione applicativa
  582.                     if(CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_DISABILITATO.equals(elemento.getIdentificazione())){
  583.                         correlazioneNonRiuscitaDaAccettare = true;
  584.                         findCorrelazione = true;
  585.                         break;
  586.                     }
  587.                    
  588.                    
  589.                     if(readFirstHeaderIntegrazione &&
  590.                         headerIntegrazione.getIdApplicativo()!=null){
  591.                         idCorrelazioneApplicativa = headerIntegrazione.getIdApplicativo();
  592.                         findCorrelazione = true;
  593.                         break;
  594.                     }

  595.                     if( CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_URL_BASED.equals(elemento.getIdentificazione())){
  596.                         try{
  597.                             List<String> l = RegularExpressionEngine.getAllStringMatchPattern(urlProtocolContext.getUrlInvocazione_formBased(),
  598.                                     elemento.getPattern());
  599.                             if(l!=null && !l.isEmpty()) {
  600.                                 StringBuilder bf = new StringBuilder();
  601.                                 for (String id : l) {
  602.                                     if(bf.length()>0) {
  603.                                         bf.append(" ");
  604.                                     }
  605.                                     bf.append(id);
  606.                                 }
  607.                                 idCorrelazioneApplicativa =  bf.toString();
  608.                             }
  609.                             checkExtractedIdentifierIsNull(idCorrelazioneApplicativa, true);
  610.                             checkExtractedIdentifierIsEmpty(idCorrelazioneApplicativa, true);
  611.                         }catch(Exception e){
  612.                             if(bloccaIdentificazioneNonRiuscita){
  613.                                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  614.                                         getErrore416_CorrelazioneApplicativaRichiesta(ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO+nomeElemento+ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_URL_BASED+elemento.getPattern()+"): "+e.getMessage());
  615.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  616.                             }else{
  617.                                 correlazioneNonRiuscitaDaAccettare = true;
  618.                             }
  619.                         }
  620.                     }
  621.                     else if( CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_HEADER_BASED.equals(elemento.getIdentificazione())){
  622.                         try{
  623.                             if(message==null ||
  624.                                     message.getTransportRequestContext()==null ||
  625.                                     message.getTransportRequestContext().getHeaders()==null ||
  626.                                     message.getTransportRequestContext().getHeaders().isEmpty()) {
  627.                                 throw new CoreException ("headers not found");
  628.                             }
  629.                             idCorrelazioneApplicativa = message.getTransportRequestContext().getHeaderFirstValue(elemento.getPattern());
  630.                             if(idCorrelazioneApplicativa==null) {
  631.                                 // NOTA: deve essere considerato come vi fosse un errore nel pattern
  632.                                 throw new GestoreMessaggiException("header not found");
  633.                             }
  634.                             checkExtractedIdentifierIsEmpty(idCorrelazioneApplicativa, true);
  635.                         }catch(Exception e){
  636.                             if(bloccaIdentificazioneNonRiuscita){
  637.                                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  638.                                         getErrore416_CorrelazioneApplicativaRichiesta(ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO+nomeElemento+ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_HEADER_BASED+elemento.getPattern()+"): "+e.getMessage());
  639.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  640.                             }else{
  641.                                 correlazioneNonRiuscitaDaAccettare = true;
  642.                             }
  643.                         }
  644.                     }
  645.                     else if( CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_INPUT_BASED.equals(elemento.getIdentificazione()) ){
  646.                         idCorrelazioneApplicativa = headerIntegrazione.getIdApplicativo();
  647.                         if(
  648.                                 (idCorrelazioneApplicativa==null) // NOTA: deve essere considerato come vi fosse un errore
  649.                                 ||
  650.                                 (StringUtils.isEmpty(idCorrelazioneApplicativa) && this.isRichiestaIdentificativoEstrattoIsEmptyThrowError)
  651.                             ){
  652.                             if(bloccaIdentificazioneNonRiuscita){
  653.                                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  654.                                         getErrore416_CorrelazioneApplicativaRichiesta(ERRORE_IDENTIFICAZIONE_PER_ELEMENTO+nomeElemento+"] " +
  655.                                                 ERRORE_IDENTIFICAZIONE_PER_ELEMENTO_MODALITA_INPUT_BASED);
  656.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  657.                             }else{
  658.                                 correlazioneNonRiuscitaDaAccettare = true;
  659.                             }
  660.                         }
  661.                     }
  662.                     else if( CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_TEMPLATE.equals(elemento.getIdentificazione())
  663.                             ||
  664.                             CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_FREEMARKER_TEMPLATE.equals(elemento.getIdentificazione())
  665.                             ||
  666.                             CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_VELOCITY_TEMPLATE.equals(elemento.getIdentificazione())){
  667.                         try{
  668.                            
  669.                             if(elemento.getPattern()==null || StringUtils.isEmpty(elemento.getPattern())) {
  670.                                 throw new CoreException ("Template non disponibile");
  671.                             }
  672.                            
  673.                             Map<String, List<String>> pTrasporto = null;
  674.                             String urlInvocazione = null;
  675.                             Map<String, List<String>> pQuery = null;
  676.                             Map<String, List<String>> pForm = null;
  677.                             if(this.requestInfo!=null && this.requestInfo.getProtocolContext()!=null) {
  678.                                 pTrasporto = this.requestInfo.getProtocolContext().getHeaders();
  679.                                 urlInvocazione = this.requestInfo.getProtocolContext().getUrlInvocazione_formBased();
  680.                                 pQuery = this.requestInfo.getProtocolContext().getParameters();
  681.                                 if(this.requestInfo.getProtocolContext() instanceof HttpServletTransportRequestContext) {
  682.                                     HttpServletTransportRequestContext httpServletContext = this.requestInfo.getProtocolContext();
  683.                                     HttpServletRequest httpServletRequest = httpServletContext.getHttpServletRequest();
  684.                                     if(httpServletRequest instanceof FormUrlEncodedHttpServletRequest) {
  685.                                         FormUrlEncodedHttpServletRequest formServlet = (FormUrlEncodedHttpServletRequest) httpServletRequest;
  686.                                         if(formServlet.getFormUrlEncodedParametersValues()!=null &&
  687.                                                 !formServlet.getFormUrlEncodedParametersValues().isEmpty()) {
  688.                                             pForm = formServlet.getFormUrlEncodedParametersValues();
  689.                                         }
  690.                                     }
  691.                                 }
  692.                             }
  693.                             MessageContent messageContent = null;
  694.                             boolean bufferMessageReadOnly =  OpenSPCoop2Properties.getInstance().isReadByPathBufferEnabled();
  695.                             if(ServiceBinding.SOAP.equals(message.getServiceBinding())){
  696.                                 messageContent = new MessageContent(message.castAsSoap(), bufferMessageReadOnly, this.pddContext);
  697.                             }
  698.                             else{
  699.                                 if(MessageType.XML.equals(message.getMessageType())){
  700.                                     messageContent = new MessageContent(message.castAsRestXml(), bufferMessageReadOnly, this.pddContext);
  701.                                 }
  702.                                 else if(MessageType.JSON.equals(message.getMessageType())){
  703.                                     messageContent = new MessageContent(message.castAsRestJson(), bufferMessageReadOnly, this.pddContext);
  704.                                 }
  705.                             }
  706.                            
  707.                             Map<String, Object> dynamicMap = new HashMap<>();
  708.                             ErrorHandler errorHandler = new ErrorHandler();
  709.                             DynamicUtils.fillDynamicMapRequest(this.log, dynamicMap, this.pddContext, urlInvocazione,
  710.                                     message,
  711.                                     messageContent,
  712.                                     this.busta,
  713.                                     pTrasporto,
  714.                                     pQuery,
  715.                                     pForm,
  716.                                     errorHandler);
  717.                             if(CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_TEMPLATE.equals(elemento.getIdentificazione())) {
  718.                                 idCorrelazioneApplicativa = DynamicUtils.convertDynamicPropertyValue("CorrelazioneApplicativaRichiesta.gwt", elemento.getPattern(), dynamicMap, this.pddContext);
  719.                                 if(idCorrelazioneApplicativa!=null) {
  720.                                     idCorrelazioneApplicativa = ConditionalUtils.normalizeTemplateResult(idCorrelazioneApplicativa);
  721.                                 }
  722.                             }
  723.                             else {
  724.                                 ByteArrayOutputStream bout = new ByteArrayOutputStream();
  725.                                 ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(this.state);
  726.                                 IDPortaApplicativa idPA = null;
  727.                                 IDPortaDelegata idPD = null;
  728.                                 if(this.pa!=null) {
  729.                                     idPA = new IDPortaApplicativa();
  730.                                     idPA.setNome(this.pa.getNome());
  731.                                 }
  732.                                 else if(this.pd!=null){
  733.                                     idPD = new IDPortaDelegata();
  734.                                     idPD.setNome(this.pd.getNome());
  735.                                 }
  736.                                 else {
  737.                                     throw new CoreException ("Porta non disponibile");
  738.                                 }
  739.                                 Template template = idPA!=null ?
  740.                                         configurazionePdDManager.getTemplateCorrelazioneApplicativaRichiesta(idPA, elemento.getNome(), elemento.getPattern().getBytes(), this.requestInfo)
  741.                                         :
  742.                                         configurazionePdDManager.getTemplateCorrelazioneApplicativaRichiesta(idPD, elemento.getNome(), elemento.getPattern().getBytes(), this.requestInfo);
  743.                                
  744.                                 if(CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_FREEMARKER_TEMPLATE.equals(elemento.getIdentificazione())) {
  745.                                     DynamicUtils.convertFreeMarkerTemplate(template, dynamicMap, bout);
  746.                                 }
  747.                                 else {
  748.                                     /** if(CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_VELOCITY_TEMPLATE.equals(elemento.getIdentificazione())) { */
  749.                                     DynamicUtils.convertVelocityTemplate(template, dynamicMap, bout);
  750.                                 }
  751.                                 bout.flush();
  752.                                 bout.close();
  753.                                 idCorrelazioneApplicativa = bout.toString();
  754.                                 if(idCorrelazioneApplicativa!=null) {
  755.                                     idCorrelazioneApplicativa = ConditionalUtils.normalizeTemplateResult(idCorrelazioneApplicativa);
  756.                                 }
  757.                             }
  758.                            
  759.                             checkExtractedIdentifierIsNull(idCorrelazioneApplicativa, true);
  760.                             checkExtractedIdentifierIsEmpty(idCorrelazioneApplicativa, true);

  761.                         }catch(Exception e){
  762.                             if(bloccaIdentificazioneNonRiuscita){
  763.                                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  764.                                         getErrore416_CorrelazioneApplicativaRichiesta(ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO+nomeElemento+ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_TEMPLATE_BASED+elemento.getIdentificazione().getValue()+"): "+e.getMessage());
  765.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  766.                             }else{
  767.                                 correlazioneNonRiuscitaDaAccettare = true;
  768.                             }
  769.                         }
  770.                     }
  771.                     else{
  772.                         // Content-Based
  773.                         try{
  774.                             if(ServiceBinding.REST.equals(message.getServiceBinding()) &&
  775.                                     !MessageType.XML.equals(message.getMessageType()) &&
  776.                                     !MessageType.JSON.equals(message.getMessageType()) &&
  777.                                     !MessageType.MIME_MULTIPART.equals(message.getMessageType())){
  778.                                 throw new CoreException("MessageType ["+message.getMessageType()+"] non supportato con correlazione di tipo '"+
  779.                                         CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_CONTENT_BASED.toString()+"'");
  780.                             }
  781.                             if(element==null && elementJson==null){
  782.                                 throw new CoreException("Contenuto non disponibile su cui effettuare una correlazione di tipo '"+
  783.                                         CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_CONTENT_BASED.toString()+"'");
  784.                             }
  785.                             if(element!=null) {
  786.                                 idCorrelazioneApplicativa = AbstractXPathExpressionEngine.extractAndConvertResultAsString(element, xPathEngine, elemento.getPattern(), this.log);
  787.                             }
  788.                             else {
  789.                                 idCorrelazioneApplicativa = JsonXmlPathExpressionEngine.extractAndConvertResultAsString(elementJson, elemento.getPattern(), this.log);
  790.                             }
  791.                                    
  792.                             checkExtractedIdentifierIsNull(idCorrelazioneApplicativa, true);
  793.                             checkExtractedIdentifierIsEmpty(idCorrelazioneApplicativa, true);
  794.                            
  795.                         }catch(Exception e){
  796.                             if(bloccaIdentificazioneNonRiuscita){
  797.                                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  798.                                         getErrore416_CorrelazioneApplicativaRichiesta(ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO+nomeElemento+ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_CONTENT_BASED+elemento.getPattern()+"): "+e.getMessage());
  799.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  800.                             }else{
  801.                                 correlazioneNonRiuscitaDaAccettare = true;
  802.                                 String debugInfo = "[AccettaIdentificazioneFallita] Identificativo di correlazione applicativa non identificato nell'elemento ["+nomeElemento+ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_CONTENT_BASED+elemento.getPattern()+"): "+e.getMessage();
  803.                                 this.log.info(debugInfo);
  804.                             }
  805.                         }
  806.                     }
  807.                    
  808.                    
  809.                     if(idCorrelazioneApplicativa!=null && idCorrelazioneApplicativa.length()>this.maxLengthCorrelazioneApplicativa) {
  810.                         if(bloccaIdentificazioneNonRiuscita) {
  811.                             if(this.isTruncateEnabled(RICHIESTA, BLOCCA)) {
  812.                                 idCorrelazioneApplicativa = this.truncate(idCorrelazioneApplicativa, RICHIESTA, BLOCCA);
  813.                             }
  814.                             else {
  815.                                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  816.                                         getErrore416_CorrelazioneApplicativaRichiesta(this.buildErroreLunghezzaIdentificativo(idCorrelazioneApplicativa));
  817.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  818.                             }
  819.                         }
  820.                         else {
  821.                             if(this.isTruncateEnabled(RICHIESTA, ACCETTA)) {
  822.                                 idCorrelazioneApplicativa = this.truncate(idCorrelazioneApplicativa, RICHIESTA, ACCETTA);
  823.                             }
  824.                             else {
  825.                                 String erroreId = this.buildErroreLunghezzaIdentificativo(idCorrelazioneApplicativa);
  826.                                 this.log.error(erroreId);
  827.                                 correlazioneNonRiuscitaDaAccettare = true;
  828.                                 idCorrelazioneApplicativa = null;
  829.                             }
  830.                         }
  831.                     }
  832.                    
  833.                     findCorrelazione = true;
  834.                     break;
  835.                 }
  836.             }
  837.         }
  838.        
  839.         if(idCorrelazioneApplicativa == null){
  840.             boolean generaErrore = false;
  841.             if( !findCorrelazione ) {
  842.                 generaErrore = this.isRichiestaRegolaCorrelazioneNonTrovataBlocca;
  843.             }
  844.             else {
  845.                 generaErrore = !correlazioneNonRiuscitaDaAccettare;
  846.             }
  847.             if( generaErrore ){
  848.                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  849.                         getErrore416_CorrelazioneApplicativaRichiesta("Identificativo di correlazione applicativa non identificato; nessun elemento tra quelli di correlazione definiti è presente nel body");
  850.                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  851.             }
  852.         }else{          
  853.             this.idCorrelazione = idCorrelazioneApplicativa;
  854.             if(this.pddContext!=null) {
  855.                 this.pddContext.addObject(CONTEXT_CORRELAZIONE_APPLICATIVA_RICHIESTA, this.idCorrelazione);
  856.             }
  857.         }

  858.     }
  859.    
  860.     private boolean verificaCorrelazioneIdentificativoRichiestaEngine() throws GestoreMessaggiException{
  861.        
  862.         /** Fase di verifica dell'id di correlazione con l'id */
  863.        
  864.         if(this.riusoIdentificativo){
  865.             try{
  866.                 StateMessage stateMSG = (StateMessage)this.state;
  867.                 Connection connectionDB = stateMSG.getConnectionDB();
  868.    
  869.                 // Lettura attuale valore
  870.                
  871.                 executeVerificaCorrelazioneIdentificativoRichiesta(connectionDB);
  872.    
  873.             } catch(Exception er) {
  874.                 this.errore = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  875.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_529_CORRELAZIONE_APPLICATIVA_RICHIESTA_NON_RIUSCITA);
  876.                 String error = "Verifica correlazione IDApplicativo - ID non riuscita: "+er.getMessage();
  877.                 this.log.error(error);
  878.                 throw new GestoreMessaggiException("Verifica correlazione IDApplicativo - ID non riuscita: "+er.getMessage(),er);
  879.             }
  880.    
  881.             return this.idBustaCorrelato!=null;

  882.         }else{
  883.             return false;
  884.         }

  885.     }
  886.     private boolean executeVerificaCorrelazioneIdentificativoRichiesta(Connection connectionDB) throws SQLException, GestoreMessaggiException{
  887.        
  888.         PreparedStatement pstmt = null;
  889.         ResultSet rs = null;
  890.         boolean correlazionePresente = false;
  891.         try{
  892.        
  893.             // Azione
  894.             String valoreAzione = "(AZIONE is null)";
  895.             if( (this.idServizio.getAzione()!=null) && (!"".equals(this.idServizio.getAzione())) ){
  896.                 valoreAzione = "AZIONE=?";
  897.             }
  898.            
  899.             StringBuilder query = new StringBuilder();
  900.             query.append("SELECT * FROM "+GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA+" WHERE ID_APPLICATIVO=? AND SERVIZIO_APPLICATIVO=? AND"+
  901.                     " TIPO_MITTENTE=? AND MITTENTE=? AND TIPO_DESTINATARIO=? AND DESTINATARIO=? AND TIPO_SERVIZIO=? AND SERVIZIO=? AND VERSIONE_SERVIZIO=? AND "+valoreAzione);
  902.             pstmt = connectionDB.prepareStatement(query.toString());
  903.             int index = 1;
  904.             pstmt.setString(index++,this.idCorrelazione);
  905.             pstmt.setString(index++,this.servizioApplicativo);
  906.             pstmt.setString(index++,this.soggettoFruitore.getTipo());
  907.             pstmt.setString(index++,this.soggettoFruitore.getNome());
  908.             pstmt.setString(index++,this.idServizio.getSoggettoErogatore().getTipo());
  909.             pstmt.setString(index++,this.idServizio.getSoggettoErogatore().getNome());
  910.             pstmt.setString(index++,this.idServizio.getTipo());
  911.             pstmt.setString(index++,this.idServizio.getNome());
  912.             pstmt.setInt(index++,this.idServizio.getVersione());
  913.            
  914.             if( (this.idServizio.getAzione()!=null) && (!"".equals(this.idServizio.getAzione())) ){
  915.                 pstmt.setString(index,this.idServizio.getAzione());
  916.             }
  917.            
  918.             rs = pstmt.executeQuery();
  919.             if(rs == null) {
  920.                 pstmt.close();
  921.                 this.log.error("Verifica correlazione IDApplicativo - ID non riuscita: ResultSet is null?");
  922.                 throw new GestoreMessaggiException("Verifica correlazione IDApplicativo - ID non riuscita: ResultSet is null?");        
  923.             }
  924.             correlazionePresente = rs.next();
  925.             if(correlazionePresente){
  926.                 this.idBustaCorrelato = rs.getString(CORRELAZIONE_APPLICATIVA_COLUMN_ID_MESSAGGIO);
  927.             }
  928.         } finally {
  929.             try {
  930.                 if(rs!=null) {
  931.                     rs.close();
  932.                 }
  933.             }catch(Exception t) {
  934.                 // ignore
  935.             }
  936.             try {
  937.                 if(pstmt!=null) {
  938.                     pstmt.close();
  939.                 }
  940.             }catch(Exception t) {
  941.                 // ignore
  942.             }
  943.         }
  944.        
  945.         return correlazionePresente;
  946.     }


  947.    
  948.    
  949.    
  950.    
  951.     /* *********** GESTIONE CORRELAZIONE APPLICATIVA RISPOSTA (RISPOSTA) ************ */
  952.    
  953.     public void verificaCorrelazioneRisposta(CorrelazioneApplicativaRisposta correlazioneApplicativa,
  954.             OpenSPCoop2Message message,HeaderIntegrazione headerIntegrazione,boolean readFirstHeaderIntegrazione) throws GestoreMessaggiException, ProtocolException{
  955.         if(this.transaction!=null) {
  956.             this.transaction.getTempiElaborazione().startCorrelazioneApplicativaRisposta();
  957.         }
  958.         try {
  959.             this.verificaCorrelazioneRispostaEngine(correlazioneApplicativa, message, headerIntegrazione, readFirstHeaderIntegrazione);
  960.         }
  961.         finally {
  962.             if(this.transaction!=null) {
  963.                 this.transaction.getTempiElaborazione().endCorrelazioneApplicativaRisposta();
  964.             }
  965.         }
  966.     }
  967.     private void verificaCorrelazioneRispostaEngine(CorrelazioneApplicativaRisposta correlazioneApplicativa,
  968.             OpenSPCoop2Message message,HeaderIntegrazione headerIntegrazione,boolean readFirstHeaderIntegrazione) throws GestoreMessaggiException, ProtocolException{

  969.         if(correlazioneApplicativa==null){
  970.             this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  971.                     getErrore434_CorrelazioneApplicativaRisposta("dati per l'identificazione dell'id di correlazione non presenti");
  972.             throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  973.         }
  974.        
  975.         if(message==null) {
  976.             this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  977.                     getErrore434_CorrelazioneApplicativaRisposta("messaggio non presente");
  978.             throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  979.         }

  980.         Element element = null;
  981.         String elementJson = null;
  982.         try{
  983.             String idTransazione = null;
  984.             if(this.pddContext!=null) {
  985.                 idTransazione = (String)this.pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  986.             }
  987.             boolean bufferMessageReadOnly =  OpenSPCoop2Properties.getInstance().isReadByPathBufferEnabled();
  988.             boolean checkSoapBodyEmpty = false; // devo poter fare xpath anche su soapBody empty
  989.             element = MessageUtils.getContentElement(message, checkSoapBodyEmpty, bufferMessageReadOnly, idTransazione);
  990.             elementJson = MessageUtils.getContentString(message, bufferMessageReadOnly, idTransazione);
  991.         }catch(Exception e){
  992.             throw new GestoreMessaggiException(e.getMessage(),e);
  993.         }
  994.        
  995.         // XPathExpressionEngine
  996.         AbstractXPathExpressionEngine xPathEngine = new org.openspcoop2.message.xml.XPathExpressionEngine(message.getFactory());
  997.        
  998.         /** Fase di identificazione dell'id di correlazione */
  999.         boolean checkElementiInTransito = false;
  1000.         if(correlazioneApplicativa.sizeElementoList()>1){
  1001.             checkElementiInTransito = true;
  1002.         }
  1003.         else{
  1004.             if(correlazioneApplicativa.sizeElementoList()>0){
  1005.                 CorrelazioneApplicativaRispostaElemento elemento = correlazioneApplicativa.getElemento(0);
  1006.                 if( (elemento.getNome()!=null) && !"".equals(elemento.getNome()) ){
  1007.                     checkElementiInTransito = true;
  1008.                 }
  1009.             }
  1010.         }
  1011.         List<Node> nList = null;
  1012.         if(checkElementiInTransito){
  1013.             try{
  1014.                 if(ServiceBinding.SOAP.equals(message.getServiceBinding())){
  1015.                     SOAPEnvelope envelope = (SOAPEnvelope) element;
  1016.                     if(envelope==null){
  1017.                         throw new CoreException("Envelope non presente nel messaggio Soap");
  1018.                     }
  1019.                     if(envelope.getBody()==null || !envelope.getBody().hasChildNodes()){
  1020.                         throw new CoreException("Body applicativo non presente nel messaggio Soap");
  1021.                     }
  1022.                     NodeList nListSoapBody = envelope.getBody().getChildNodes();
  1023.                     if(nListSoapBody==null || nListSoapBody.getLength()==0){
  1024.                         throw new CoreException("Elementi del Body non presenti?");
  1025.                     }
  1026.                     nList = new ArrayList<>();
  1027.                     for (int elem=0; elem<nListSoapBody.getLength(); elem++){
  1028.                         Node nodeInEsame =  nListSoapBody.item(elem);
  1029.                         if(nodeInEsame instanceof Text || nodeInEsame instanceof Comment){
  1030.                             continue;
  1031.                         }
  1032.                         nList.add(nodeInEsame);
  1033.                     }
  1034.                 }
  1035.                 else{
  1036.                     if(MessageType.XML.equals(message.getMessageType()) ||
  1037.                             MessageType.MIME_MULTIPART.equals(message.getMessageType()) // viene prelevato il primo xml trovato
  1038.                             ){
  1039.                         /** il body http puo' essere vuoto
  1040.                         if(element==null){
  1041.                             throw new Exception("Contenuto non presente nel messaggio");
  1042.                         }*/
  1043.                         if(element!=null) {
  1044.                             nList = new ArrayList<>();
  1045.                             nList.add(element);
  1046.                         }
  1047.                     }
  1048.                     else{
  1049.                         checkElementiInTransito = false;
  1050.                     }
  1051.                 }
  1052.             }catch(Exception e){
  1053.                 this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  1054.                         getErrore434_CorrelazioneApplicativaRisposta(ERRORE_IDENTIFICAZIONE_MESSAGE+e.getMessage());
  1055.                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  1056.             }
  1057.         }

  1058.        
  1059.         /** Gestioni correlazioni, in modo da avere lo '*' in fondo */
  1060.         java.util.List<CorrelazioneApplicativaRispostaElemento> c = new java.util.ArrayList<>();
  1061.         int posizioneElementoQualsiasi = -1;
  1062.         for(int i=0; i<correlazioneApplicativa.sizeElementoList(); i++){
  1063.             CorrelazioneApplicativaRispostaElemento elemento = correlazioneApplicativa.getElemento(i);
  1064.             if( (elemento.getNome()==null) || "".equals(elemento.getNome()) ){
  1065.                 if(posizioneElementoQualsiasi!=-1){
  1066.                     this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  1067.                             getErrore434_CorrelazioneApplicativaRisposta("errore durante l'analisi dell'elementName: piu' di un elemento '*' non puo' essere definito");
  1068.                     throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  1069.                 }else{
  1070.                     posizioneElementoQualsiasi = i;
  1071.                 }
  1072.             }else{
  1073.                 c.add(elemento);
  1074.             }
  1075.         }
  1076.         if(posizioneElementoQualsiasi>=0){
  1077.             // deve essere analizzato per ultimo
  1078.             c.add(correlazioneApplicativa.getElemento(posizioneElementoQualsiasi));
  1079.         }
  1080.        

  1081.         /** Fase di identificazione dell'id di correlazione */
  1082.         boolean findCorrelazione = false;
  1083.         boolean correlazioneNonRiuscitaDaAccettare = false;
  1084.         String idCorrelazioneApplicativa = null;
  1085.        
  1086.         // Calcolo posizione ultimo nodo "buono"
  1087.         int posizioneUltimoNodo = -1;
  1088.         if(checkElementiInTransito && nList!=null){
  1089.             for (int elem=0; elem<nList.size(); elem++){
  1090.                 Node nodeInEsame =  nList.get(elem);
  1091.                 if(nodeInEsame instanceof Text || nodeInEsame instanceof Comment){
  1092.                     continue;
  1093.                 }
  1094.                 posizioneUltimoNodo = elem;
  1095.             }
  1096.         }
  1097.         else{
  1098.             posizioneUltimoNodo = 0;
  1099.         }
  1100.        
  1101.         // Calcolo nomi
  1102.         List<String> nomiPresentiBody = new ArrayList<>();
  1103.         if(checkElementiInTransito && nList!=null){
  1104.             for (int elem=0; elem<nList.size(); elem++){
  1105.                 String elementName = null;
  1106.                 Node nodeInEsame =  nList.get(elem);
  1107.                 if( (!(nodeInEsame instanceof Text)) && (!(nodeInEsame instanceof Comment)) ){
  1108.                     try{
  1109.                         elementName = nodeInEsame.getLocalName();
  1110.                     }catch(Exception e){
  1111.                         this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  1112.                                 getErrore434_CorrelazioneApplicativaRisposta(ERRORE_IDENTIFICAZIONE_MESSAGE+e.getMessage());
  1113.                         throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  1114.                     }
  1115.                     if(elementName==null){
  1116.                         continue;
  1117.                     }
  1118.                     nomiPresentiBody.add(elementName);
  1119.                 }
  1120.             }
  1121.         }
  1122.         else{
  1123.             nomiPresentiBody.add("PresenteSoloRegola*");
  1124.         }
  1125.        
  1126.        
  1127.         for (int elem=0; elem<nomiPresentiBody.size(); elem++){

  1128.             String elementName = nomiPresentiBody.get(elem);

  1129.             if(findCorrelazione)
  1130.                 break;

  1131.             for(int i=0; i<c.size(); i++){
  1132.                
  1133.                 CorrelazioneApplicativaRispostaElemento elemento = c.get(i);
  1134.                
  1135.                 boolean bloccaIdentificazioneNonRiuscita = true;
  1136.                 if(CostantiConfigurazione.ACCETTA.equals(elemento.getIdentificazioneFallita()))
  1137.                     bloccaIdentificazioneNonRiuscita = false;
  1138.                
  1139.                 // Il nome dell'elemento di una correlazione applicativa puo' essere:
  1140.                 // non definito: significa per qualsiasi XML
  1141.                 // nome: nome dell'elemento radice dell'xml
  1142.                 // xpath expression: per identificare il nome dell'elemento radice XML
  1143.                 boolean matchNodePerCorrelazioneApplicativa = false;
  1144.                 String nomeElemento = null;
  1145.                 if( (elemento.getNome()==null) || "".equals(elemento.getNome()) ){
  1146.                     matchNodePerCorrelazioneApplicativa = true;
  1147.                     nomeElemento = "*";
  1148.                    
  1149.                     // Devo applicare lo '*' solo se ho prima guardato tutti i nodi radice e sono ad esaminare l'ultimo nodo radice.
  1150.                     // L'ordine delle correlazioni mi garantira' che lo '*' sara' esaminato per ultimo
  1151.                     if( elem!=posizioneUltimoNodo ) {
  1152.                         continue;
  1153.                     }
  1154.                    
  1155.                 }
  1156.                 else if(
  1157.                             (
  1158.                                 // Ricerco per match sull'azione
  1159.                                 this.idServizio!=null && this.idServizio.getAzione()!=null &&
  1160.                                 this.idServizio.getAzione().equals(elemento.getNome())
  1161.                             )
  1162.                             ||
  1163.                             (
  1164.                                 // Ricerco per match sul localName dell'elemento (se XML)
  1165.                                 elementName.equals(elemento.getNome())
  1166.                             )
  1167.                         ) {
  1168.                    
  1169.                     matchNodePerCorrelazioneApplicativa = true;
  1170.                     nomeElemento = elemento.getNome();
  1171.                 }
  1172.                 else{
  1173.                    
  1174.                     // se siamo in REST provo a cercare per metodo e path
  1175.                     boolean isResourceRest = false;
  1176.                     if(ServiceBinding.REST.equals(message.getServiceBinding())){
  1177.                         isResourceRest = isMatchResourceRest(elemento.getNome());
  1178.                     }
  1179.                     if(isResourceRest) {
  1180.                         matchNodePerCorrelazioneApplicativa = true;
  1181.                         nomeElemento = elemento.getNome();
  1182.                     }
  1183.                     else {
  1184.                    
  1185.                         // Ricerco elemento con una espressione che potrebbe essere riferita a tutta l'envelope
  1186.                         try{
  1187.                             if(element==null && elementJson==null){
  1188.                                 throw new CoreException("Contenuto non disponibile su cui effettuare un match");
  1189.                             }
  1190.                             if(element!=null) {
  1191.                                 nomeElemento = AbstractXPathExpressionEngine.extractAndConvertResultAsString(element, xPathEngine, elemento.getNome(), this.log);
  1192.                             }
  1193.                             else {
  1194.                                 nomeElemento = JsonXmlPathExpressionEngine.extractAndConvertResultAsString(elementJson, elemento.getNome(), this.log);
  1195.                             }
  1196.                             if(nomeElemento!=null) {
  1197.                                 matchNodePerCorrelazioneApplicativa = true;
  1198.                             }
  1199.                         }catch(Exception e){
  1200.                             String error = "Calcolo non riuscito ["+elementName+"] ["+elemento.getNome()+"]: "+e.getMessage();
  1201.                             this.log.info(error);
  1202.                         }
  1203.                         // Ricerco tramuite espressione regolare sulla url
  1204.                         // Non possibile sulla risposta
  1205.                        
  1206.                     }
  1207.                 }


  1208.                 // Correlazione
  1209.                 if( matchNodePerCorrelazioneApplicativa ){

  1210.                     // Puo' darsi che questo elemento identificato non abbia bisogna effettuare correlazione applicativa
  1211.                     if(CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_DISABILITATO.equals(elemento.getIdentificazione())){
  1212.                         correlazioneNonRiuscitaDaAccettare = true;
  1213.                         findCorrelazione = true;
  1214.                         break;
  1215.                     }
  1216.                    
  1217.                    
  1218.                     if(readFirstHeaderIntegrazione &&
  1219.                         headerIntegrazione.getIdApplicativo()!=null){
  1220.                         idCorrelazioneApplicativa = headerIntegrazione.getIdApplicativo();
  1221.                         findCorrelazione = true;
  1222.                         break;
  1223.                     }

  1224.                     if( CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_HEADER_BASED.equals(elemento.getIdentificazione())){
  1225.                         try{
  1226.                             if(message==null ||
  1227.                                     message.getTransportResponseContext()==null ||
  1228.                                     message.getTransportResponseContext().getHeaders()==null ||
  1229.                                     message.getTransportResponseContext().getHeaders().isEmpty()) {
  1230.                                 throw new CoreException ("headers not found");
  1231.                             }
  1232.                             idCorrelazioneApplicativa = message.getTransportResponseContext().getHeaderFirstValue(elemento.getPattern());
  1233.                             if(idCorrelazioneApplicativa==null) {
  1234.                                 // NOTA: deve essere considerato come vi fosse un errore nel pattern
  1235.                                 throw new GestoreMessaggiException("header not found");
  1236.                             }
  1237.                             checkExtractedIdentifierIsEmpty(idCorrelazioneApplicativa, false);
  1238.                         }catch(Exception e){
  1239.                             if(bloccaIdentificazioneNonRiuscita){
  1240.                                 this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  1241.                                         getErrore434_CorrelazioneApplicativaRisposta(ERRORE_IDENTIFICAZIONE_PER_ELEMENTO+nomeElemento+"] " +
  1242.                                                 ERRORE_IDENTIFICAZIONE_PER_ELEMENTO_MODALITA_INPUT_BASED);
  1243.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  1244.                             }else{
  1245.                                 correlazioneNonRiuscitaDaAccettare = true;
  1246.                             }
  1247.                         }
  1248.                     }
  1249.                     else if( CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_INPUT_BASED.equals(elemento.getIdentificazione()) ){
  1250.                         idCorrelazioneApplicativa = headerIntegrazione.getIdApplicativo();
  1251.                         if(
  1252.                                 (idCorrelazioneApplicativa==null) // NOTA: deve essere considerato come vi fosse un errore
  1253.                                 ||
  1254.                                 (StringUtils.isEmpty(idCorrelazioneApplicativa) && this.isRispostaIdentificativoEstrattoIsEmptyThrowError)
  1255.                             ){
  1256.                             if(bloccaIdentificazioneNonRiuscita){
  1257.                                 this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  1258.                                         getErrore434_CorrelazioneApplicativaRisposta(ERRORE_IDENTIFICAZIONE_PER_ELEMENTO+nomeElemento+"] " +
  1259.                                                 ERRORE_IDENTIFICAZIONE_PER_ELEMENTO_MODALITA_INPUT_BASED);
  1260.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  1261.                             }else{
  1262.                                 correlazioneNonRiuscitaDaAccettare = true;
  1263.                             }
  1264.                         }
  1265.                     }
  1266.                     else if( CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_TEMPLATE.equals(elemento.getIdentificazione())
  1267.                             ||
  1268.                             CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_FREEMARKER_TEMPLATE.equals(elemento.getIdentificazione())
  1269.                             ||
  1270.                             CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_VELOCITY_TEMPLATE.equals(elemento.getIdentificazione())){
  1271.                         try{
  1272.                            
  1273.                             if(elemento.getPattern()==null || StringUtils.isEmpty(elemento.getPattern())) {
  1274.                                 throw new CoreException ("Template non disponibile");
  1275.                             }
  1276.                            
  1277.                             Map<String, List<String>> pTrasporto = null;
  1278.                             String urlInvocazione = null;
  1279.                             Map<String, List<String>> pQuery = null;
  1280.                             Map<String, List<String>> pForm = null;
  1281.                             if(this.requestInfo!=null && this.requestInfo.getProtocolContext()!=null) {
  1282.                                 pTrasporto = this.requestInfo.getProtocolContext().getHeaders();
  1283.                                 urlInvocazione = this.requestInfo.getProtocolContext().getUrlInvocazione_formBased();
  1284.                                 pQuery = this.requestInfo.getProtocolContext().getParameters();
  1285.                                 if(this.requestInfo.getProtocolContext() instanceof HttpServletTransportRequestContext) {
  1286.                                     HttpServletTransportRequestContext httpServletContext = this.requestInfo.getProtocolContext();
  1287.                                     HttpServletRequest httpServletRequest = httpServletContext.getHttpServletRequest();
  1288.                                     if(httpServletRequest instanceof FormUrlEncodedHttpServletRequest) {
  1289.                                         FormUrlEncodedHttpServletRequest formServlet = (FormUrlEncodedHttpServletRequest) httpServletRequest;
  1290.                                         if(formServlet.getFormUrlEncodedParametersValues()!=null &&
  1291.                                                 !formServlet.getFormUrlEncodedParametersValues().isEmpty()) {
  1292.                                             pForm = formServlet.getFormUrlEncodedParametersValues();
  1293.                                         }
  1294.                                     }
  1295.                                 }
  1296.                             }
  1297.                            
  1298.                             Map<String, List<String>> parametriTrasporto = null;
  1299.                             if(message.getTransportResponseContext()!=null) {
  1300.                                 if(message.getTransportResponseContext().getHeaders()!=null &&
  1301.                                     !message.getTransportResponseContext().getHeaders().isEmpty()) {
  1302.                                     parametriTrasporto = message.getTransportResponseContext().getHeaders();
  1303.                                 }
  1304.                                 else {
  1305.                                     parametriTrasporto = new HashMap<>();
  1306.                                     message.getTransportResponseContext().setHeaders(parametriTrasporto);
  1307.                                 }
  1308.                             }

  1309.                             MessageContent messageContent = null;
  1310.                             boolean bufferMessageReadOnly =  OpenSPCoop2Properties.getInstance().isReadByPathBufferEnabled();
  1311.                             if(ServiceBinding.SOAP.equals(message.getServiceBinding())){
  1312.                                 messageContent = new MessageContent(message.castAsSoap(), bufferMessageReadOnly, this.pddContext);
  1313.                             }
  1314.                             else{
  1315.                                 if(MessageType.XML.equals(message.getMessageType())){
  1316.                                     messageContent = new MessageContent(message.castAsRestXml(), bufferMessageReadOnly, this.pddContext);
  1317.                                 }
  1318.                                 else if(MessageType.JSON.equals(message.getMessageType())){
  1319.                                     messageContent = new MessageContent(message.castAsRestJson(), bufferMessageReadOnly, this.pddContext);
  1320.                                 }
  1321.                             }
  1322.                            
  1323.                             Map<String, Object> dynamicMapRequest = new HashMap<>();
  1324.                             ErrorHandler errorHandlerRequest = new ErrorHandler();
  1325.                             DynamicUtils.fillDynamicMapRequest(this.log, dynamicMapRequest, this.pddContext, urlInvocazione,
  1326.                                     null, //message,
  1327.                                     null, //messageContent,
  1328.                                     this.busta,
  1329.                                     pTrasporto,
  1330.                                     pQuery,
  1331.                                     pForm,
  1332.                                     errorHandlerRequest);
  1333.                            
  1334.                             Map<String, Object> dynamicMap = new HashMap<>();
  1335.                             ErrorHandler errorHandler = new ErrorHandler();
  1336.                             DynamicUtils.fillDynamicMapResponse(this.log, dynamicMap, dynamicMapRequest, this.pddContext,
  1337.                                     message,
  1338.                                     messageContent, this.busta, parametriTrasporto,
  1339.                                     errorHandler);
  1340.                             if(CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_TEMPLATE.equals(elemento.getIdentificazione())) {
  1341.                                 idCorrelazioneApplicativa = DynamicUtils.convertDynamicPropertyValue("CorrelazioneApplicativaRisposta.gwt", elemento.getPattern(), dynamicMap, this.pddContext);
  1342.                                 if(idCorrelazioneApplicativa!=null) {
  1343.                                     idCorrelazioneApplicativa = ConditionalUtils.normalizeTemplateResult(idCorrelazioneApplicativa);
  1344.                                 }
  1345.                             }
  1346.                             else {
  1347.                                 ByteArrayOutputStream bout = new ByteArrayOutputStream();
  1348.                                 ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(this.state);
  1349.                                 IDPortaApplicativa idPA = null;
  1350.                                 IDPortaDelegata idPD = null;
  1351.                                 if(this.pa!=null) {
  1352.                                     idPA = new IDPortaApplicativa();
  1353.                                     idPA.setNome(this.pa.getNome());
  1354.                                 }
  1355.                                 else if(this.pd!=null){
  1356.                                     idPD = new IDPortaDelegata();
  1357.                                     idPD.setNome(this.pd.getNome());
  1358.                                 }
  1359.                                 else {
  1360.                                     throw new CoreException ("Porta non disponibile");
  1361.                                 }
  1362.                                 Template template = idPA!=null ?
  1363.                                         configurazionePdDManager.getTemplateCorrelazioneApplicativaRisposta(idPA, elemento.getNome(), elemento.getPattern().getBytes(), this.requestInfo)
  1364.                                         :
  1365.                                         configurazionePdDManager.getTemplateCorrelazioneApplicativaRisposta(idPD, elemento.getNome(), elemento.getPattern().getBytes(), this.requestInfo);
  1366.                                
  1367.                                 if(CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_FREEMARKER_TEMPLATE.equals(elemento.getIdentificazione())) {
  1368.                                     DynamicUtils.convertFreeMarkerTemplate(template, dynamicMap, bout);
  1369.                                 }
  1370.                                 else {
  1371.                                     /** if(CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RISPOSTA_VELOCITY_TEMPLATE.equals(elemento.getIdentificazione())) { */
  1372.                                     DynamicUtils.convertVelocityTemplate(template, dynamicMap, bout);
  1373.                                 }
  1374.                                 bout.flush();
  1375.                                 bout.close();
  1376.                                 idCorrelazioneApplicativa = bout.toString();
  1377.                                 if(idCorrelazioneApplicativa!=null) {
  1378.                                     idCorrelazioneApplicativa = ConditionalUtils.normalizeTemplateResult(idCorrelazioneApplicativa);
  1379.                                 }
  1380.                             }

  1381.                             checkExtractedIdentifierIsNull(idCorrelazioneApplicativa, false);
  1382.                             checkExtractedIdentifierIsEmpty(idCorrelazioneApplicativa, false);
  1383.                            
  1384.                         }catch(Exception e){
  1385.                             if(bloccaIdentificazioneNonRiuscita){
  1386.                                 this.errore = ErroriIntegrazione.ERRORE_416_CORRELAZIONE_APPLICATIVA_RICHIESTA_ERRORE.
  1387.                                         getErrore416_CorrelazioneApplicativaRichiesta(ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO+nomeElemento+ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_TEMPLATE_BASED+elemento.getIdentificazione().getValue()+"): "+e.getMessage());
  1388.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  1389.                             }else{
  1390.                                 correlazioneNonRiuscitaDaAccettare = true;
  1391.                             }
  1392.                         }
  1393.                     }
  1394.                     else{
  1395.                         // Content-Based
  1396.                         try{
  1397.                             if(ServiceBinding.REST.equals(message.getServiceBinding()) &&
  1398.                                     !MessageType.XML.equals(message.getMessageType()) &&
  1399.                                     !MessageType.JSON.equals(message.getMessageType()) &&
  1400.                                     !MessageType.MIME_MULTIPART.equals(message.getMessageType())){
  1401.                                 throw new CoreException("MessageType ["+message.getMessageType()+"] non supportato con correlazione di tipo '"+
  1402.                                         CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_CONTENT_BASED.toString()+"'");
  1403.                             }
  1404.                             if(element==null && elementJson==null){
  1405.                                 throw new CoreException("Contenuto non disponibile su cui effettuare una correlazione di tipo '"+
  1406.                                         CostantiConfigurazione.CORRELAZIONE_APPLICATIVA_RICHIESTA_CONTENT_BASED.toString()+"'");
  1407.                             }
  1408.                             if(element!=null) {
  1409.                                 idCorrelazioneApplicativa = AbstractXPathExpressionEngine.extractAndConvertResultAsString(element, xPathEngine, elemento.getPattern(), this.log);
  1410.                             }
  1411.                             else {
  1412.                                 idCorrelazioneApplicativa = JsonXmlPathExpressionEngine.extractAndConvertResultAsString(elementJson, elemento.getPattern(), this.log);
  1413.                             }
  1414.                                    
  1415.                             checkExtractedIdentifierIsNull(idCorrelazioneApplicativa, false);
  1416.                             checkExtractedIdentifierIsEmpty(idCorrelazioneApplicativa, false);
  1417.                            
  1418.                         }catch(Exception e){
  1419.                             if(bloccaIdentificazioneNonRiuscita){
  1420.                                 this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  1421.                                         getErrore434_CorrelazioneApplicativaRisposta("Identificativo di correlazione applicativa non identificato nell'elemento ["+nomeElemento+ERRORE_IDENTIFICAZIONE_NON_IDENTIFICATO_NEL_ELEMENTO_MODALITA_CONTENT_BASED+elemento.getPattern()+"): "+e.getMessage());
  1422.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory),e);
  1423.                             }else{
  1424.                                 correlazioneNonRiuscitaDaAccettare = true;
  1425.                             }
  1426.                         }
  1427.                     }
  1428.                    
  1429.                     if(idCorrelazioneApplicativa!=null && idCorrelazioneApplicativa.length()>this.maxLengthCorrelazioneApplicativa) {
  1430.                         if(bloccaIdentificazioneNonRiuscita) {
  1431.                             if(this.isTruncateEnabled(RISPOSTA, BLOCCA)) {
  1432.                                 idCorrelazioneApplicativa = this.truncate(idCorrelazioneApplicativa, RISPOSTA, BLOCCA);
  1433.                             }
  1434.                             else {
  1435.                                 this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  1436.                                         getErrore434_CorrelazioneApplicativaRisposta(this.buildErroreLunghezzaIdentificativo(idCorrelazioneApplicativa));
  1437.                                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  1438.                             }
  1439.                         }
  1440.                         else {
  1441.                             if(this.isTruncateEnabled(RISPOSTA, ACCETTA)) {
  1442.                                 idCorrelazioneApplicativa = this.truncate(idCorrelazioneApplicativa, RISPOSTA, ACCETTA);
  1443.                             }
  1444.                             else {
  1445.                                 String errorId = this.buildErroreLunghezzaIdentificativo(idCorrelazioneApplicativa);
  1446.                                 this.log.error(errorId);
  1447.                                 correlazioneNonRiuscitaDaAccettare = true;
  1448.                                 idCorrelazioneApplicativa = null;
  1449.                             }
  1450.                         }
  1451.                     }
  1452.                    
  1453.                     findCorrelazione = true;
  1454.                     break;
  1455.                 }
  1456.             }
  1457.         }

  1458.         if(idCorrelazioneApplicativa == null){
  1459.             boolean generaErrore = false;
  1460.             if( !findCorrelazione ) {
  1461.                 generaErrore = this.isRispostaRegolaCorrelazioneNonTrovataBlocca;
  1462.             }
  1463.             else {
  1464.                 generaErrore = !correlazioneNonRiuscitaDaAccettare;
  1465.             }
  1466.             if( generaErrore ){
  1467.                 this.errore = ErroriIntegrazione.ERRORE_434_CORRELAZIONE_APPLICATIVA_RISPOSTA_ERRORE.
  1468.                         getErrore434_CorrelazioneApplicativaRisposta("Identificativo di correlazione applicativa non identificato; nessun elemento tra quelli di correlazione definiti è presente nel body");
  1469.                 throw new GestoreMessaggiException(this.errore.getDescrizione(this.protocolFactory));
  1470.             }
  1471.         }else{
  1472.             this.idCorrelazione = idCorrelazioneApplicativa;
  1473.             if(this.pddContext!=null) {
  1474.                 this.pddContext.addObject(CONTEXT_CORRELAZIONE_APPLICATIVA_RISPOSTA, this.idCorrelazione);
  1475.             }
  1476.         }

  1477.     }
  1478.    
  1479.    
  1480.    
  1481.    
  1482.    
  1483.     /* *********** INDIVIDUAZIONE RISORSA REST ************ */
  1484.    
  1485.     private boolean isMatchResourceRest(String elemento) {
  1486.         boolean isResourceRest = false;
  1487.         if(elemento!=null && !"".equals(elemento)) {
  1488.             String [] parseResourceRest = Utilities.parseResourceRest(elemento);
  1489.             if(parseResourceRest!=null) {
  1490.                 this.initRestResource();
  1491.                 if(this.restResource!=null) {
  1492.                     isResourceRest = Utilities.isRestResourceMatch(parseResourceRest, this.restResource);
  1493.                 }
  1494.             }
  1495.         }
  1496.         return isResourceRest;
  1497.     }
  1498.    
  1499.     private void initRestResource() {
  1500.         if(this.restResource!=null) {
  1501.             return;
  1502.         }
  1503.         this.restResource = Utilities.getRestResource(this.log, this.state, this.idServizio, this.requestInfo);
  1504.     }
  1505.    
  1506.    

  1507.    
  1508.    
  1509.    
  1510.     /* *********** RIUSO DELL'ID ************ */
  1511.    
  1512.    
  1513.     /**
  1514.      * Ritorna true se l'id passato come parametro viene correlato all'id applicativo.
  1515.      * Se avviene un errore durante la ricerca della correlazione, viene lanciata una eccezione.
  1516.      *
  1517.      * @param correlazioneApplicativa Parametri di correlazione applicativa
  1518.      * @param idApplicativo IDApplicativo da associare alla richiesta
  1519.      * @param idBustaRequest Nuovo potenziale ID da associare alla richiesta
  1520.      * @throws ProtocolException
  1521.      */
  1522.     public void applicaCorrelazione(CorrelazioneApplicativa correlazioneApplicativa,String idApplicativo,String idBustaRequest) throws GestoreMessaggiException, ProtocolException{
  1523.         GestoreCorrelazioneApplicativaPSUtilities.applicaCorrelazione(this, correlazioneApplicativa, idApplicativo, idBustaRequest);
  1524.     }



  1525.     /**
  1526.      * Cerca nella tabella CORRELAZIONE_APPLICATIVA le correlazioni scadute
  1527.      *
  1528.      * @return Nel caso l'operazione ha successo ritorna gli id delle tabelle delle correlazioni scadute
  1529.      */
  1530.     private static final String COLUMN_SCADENZA = "SCADENZA";
  1531.     private static final String COLUMN_ORA_REGISTRAZIONE = "ORA_REGISTRAZIONE";
  1532.     public java.util.List<Long> getCorrelazioniScadute(int limit,boolean logQuery,boolean orderBy) throws GestoreMessaggiException{

  1533.         java.util.List<Long> idMsg = new java.util.ArrayList<>();

  1534.         PreparedStatement pstmtMsgScaduti = null;
  1535.         ResultSet rs = null;
  1536.         String queryString = null;
  1537.         try{    
  1538.             StateMessage stateMSG = (StateMessage)this.state;
  1539.             Connection connectionDB = stateMSG.getConnectionDB();

  1540.             /** Query per Ricerca messaggi scaduti
  1541.              Algoritmo:
  1542.                 if( scaduto < now )
  1543.                    msgScaduto
  1544.              */
  1545.             java.sql.Timestamp nowT = DateManager.getTimestamp();


  1546.             queryString = buildQueryCorrelazioniScadute(limit, orderBy);
  1547.             /** System.out.println("QUERY CORRELAZIONE APPLICATIVA IS: ["+queryString+"] 1["+nowT+"]"); */


  1548.             pstmtMsgScaduti = connectionDB.prepareStatement(queryString);
  1549.             pstmtMsgScaduti.setTimestamp(1,nowT);

  1550.             long startDateSQLCommand = DateManager.getTimeMillis();
  1551.             if(logQuery) {
  1552.                 String debugS = "[QUERY] (CorrelazioneApplicativa.scaduta) ["+queryString+"] 1["+nowT+"]...";
  1553.                 this.log.debug(debugS);
  1554.             }
  1555.             rs = pstmtMsgScaduti.executeQuery();
  1556.             long endDateSQLCommand = DateManager.getTimeMillis();
  1557.             long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  1558.             if(logQuery) {
  1559.                 String debugS = "[QUERY] (CorrelazioneApplicativa.scaduta) ["+queryString+"] 1["+nowT+"] effettuata in "+secondSQLCommand+" secondi";
  1560.                 this.log.debug(debugS);
  1561.             }

  1562.             while(rs.next()){
  1563.                 if(!readCorrelazioniScaduteEngine(idMsg, rs, limit)) {
  1564.                     break;
  1565.                 }
  1566.             }
  1567.             rs.close();
  1568.             pstmtMsgScaduti.close();

  1569.             return idMsg;

  1570.         } catch(Exception e) {
  1571.             String errorMsg = "[GestoreCorrelazioneApplicativa.getCorrelazioniScadute] errore, queryString["+queryString+"]: "+e.getMessage();
  1572.             try{
  1573.                 if(rs != null)
  1574.                     rs.close();
  1575.             } catch(Exception er) {
  1576.                 // close
  1577.             }
  1578.             try{
  1579.                 if(pstmtMsgScaduti != null)
  1580.                     pstmtMsgScaduti.close();
  1581.             } catch(Exception er) {
  1582.                 // close
  1583.             }
  1584.             this.log.error(errorMsg);
  1585.             throw new GestoreMessaggiException(errorMsg,e);
  1586.         }  
  1587.     }
  1588.     private String buildQueryCorrelazioniScadute(int limit,boolean orderBy) throws SQLQueryObjectException{
  1589.         String queryString = null;
  1590.         if(Configurazione.getSqlQueryObjectType()==null){
  1591.             StringBuilder query = new StringBuilder();
  1592.             query.append("SELECT id FROM ");
  1593.             query.append(GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA);
  1594.             query.append(" WHERE "+COLUMN_SCADENZA+" is not null AND "+COLUMN_SCADENZA+" < ?");
  1595.             queryString = query.toString();
  1596.         }else{
  1597.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  1598.             sqlQueryObject.addSelectField("id");
  1599.             sqlQueryObject.addSelectField(COLUMN_SCADENZA);
  1600.             sqlQueryObject.addFromTable(GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA);
  1601.             sqlQueryObject.addWhereCondition(COLUMN_SCADENZA+" is not null");
  1602.             sqlQueryObject.addWhereCondition(COLUMN_SCADENZA+" < ?");
  1603.             sqlQueryObject.setANDLogicOperator(true);
  1604.             if(orderBy){
  1605.                 sqlQueryObject.addOrderBy(COLUMN_SCADENZA);
  1606.                 sqlQueryObject.setSortType(true);
  1607.             }
  1608.             sqlQueryObject.setLimit(limit);
  1609.             queryString = sqlQueryObject.createSQLQuery();
  1610.         }
  1611.         return queryString;
  1612.     }
  1613.    
  1614.    
  1615.     /**
  1616.      * Cerca nella tabella CORRELAZIONE_APPLICATIVA le correlazioni 'vecchie' (rispetto all'ora di registrazione)
  1617.      *
  1618.      * @return Nel caso l'operazione ha successo ritorna gli id delle tabelle delle correlazioni 'vecchie' (rispetto all'ora di registrazione)
  1619.      */
  1620.     public java.util.List<Long> getCorrelazioniScaduteRispettoOraRegistrazione(int limit,long scadenzaMsg,boolean logQuery,boolean orderBy,boolean escludiCorrelazioniConScadenza) throws GestoreMessaggiException{

  1621.         java.util.List<Long> idMsg = new java.util.ArrayList<>();
  1622.        
  1623.         PreparedStatement pstmtMsgScaduti = null;
  1624.         ResultSet rs = null;
  1625.         String queryString = null;
  1626.         try{    
  1627.             StateMessage stateMSG = (StateMessage)this.state;
  1628.             Connection connectionDB = stateMSG.getConnectionDB();

  1629.             /** Query per Ricerca messaggi scaduti
  1630.              Algoritmo:
  1631.                 if( (now-timeout) > oraRegistrazione )
  1632.                    msgScaduto
  1633.              */
  1634.             long scadenza = DateManager.getTimeMillis() - (scadenzaMsg * 60 * 1000);
  1635.             java.sql.Timestamp scandenzaT = new java.sql.Timestamp(scadenza);

  1636.             queryString = buildQueryCorrelazioniScaduteRispettoOraRegistrazione(limit, orderBy, escludiCorrelazioniConScadenza);
  1637.             /** System.out.println("QUERY CORRELAZIONE APPLICATIVA IS: ["+queryString+"] 1["+nowT+"]"); */


  1638.             pstmtMsgScaduti = connectionDB.prepareStatement(queryString);
  1639.             pstmtMsgScaduti.setTimestamp(1,scandenzaT);

  1640.             long startDateSQLCommand = DateManager.getTimeMillis();
  1641.             if(logQuery) {
  1642.                 String sDebug = "[QUERY] (CorrelazioneApplicativa.storiche) ["+queryString+"] 1["+scandenzaT+"]...";
  1643.                 this.log.debug(sDebug);
  1644.             }
  1645.             rs = pstmtMsgScaduti.executeQuery();
  1646.             long endDateSQLCommand = DateManager.getTimeMillis();
  1647.             long secondSQLCommand = (endDateSQLCommand - startDateSQLCommand) / 1000;
  1648.             if(logQuery) {
  1649.                 String sDebug = "[QUERY] (CorrelazioneApplicativa.storiche) ["+queryString+"] 1["+scandenzaT+"] effettuata in "+secondSQLCommand+" secondi";
  1650.                 this.log.debug(sDebug);
  1651.             }

  1652.             while(rs.next()){
  1653.                 if(!readCorrelazioniScaduteEngine(idMsg, rs, limit)) {
  1654.                     break;
  1655.                 }
  1656.             }
  1657.             rs.close();
  1658.             pstmtMsgScaduti.close();

  1659.             return idMsg;

  1660.         } catch(Exception e) {
  1661.             String errorMsg = "[GestoreCorrelazioneApplicativa.getCorrelazioniStoriche] errore, queryString["+queryString+"]: "+e.getMessage();
  1662.             try{
  1663.                 if(rs != null)
  1664.                     rs.close();
  1665.             } catch(Exception er) {
  1666.                 // close
  1667.             }
  1668.             try{
  1669.                 if(pstmtMsgScaduti != null)
  1670.                     pstmtMsgScaduti.close();
  1671.             } catch(Exception er) {
  1672.                 // close
  1673.             }
  1674.             this.log.error(errorMsg);
  1675.             throw new GestoreMessaggiException(errorMsg,e);
  1676.         }  
  1677.     }
  1678.     private String buildQueryCorrelazioniScaduteRispettoOraRegistrazione(int limit,boolean orderBy, boolean escludiCorrelazioniConScadenza) throws SQLQueryObjectException{
  1679.         String queryString = null;
  1680.         if(Configurazione.getSqlQueryObjectType()==null){
  1681.             StringBuilder query = new StringBuilder();
  1682.             query.append("SELECT id FROM ");
  1683.             query.append(GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA);
  1684.             query.append(" WHERE "+COLUMN_ORA_REGISTRAZIONE+" < ?");
  1685.             if(escludiCorrelazioniConScadenza){
  1686.                 query.append(" AND "+COLUMN_SCADENZA+" is null");
  1687.             }
  1688.             queryString = query.toString();
  1689.         }else{
  1690.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(Configurazione.getSqlQueryObjectType());
  1691.             sqlQueryObject.addSelectField("id");
  1692.             sqlQueryObject.addSelectField(COLUMN_SCADENZA);
  1693.             sqlQueryObject.addFromTable(GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA);
  1694.             sqlQueryObject.addWhereCondition(COLUMN_ORA_REGISTRAZIONE+" < ?");
  1695.             if(escludiCorrelazioniConScadenza){
  1696.                 sqlQueryObject.addWhereCondition(COLUMN_SCADENZA+" is null");
  1697.             }
  1698.             sqlQueryObject.setANDLogicOperator(true);
  1699.             if(orderBy){
  1700.                 sqlQueryObject.addOrderBy(COLUMN_ORA_REGISTRAZIONE);
  1701.                 sqlQueryObject.setSortType(true);
  1702.             }
  1703.             sqlQueryObject.setLimit(limit);
  1704.             queryString = sqlQueryObject.createSQLQuery();
  1705.         }
  1706.         return queryString;
  1707.     }
  1708.    
  1709.     private boolean readCorrelazioniScaduteEngine(java.util.List<Long> idMsg, ResultSet rs, int limit) throws SQLException {
  1710.         int countLimit = 0;
  1711.         if(Configurazione.getSqlQueryObjectType()==null){
  1712.             // LIMIT Applicativo
  1713.             idMsg.add(rs.getLong("id"));
  1714.             countLimit++;
  1715.             if(countLimit==limit) {
  1716.                 return false;
  1717.             }
  1718.         }
  1719.         else{
  1720.             idMsg.add(rs.getLong("id"));
  1721.         }
  1722.         return true;
  1723.     }

  1724.    
  1725.     /**
  1726.      * Ritorna l'id e l'id di correlazione applicativa.
  1727.      *
  1728.      */
  1729.     public String[] getIDMappingCorrelazioneApplicativa(long idCorrelazioneApplicativa)throws GestoreMessaggiException{

  1730.         PreparedStatement pstmtReadMSG= null;
  1731.         ResultSet rs = null;
  1732.         try{

  1733.             StateMessage stateMSG = (StateMessage)this.state;
  1734.             Connection connectionDB = stateMSG.getConnectionDB();

  1735.             String query = "SELECT "+GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA_COLUMN_ID_MESSAGGIO+","+GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA_COLUMN_ID_APPLICATIVO+"  FROM "+GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA+" WHERE id=?";
  1736.             /** log.debug("Query: "+query); */
  1737.             pstmtReadMSG=connectionDB.prepareStatement(query);
  1738.             pstmtReadMSG.setLong(1,idCorrelazioneApplicativa);
  1739.             rs = pstmtReadMSG.executeQuery();
  1740.             if(rs.next()){
  1741.                 String [] s = new String[2];
  1742.                 s[0] = rs.getString(GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA_COLUMN_ID_MESSAGGIO);
  1743.                 s[1] = rs.getString(GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA_COLUMN_ID_APPLICATIVO);
  1744.                 rs.close();
  1745.                 pstmtReadMSG.close();
  1746.                 return s;
  1747.             }
  1748.             rs.close();
  1749.             pstmtReadMSG.close();
  1750.             throw new CoreException("CorrelazioneApplicativa con id["+idCorrelazioneApplicativa+"] non trovata");
  1751.         }
  1752.         catch(Exception e) {
  1753.             String errorMsg = "GestoreCorrelazioneApplicativa, error getIDMappingCorrelazioneApplicativa ["+idCorrelazioneApplicativa+"] : "+e.getMessage();        
  1754.             try{
  1755.                 if(rs != null)
  1756.                     rs.close();
  1757.             } catch(Exception er) {
  1758.                 // close
  1759.             }
  1760.             try{
  1761.                 if(pstmtReadMSG != null)
  1762.                     pstmtReadMSG.close();
  1763.             } catch(Exception er) {
  1764.                 // close
  1765.             }
  1766.             this.log.error(errorMsg);
  1767.             throw new GestoreMessaggiException(errorMsg,e);
  1768.         }  

  1769.     }
  1770.    

  1771.     /**
  1772.      * Elimina la correlazione applicativa gestito da OpenSPCoop.
  1773.      *
  1774.      */
  1775.     public void deleteCorrelazioneApplicativa(long idCorrelazioneApplicativa)throws GestoreMessaggiException{

  1776.         PreparedStatement pstmtDeleteMSG= null;
  1777.         try{

  1778.             StateMessage stateMSG = (StateMessage)this.state;
  1779.             Connection connectionDB = stateMSG.getConnectionDB();

  1780.             String query = "DELETE FROM "+GestoreCorrelazioneApplicativa.CORRELAZIONE_APPLICATIVA+" WHERE id=?";
  1781.             /** log.debug("Query: "+query); */
  1782.             pstmtDeleteMSG=connectionDB.prepareStatement(query);
  1783.             pstmtDeleteMSG.setLong(1,idCorrelazioneApplicativa);
  1784.             pstmtDeleteMSG.execute();
  1785.             pstmtDeleteMSG.close();
  1786.         }
  1787.         catch(Exception e) {
  1788.             String errorMsg = "GestoreCorrelazioneApplicativa, error deleteCorrelazione ["+idCorrelazioneApplicativa+"] : "+e.getMessage();    
  1789.             try{
  1790.                 if(pstmtDeleteMSG != null)
  1791.                     pstmtDeleteMSG.close();
  1792.             } catch(Exception er) {
  1793.                 // close
  1794.             }
  1795.             this.log.error(errorMsg);
  1796.             throw new GestoreMessaggiException(errorMsg,e);
  1797.         }  

  1798.     }

  1799.     /**
  1800.      * id precedentemente correlato alla richiesta applicativa
  1801.      *
  1802.      * @return id precedentemente correlato alla richiesta applicativa
  1803.      */
  1804.     public String getIdBustaCorrelato() {
  1805.         return this.idBustaCorrelato;
  1806.     }
  1807.     public ErroreIntegrazione getErrore() {
  1808.         return this.errore;
  1809.     }


  1810.     public String getIdCorrelazione() {
  1811.         return this.idCorrelazione;
  1812.     }

  1813.     private static final boolean RICHIESTA = true;
  1814.     private static final boolean RISPOSTA = false;
  1815.     private static final boolean BLOCCA = true;
  1816.     private static final boolean ACCETTA = false;
  1817.     public boolean isTruncateEnabled(boolean request, boolean blocca) {
  1818.         if(blocca) {
  1819.             if(request) {
  1820.                 return this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateRequest>0 &&
  1821.                         this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateRequest<this.maxLengthCorrelazioneApplicativa;
  1822.             }
  1823.             else {
  1824.                 return this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateResponse>0 &&
  1825.                         this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateResponse<this.maxLengthCorrelazioneApplicativa;
  1826.             }
  1827.         }
  1828.         else {
  1829.             if(request) {
  1830.                 return this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateRequest>0 &&
  1831.                         this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateRequest<this.maxLengthCorrelazioneApplicativa;
  1832.             }
  1833.             else {
  1834.                 return this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateResponse>0 &&
  1835.                         this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateResponse<this.maxLengthCorrelazioneApplicativa;
  1836.             }
  1837.         }
  1838.     }
  1839.     public String truncate(String id, boolean request, boolean blocca) {
  1840.         if(blocca) {
  1841.             if(request) {
  1842.                 return id.substring(0, this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateRequest);
  1843.             }
  1844.             else {
  1845.                 return id.substring(0, this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaBloccaTruncateResponse);
  1846.             }
  1847.         }
  1848.         else {
  1849.             if(request) {
  1850.                 return id.substring(0, this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateRequest);
  1851.             }
  1852.             else {
  1853.                 return id.substring(0, this.maxLengthExceededCorrelazioneApplicativaIdentificazioneFallitaAccettaTruncateResponse);
  1854.             }
  1855.         }
  1856.     }
  1857. }