ConnettoreNULLEcho.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.connettori;

  21. import java.sql.Connection;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.Map;

  27. import org.openspcoop2.core.config.ResponseCachingConfigurazione;
  28. import org.openspcoop2.core.constants.CostantiConnettori;
  29. import org.openspcoop2.core.constants.CostantiLabel;
  30. import org.openspcoop2.core.constants.TipoPdD;
  31. import org.openspcoop2.core.id.IDSoggetto;
  32. import org.openspcoop2.core.registry.constants.CostantiRegistroServizi;
  33. import org.openspcoop2.core.transazioni.constants.TipoMessaggio;
  34. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  35. import org.openspcoop2.message.OpenSPCoop2MessageParseResult;
  36. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  37. import org.openspcoop2.message.constants.Costanti;
  38. import org.openspcoop2.message.constants.MessageRole;
  39. import org.openspcoop2.message.constants.MessageType;
  40. import org.openspcoop2.message.soap.TunnelSoapUtils;
  41. import org.openspcoop2.pdd.config.DBManager;
  42. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  43. import org.openspcoop2.pdd.config.Resource;
  44. import org.openspcoop2.pdd.core.Utilities;
  45. import org.openspcoop2.protocol.engine.builder.Imbustamento;
  46. import org.openspcoop2.protocol.engine.builder.Sbustamento;
  47. import org.openspcoop2.protocol.engine.driver.ProfiloDiCollaborazione;
  48. import org.openspcoop2.protocol.engine.driver.RepositoryBuste;
  49. import org.openspcoop2.protocol.engine.validator.Validatore;
  50. import org.openspcoop2.protocol.engine.validator.ValidazioneSintattica;
  51. import org.openspcoop2.protocol.sdk.Busta;
  52. import org.openspcoop2.protocol.sdk.BustaRawContent;
  53. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  54. import org.openspcoop2.protocol.sdk.Integrazione;
  55. import org.openspcoop2.protocol.sdk.ProtocolMessage;
  56. import org.openspcoop2.protocol.sdk.Riscontro;
  57. import org.openspcoop2.protocol.sdk.Trasmissione;
  58. import org.openspcoop2.protocol.sdk.config.IProtocolManager;
  59. import org.openspcoop2.protocol.sdk.constants.FaseImbustamento;
  60. import org.openspcoop2.protocol.sdk.constants.FaseSbustamento;
  61. import org.openspcoop2.protocol.sdk.constants.RuoloMessaggio;
  62. import org.openspcoop2.protocol.sdk.constants.TipoOraRegistrazione;
  63. import org.openspcoop2.protocol.sdk.state.StatefulMessage;
  64. import org.openspcoop2.protocol.sdk.validator.IValidatoreErrori;
  65. import org.openspcoop2.protocol.sdk.validator.ProprietaValidazione;
  66. import org.openspcoop2.protocol.sdk.validator.ProprietaValidazioneErrori;
  67. import org.openspcoop2.utils.date.DateManager;
  68. import org.openspcoop2.utils.io.DumpByteArrayOutputStream;
  69. import org.openspcoop2.utils.transport.TransportUtils;
  70. import org.openspcoop2.utils.transport.http.HttpConstants;
  71. import org.openspcoop2.utils.transport.http.HttpUtilities;




  72. /**
  73.  * Classe utilizzata per effettuare consegne di messaggi Soap, attraverso
  74.  * l'invocazione di un server http.
  75.  *
  76.  *
  77.  * @author Poli Andrea (apoli@link.it)
  78.  * @author $Author$
  79.  * @version $Rev$, $Date$
  80.  */

  81. public class ConnettoreNULLEcho extends ConnettoreBaseWithResponse {
  82.    
  83.     @Override
  84.     public String getProtocollo() {
  85.         return "";
  86.     }
  87.    
  88.     public static final String LOCATION = "govway://echo";
  89.    
  90.     private DumpByteArrayOutputStream requestBout = null;
  91.    
  92.    
  93.    


  94.     /* ********  METODI  ******** */

  95.     @Override
  96.     protected boolean initializePreSend(ResponseCachingConfigurazione responseCachingConfig, ConnettoreMsg request) {
  97.        
  98.         if(this.initialize(request, false, responseCachingConfig)==false){
  99.             return false;
  100.         }
  101.        
  102.         return true;
  103.        
  104.     }
  105.    
  106.     @Override
  107.     protected boolean send(ConnettoreMsg request) {

  108.         boolean generaTrasmissione = false;
  109.         if(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE)!=null){
  110.             if("true".equalsIgnoreCase(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE).trim()))
  111.                 generaTrasmissione = true;
  112.         }
  113.         boolean generaTrasmissioneInvertita = false;
  114.         if(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE_INVERTITA)!=null){
  115.             if("true".equalsIgnoreCase(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE_INVERTITA).trim()))
  116.                 generaTrasmissioneInvertita = true;
  117.         }
  118.         boolean generaTrasmissioneAndataRitorno = false;
  119.         if(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE_ANDATA_RITORNO)!=null){
  120.             if("true".equalsIgnoreCase(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE_ANDATA_RITORNO).trim()))
  121.                 generaTrasmissioneAndataRitorno = true;
  122.         }
  123.        
  124.        
  125.         this.codice = 200;
  126.         DBManager dbManager = DBManager.getInstance();
  127.         Resource resource = null;
  128.        
  129.         StatefulMessage state = new StatefulMessage(null, this.logger.getLogger());
  130.        
  131.         ValidazioneSintattica validatoreSintattico = null;
  132.         Validatore validatoreProtocollo = null;
  133.         @SuppressWarnings("unused")
  134.         BustaRawContent<?> headerProtocolloRisposta = null;
  135.         String protocol = null;
  136.         try{
  137.             IProtocolFactory<?> protocolFactory = this.getProtocolFactory();
  138.             IProtocolManager protocolManager = protocolFactory.createProtocolManager();
  139.             protocol = protocolFactory.getProtocol();
  140.            
  141.             // Tipologia di servizio
  142.             MessageType requestMessageType = this.requestMsg.getMessageType();
  143.             OpenSPCoop2SoapMessage soapMessageRequest = null;
  144.             if(this.debug)
  145.                 this.logger.debug("Tipologia Servizio: "+this.requestMsg.getServiceBinding());
  146.             if(this.isSoap){
  147.                 soapMessageRequest = this.requestMsg.castAsSoap();
  148.             }
  149.            
  150.            
  151.             // Collezione header di trasporto per dump
  152.             Map<String, List<String>> propertiesTrasportoDebug = null;
  153.             if(this.isDumpBinarioRichiesta()) {
  154.                 propertiesTrasportoDebug = new HashMap<>();
  155.             }
  156.            
  157.            
  158.             // Impostazione Content-Type
  159.             String contentTypeRichiesta = null;
  160.             if(this.debug)
  161.                 this.logger.debug("Impostazione content type...");
  162.             if(this.isSoap){
  163.                 if(this.sbustamentoSoap && soapMessageRequest.countAttachments()>0 && TunnelSoapUtils.isTunnelOpenSPCoopSoap(soapMessageRequest)){
  164.                     contentTypeRichiesta = TunnelSoapUtils.getContentTypeTunnelOpenSPCoopSoap(soapMessageRequest.getSOAPBody());
  165.                 }else{
  166.                     contentTypeRichiesta = this.requestMsg.getContentType();
  167.                 }
  168.                 if(contentTypeRichiesta==null){
  169.                     throw new Exception("Content-Type del messaggio da spedire non definito");
  170.                 }
  171.             }
  172.             else{
  173.                 contentTypeRichiesta = this.requestMsg.getContentType();
  174.                 // Content-Type non obbligatorio in REST
  175.             }
  176.             if(this.debug)
  177.                 this.logger.info("Impostazione Content-Type ["+contentTypeRichiesta+"]",false);
  178.             if(contentTypeRichiesta!=null){
  179.                 setRequestHeader(HttpConstants.CONTENT_TYPE, contentTypeRichiesta, this.logger, propertiesTrasportoDebug);
  180.             }
  181.            
  182.            
  183.            
  184.             // Impostazione timeout
  185.             if(this.debug)
  186.                 this.logger.debug("Impostazione timeout...");
  187.             int readConnectionTimeout = -1;
  188.             boolean readConnectionTimeoutConfigurazioneGlobale = true;
  189.             if(this.properties.get(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT)!=null){
  190.                 try{
  191.                     readConnectionTimeout = Integer.parseInt(this.properties.get(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT));
  192.                     readConnectionTimeoutConfigurazioneGlobale = this.properties.containsKey(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT_GLOBALE);
  193.                 }catch(Exception e){
  194.                     this.logger.error("Parametro "+CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT+" errato",e);
  195.                 }
  196.             }
  197.             if(readConnectionTimeout==-1){
  198.                 readConnectionTimeout = HttpUtilities.HTTP_READ_CONNECTION_TIMEOUT;
  199.             }
  200.             if(this.debug)
  201.                 this.logger.info("Impostazione read timeout ["+readConnectionTimeout+"]",false);
  202.            
  203.            
  204.             // Impostazione Proprieta del trasporto
  205.             if(this.debug)
  206.                 this.logger.debug("Impostazione header di trasporto...");
  207.             this.forwardHttpRequestHeader();
  208.             if(this.propertiesTrasporto != null){
  209.                 Iterator<String> keys = this.propertiesTrasporto.keySet().iterator();
  210.                 while (keys.hasNext()) {
  211.                     String key = (String) keys.next();
  212.                     List<String> values = this.propertiesTrasporto.get(key);
  213.                     if(this.debug) {
  214.                         if(values!=null && !values.isEmpty()) {
  215.                             for (String value : values) {
  216.                                 this.logger.info("Set Transport Header ["+key+"]=["+value+"]",false);
  217.                             }
  218.                         }
  219.                     }
  220.                    
  221.                     setRequestHeader(key, values, this.logger, propertiesTrasportoDebug);
  222.                 }
  223.             }
  224.            
  225.            
  226.            
  227.             // Aggiunga del SoapAction Header in caso di richiesta SOAP
  228.             // spostato sotto il forwardHeader per consentire alle trasformazioni di modificarla
  229.             if(this.isSoap && this.sbustamentoSoap == false){
  230.                 if(this.debug)
  231.                     this.logger.debug("Impostazione soap action...");
  232.                 boolean existsTransportProperties = false;
  233.                 if(TransportUtils.containsKey(this.propertiesTrasporto, Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION)){
  234.                     this.soapAction = TransportUtils.getFirstValue(this.propertiesTrasporto, Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION);
  235.                     existsTransportProperties = (this.soapAction!=null);
  236.                 }
  237.                 if(!existsTransportProperties) {
  238.                     this.soapAction = soapMessageRequest.getSoapAction();
  239.                 }
  240.                 if(this.soapAction==null){
  241.                     this.soapAction="\"OpenSPCoop\"";
  242.                 }
  243.                 if(MessageType.SOAP_11.equals(this.requestMsg.getMessageType()) && !existsTransportProperties){
  244.                     // NOTA non quotare la soap action, per mantenere la trasparenza della PdD
  245.                     setRequestHeader(Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION,this.soapAction, propertiesTrasportoDebug);
  246.                 }
  247.                 if(this.debug)
  248.                     this.logger.info("SOAP Action inviata ["+this.soapAction+"]",false);
  249.             }
  250.            
  251.            
  252.            
  253.             // SIMULAZIONE WRITE_TO
  254.             //this.response = request.getRequestMessage();
  255.             boolean consumeRequestMessage = true;
  256.             if(this.debug)
  257.                 this.logger.debug("Serializzazione (consume-request-message:"+consumeRequestMessage+")...");
  258.             if(this.isDumpBinarioRichiesta()) {
  259.                 this.requestBout = new DumpByteArrayOutputStream(this.dumpBinario_soglia, this.dumpBinario_repositoryFile, this.idTransazione,
  260.                         "NullEcho-"+TipoMessaggio.RICHIESTA_USCITA_DUMP_BINARIO.getValue());
  261.                
  262.                 this.emitDiagnosticStartDumpBinarioRichiestaUscita();
  263.                
  264.                 if(this.isSoap && this.sbustamentoSoap){
  265.                     this.logger.debug("Sbustamento...");
  266.                     TunnelSoapUtils.sbustamentoMessaggio(soapMessageRequest,this.requestBout);
  267.                 }else{
  268.                     this.requestMsg.writeTo(this.requestBout, consumeRequestMessage);
  269.                 }
  270.                 this.requestBout.flush();
  271.                 this.requestBout.close();
  272.                                    
  273.                 this.dataRichiestaInoltrata = DateManager.getDate();
  274.                
  275.                 this.dumpBinarioRichiestaUscita(this.requestBout, requestMessageType, contentTypeRichiesta, this.location, propertiesTrasportoDebug);
  276.             }
  277.             else {
  278.                 this.requestBout = new DumpByteArrayOutputStream(this.dumpBinario_soglia, this.dumpBinario_repositoryFile, this.idTransazione,
  279.                         "NullEcho-"+TipoMessaggio.RICHIESTA_USCITA_DUMP_BINARIO.getValue());
  280.                 if(this.isSoap && this.sbustamentoSoap){
  281.                     this.logger.debug("Sbustamento...");
  282.                     TunnelSoapUtils.sbustamentoMessaggio(soapMessageRequest,this.requestBout);
  283.                 }else{
  284.                     this.requestMsg.writeTo(this.requestBout, consumeRequestMessage);
  285.                 }
  286.                 this.requestBout.flush();
  287.                 this.requestBout.close();
  288.                
  289.                 this.dataRichiestaInoltrata = DateManager.getDate();
  290.             }
  291.            
  292.            
  293.            
  294.            
  295.            
  296.            
  297.             /* ------------  PostOutRequestHandler ------------- */
  298.             this.postOutRequest();
  299.            
  300.            
  301.            
  302.             /* ------------  PreInResponseHandler ------------- */
  303.             this.preInResponse();
  304.            
  305.             // Lettura risposta parametri NotifierInputStream per la risposta
  306.             org.openspcoop2.utils.io.notifier.NotifierInputStreamParams notifierInputStreamParams = null;
  307.             if(this.preInResponseContext!=null){
  308.                 notifierInputStreamParams = this.preInResponseContext.getNotifierInputStreamParams();
  309.             }
  310.            
  311.             if(this.requestBout.isSerializedOnFileSystem()) {
  312.                 //System.out.println("FROM FILE ["+this.requestBout.getSerializedFile()+"]");
  313.                 this.isResponse = new java.io.FileInputStream(this.requestBout.getSerializedFile());
  314.             }
  315.             else {
  316.                 //System.out.println("FROM BUFF ["+this.requestBout.size()+"]");
  317.                 this.isResponse = new java.io.ByteArrayInputStream(this.requestBout.toByteArray());
  318.             }
  319.            
  320.             this.normalizeInputStreamResponse(readConnectionTimeout, readConnectionTimeoutConfigurazioneGlobale);
  321.            
  322.             this.initCheckContentTypeConfiguration();
  323.            
  324.             this.messageTypeResponse = this.requestMsg.getMessageType();
  325.             this.tipoRisposta = this.requestMsg.getContentType();
  326.            
  327.             if(this.isDumpBinarioRisposta()){
  328.                 this.dumpResponse(this.propertiesTrasportoRisposta);
  329.             }
  330.            
  331.             if(this.isResponse!=null) {
  332.                 this.emitDiagnosticResponseRead(this.isResponse);
  333.             }
  334.            
  335.             OpenSPCoop2MessageFactory messageFactory = Utilities.getOpenspcoop2MessageFactory(this.logger.getLogger(),this.requestMsg, this.requestInfo, MessageRole.RESPONSE);
  336.             OpenSPCoop2MessageParseResult pr = messageFactory.createMessage(this.messageTypeResponse,MessageRole.RESPONSE,
  337.                     this.requestMsg.getContentType(),
  338.                     this.isResponse,notifierInputStreamParams,
  339.                     this.openspcoopProperties.getAttachmentsProcessingMode());
  340.             // Non funziona con gli attachments: this.responseMsg = OpenSPCoop2MessageFactory.getMessageFactory().createMessage(request.getRequestMessage().getVersioneSoap(),(bout.toByteArray()),notifierInputStreamParams);
  341.             if(pr.getParseException()!=null){
  342.                 this.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION, pr.getParseException());
  343.             }
  344.             this.responseMsg = pr.getMessage_throwParseException();
  345.            
  346.             validatoreSintattico = new ValidazioneSintattica(this.getPddContext(),state,this.responseMsg, this.openspcoopProperties.isReadQualifiedAttribute(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD), protocolFactory);

  347.             if(validatoreSintattico.verifyProtocolPresence(TipoPdD.APPLICATIVA,null,RuoloMessaggio.RISPOSTA) &&
  348.                     !CostantiLabel.SDI_PROTOCOL_NAME.equals(protocolFactory.getProtocol())){ // evitare sdi per far funzionare il protocollo sdi con la sonda.
  349.                
  350.                 // getBusta
  351.                 ProprietaValidazione property = new ProprietaValidazione();
  352.                 property.setValidazioneConSchema(false);
  353.                 property.setValidazioneProfiloCollaborazione(false);
  354.                 property.setValidazioneManifestAttachments(false);
  355.                
  356.                 validatoreProtocollo = new Validatore(this.responseMsg,this.getPddContext(),property,null,
  357.                         this.openspcoopProperties.isReadQualifiedAttribute(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD), protocolFactory);
  358.                
  359.                 if(validatoreProtocollo.validazioneSintattica() == false){
  360.                     throw new Exception("Busta non presente: "+validatoreProtocollo.getErrore().getDescrizione(protocolFactory));
  361.                 }
  362.                
  363.                 // Leggo busta di richiesta
  364.                 Busta busta = validatoreProtocollo.getBusta();
  365.                
  366.                 // informazione spcoopErrore
  367.                 IValidatoreErrori validatoreErrori = protocolFactory.createValidatoreErrori(state);
  368.                 ProprietaValidazioneErrori pValidazioneErrori = new ProprietaValidazioneErrori();
  369.                 pValidazioneErrori.setIgnoraEccezioniNonGravi(protocolManager.isIgnoraEccezioniNonGravi());
  370.                 boolean isBustaSPCoopErrore = validatoreErrori.isBustaErrore(busta,this.responseMsg,pValidazioneErrori);
  371.                
  372.                 // Gestisco il manifest se il messaggio lo possiede
  373.                 boolean gestioneManifest = false;
  374.                 // La gestione manifest non la devo fare a questo livello.
  375.                 // Se mi arriva un messaggio senza manifest, vuol dire che era disabilitata e quindi anche nella risposta non ci deve essere
  376.                 // In egual misura se arriva un messaggio con manifest, significa che ci deve essere anche nella risposta
  377.                 // Poiche' la risposta e' esattamente uguale (nel body e negli allegati) alla richiesta,
  378.                 // venendo costruita dai bytes della richiesta
  379. //              if(this.responseMsg.countAttachments()>0){
  380. //                  javax.xml.soap.SOAPBody soapBody = this.responseMsg.getSOAPBody();
  381. //                  if(soapBody!=null){
  382. //                      Node childNode = org.openspcoop2.message.SoapUtils.getFirstNotEmptyChildNode(soapBody);
  383. //                      System.out.println("LocalName["+childNode.getLocalName()+"] ["+childNode.getNamespaceURI()+"]");
  384. //                      
  385. //                  }
  386. //              }
  387.                
  388.                 // rimozione vecchia busta
  389.                 Sbustamento sbustatore = new Sbustamento(protocolFactory,state);
  390.                 ProtocolMessage protocolMessage = sbustatore.sbustamento(this.responseMsg,this.getPddContext(),
  391.                         busta,RuoloMessaggio.RICHIESTA, gestioneManifest,
  392.                         this.openspcoopProperties.getProprietaManifestAttachments(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD),
  393.                         FaseSbustamento.PRE_CONSEGNA_RICHIESTA,this.requestInfo);
  394.                 if(protocolMessage!=null) {
  395.                     headerProtocolloRisposta = protocolMessage.getBustaRawContent();
  396.                     this.responseMsg = protocolMessage.getMessage(); // updated
  397.                 }
  398.                
  399.                 // Creo busta di risposta solo se la busta di richiesta non conteneva una busta Errore
  400.                 if(!isBustaSPCoopErrore){
  401.            
  402.                     TipoOraRegistrazione tipoOraRegistrazione = this.openspcoopProperties.getTipoTempoBusta(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD);
  403.                     Busta bustaRisposta = busta.invertiBusta(tipoOraRegistrazione,protocolFactory.createTraduttore().toString(tipoOraRegistrazione));
  404.                
  405.                     bustaRisposta.setProfiloDiCollaborazione(busta.getProfiloDiCollaborazione());
  406.                     bustaRisposta.setServizio(busta.getServizio());
  407.                     bustaRisposta.setVersioneServizio(busta.getVersioneServizio());
  408.                     bustaRisposta.setTipoServizio(busta.getTipoServizio());
  409.                     bustaRisposta.setAzione(busta.getAzione());
  410.                    
  411.                     bustaRisposta.setInoltro(busta.getInoltro(),busta.getInoltroValue());
  412.                     bustaRisposta.setConfermaRicezione(busta.isConfermaRicezione());
  413.                    
  414.                     if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ONEWAY.equals(busta.getProfiloDiCollaborazione()) &&
  415.                             busta.isConfermaRicezione() &&
  416.                             this.openspcoopProperties.isGestioneRiscontri(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD)){
  417.                         // Attendono riscontro
  418.                         Riscontro r = new Riscontro();
  419.                         r.setID(busta.getID());
  420.                         r.setOraRegistrazione(DateManager.getDate());
  421.                         r.setTipoOraRegistrazione(TipoOraRegistrazione.SINCRONIZZATO);
  422.                         bustaRisposta.addRiscontro(r);
  423.                        
  424.                     } else if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_ASIMMETRICO.equals(busta.getProfiloDiCollaborazione()) &&
  425.                             busta.getRiferimentoMessaggio()==null){
  426.                         // devo generare ricevuta
  427.                         bustaRisposta.setTipoServizioCorrelato("SPC");
  428.                         bustaRisposta.setServizioCorrelato(busta.getServizio()+"Correlato");
  429.                     } else if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO.equals(busta.getProfiloDiCollaborazione()) &&
  430.                             busta.getRiferimentoMessaggio()==null){
  431.                    
  432.                         // salvo messaggio sul database asincrono/repositoryBuste
  433.                    
  434.                         // get database
  435.                         try{
  436.                             resource = dbManager.getResource(this.openspcoopProperties.getIdentitaPortaDefault(protocolFactory.getProtocol(), this.requestInfo),"ConnettoreNullEcho",busta.getID());
  437.                         }catch(Exception e){
  438.                             throw new Exception("Risorsa non ottenibile",e);
  439.                         }
  440.                         if(resource==null)
  441.                             throw new Exception("Risorsa is null");
  442.                         if(resource.getResource() == null)
  443.                             throw new Exception("Connessione is null");
  444.                         Connection connectionDB = (Connection) resource.getResource();
  445.                         //POOL,TRANSACTIONISOLATION:connectionDB.setTransactionIsolation(DBManager.getTransactionIsolationLevel());
  446.                        
  447.                         state.setConnectionDB(connectionDB);
  448.                        
  449.                         // repository
  450.                         RepositoryBuste repositoryBuste = new RepositoryBuste(state, true,protocolFactory);
  451.                         repositoryBuste.registraBustaIntoInBox(busta, new ArrayList<>() ,
  452.                                 OpenSPCoop2Properties.getInstance().getRepositoryIntervalloScadenzaMessaggi());
  453.                         Integrazione infoIntegrazione = new Integrazione();
  454.                         infoIntegrazione.setIdModuloInAttesa(null);
  455.                         repositoryBuste.aggiornaInfoIntegrazioneIntoInBox(busta.getID(),infoIntegrazione);
  456.                    
  457.                         // asincrono
  458.                         ProfiloDiCollaborazione profiloCollaborazione = new ProfiloDiCollaborazione(state,protocolFactory);
  459.                         profiloCollaborazione.asincronoSimmetrico_registraRichiestaRicevuta(busta.getID(),busta.getCollaborazione(),
  460.                                 busta.getTipoServizioCorrelato(),busta.getServizioCorrelato(),busta.getVersioneServizioCorrelato(),true,
  461.                                 this.openspcoopProperties.getRepositoryIntervalloScadenzaMessaggi());
  462.                    
  463.                         // commit
  464.                         try{
  465.                             connectionDB.setAutoCommit(false);
  466.                             state.executePreparedStatement();
  467.                
  468.                             connectionDB.commit();
  469.                             connectionDB.setAutoCommit(true);
  470.                         }catch (Exception e) {  
  471.                             this.logger.error("Riscontrato errore durante la gestione transazione del DB per la richiesta: "+e.getMessage());
  472.                             // Rollback quanto effettuato (se l'errore e' avvenuto sul commit, o prima nell'execute delle PreparedStatement)
  473.                             try{
  474.                                 connectionDB.rollback();
  475.                             }catch(Exception er){
  476.                                 // ignore
  477.                             }
  478.                             state.closePreparedStatement(); // Chiude le PreparedStatement aperte(e non eseguite) per il save del Msg
  479.                         }finally {
  480.                             // Ripristino connessione
  481.                             try{
  482.                                 connectionDB.setAutoCommit(true);
  483.                             }catch(Exception er){
  484.                                 // ignore
  485.                             }
  486.                         }
  487.                    
  488.                     }
  489.                
  490.                     // Riferimento Messaggio
  491.                     bustaRisposta.setRiferimentoMessaggio(busta.getID());
  492.                    
  493.                     // Identificativo Messaggio
  494.                     String dominio = null;
  495.                     if(request.getConnectorProperties()!=null)
  496.                         dominio = request.getConnectorProperties().get("identificativo-porta");
  497.                     if(dominio==null){
  498.                         dominio = protocolFactory.createTraduttore().getIdentificativoPortaDefault(new IDSoggetto(busta.getTipoDestinatario(), busta.getDestinatario()));
  499.                     }
  500.                     String idBustaRisposta = null;
  501.                     Imbustamento imbustatore = new Imbustamento(this.logger.getLogger(), protocolFactory, state);
  502.                     try{
  503.                         idBustaRisposta =
  504.                             imbustatore.buildID(new IDSoggetto(busta.getTipoDestinatario(), busta.getDestinatario(), dominio),
  505.                                     null,
  506.                                     this.openspcoopProperties.getGestioneSerializableDBAttesaAttiva(),
  507.                                     this.openspcoopProperties.getGestioneSerializableDBCheckInterval(),
  508.                                     RuoloMessaggio.RISPOSTA);
  509.                     }catch(Exception e){
  510.                         // rilancio
  511.                         throw e;
  512.                     }
  513.                     bustaRisposta.setID(idBustaRisposta);
  514.                    
  515.                     if(generaTrasmissioneAndataRitorno){
  516.                         Trasmissione t = new Trasmissione();
  517.                         t.setTipoOrigine(busta.getTipoMittente());
  518.                         t.setOrigine(busta.getMittente());
  519.                         t.setIdentificativoPortaOrigine(busta.getIdentificativoPortaMittente());
  520.                         t.setIndirizzoOrigine(busta.getIndirizzoMittente());
  521.                        
  522.                         t.setTipoDestinazione(busta.getTipoDestinatario());
  523.                         t.setDestinazione(busta.getDestinatario());
  524.                         t.setIdentificativoPortaDestinazione(busta.getIdentificativoPortaDestinatario());
  525.                         t.setIndirizzoDestinazione(busta.getIndirizzoDestinatario());
  526.                        
  527.                         t.setOraRegistrazione(busta.getOraRegistrazione());
  528.                         t.setTempo(busta.getTipoOraRegistrazione(), busta.getTipoOraRegistrazioneValue());
  529.                         bustaRisposta.addTrasmissione(t);
  530.                     }
  531.                     if(generaTrasmissione || generaTrasmissioneInvertita || generaTrasmissioneAndataRitorno){
  532.                         Trasmissione t = new Trasmissione();
  533.                         if(generaTrasmissione || generaTrasmissioneAndataRitorno){
  534.                             t.setTipoOrigine(bustaRisposta.getTipoMittente());
  535.                             t.setOrigine(bustaRisposta.getMittente());
  536.                             t.setIdentificativoPortaOrigine(bustaRisposta.getIdentificativoPortaMittente());
  537.                             t.setIndirizzoOrigine(bustaRisposta.getIndirizzoMittente());
  538.                            
  539.                             t.setTipoDestinazione(bustaRisposta.getTipoDestinatario());
  540.                             t.setDestinazione(bustaRisposta.getDestinatario());
  541.                             t.setIdentificativoPortaDestinazione(bustaRisposta.getIdentificativoPortaDestinatario());
  542.                             t.setIndirizzoDestinazione(bustaRisposta.getIndirizzoDestinatario());
  543.                         }
  544.                         if(generaTrasmissioneInvertita){
  545.                             // invertita
  546.                             t.setTipoOrigine(bustaRisposta.getTipoDestinatario());
  547.                             t.setOrigine(bustaRisposta.getDestinatario());
  548.                             t.setIdentificativoPortaOrigine(bustaRisposta.getIdentificativoPortaDestinatario());
  549.                             t.setIndirizzoOrigine(bustaRisposta.getIndirizzoDestinatario());
  550.                            
  551.                             t.setTipoDestinazione(bustaRisposta.getTipoMittente());
  552.                             t.setDestinazione(bustaRisposta.getMittente());
  553.                             t.setIdentificativoPortaDestinazione(bustaRisposta.getIdentificativoPortaMittente());
  554.                             t.setIndirizzoDestinazione(bustaRisposta.getIndirizzoMittente());
  555.                         }
  556.                         t.setOraRegistrazione(bustaRisposta.getOraRegistrazione());
  557.                         t.setTempo(bustaRisposta.getTipoOraRegistrazione(), bustaRisposta.getTipoOraRegistrazioneValue());
  558.                         bustaRisposta.addTrasmissione(t);
  559.                     }
  560.                                
  561.                     // imbustamento nuova busta
  562.                     Integrazione integrazione = new Integrazione();
  563.                     integrazione.setStateless(true);
  564.                    
  565.                     ProtocolMessage protocolMessageRisposta = imbustatore.imbustamentoRisposta(this.responseMsg,this.getPddContext(),
  566.                             bustaRisposta,busta,integrazione,gestioneManifest,false,
  567.                             this.openspcoopProperties.getProprietaManifestAttachments(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD),
  568.                             FaseImbustamento.PRIMA_SICUREZZA_MESSAGGIO);
  569.                     if(protocolMessageRisposta!=null && !protocolMessageRisposta.isPhaseUnsupported()) {
  570.                         this.responseMsg = protocolMessageRisposta.getMessage(); // updated
  571.                     }
  572.                    
  573.                     protocolMessageRisposta = imbustatore.imbustamentoRisposta(this.responseMsg,this.getPddContext(),
  574.                             bustaRisposta,busta,integrazione,gestioneManifest,false,
  575.                             this.openspcoopProperties.getProprietaManifestAttachments(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD),
  576.                             FaseImbustamento.DOPO_SICUREZZA_MESSAGGIO);
  577.                     if(protocolMessageRisposta!=null && !protocolMessageRisposta.isPhaseUnsupported()) {
  578.                         this.responseMsg = protocolMessageRisposta.getMessage(); // updated
  579.                     }

  580.                 }
  581.                 else{
  582.                     // rimuovo il FAULT.
  583.                     if(this.responseMsg instanceof OpenSPCoop2SoapMessage){
  584.                         OpenSPCoop2SoapMessage soapMessage = this.responseMsg.castAsSoap();
  585.                         if(soapMessage.hasSOAPFault()){
  586.                             soapMessage.getSOAPBody().removeChild(soapMessage.getSOAPBody().getFault());
  587.                         }
  588.                     }
  589.                 }
  590.             }
  591.            
  592.             // content length
  593.             if(this.responseMsg!=null){
  594.                 this.contentLength = this.responseMsg.getIncomingMessageContentLength();
  595.             }
  596.            
  597.         }catch(Exception e){
  598.             this.eccezioneProcessamento = e;
  599.             String msgErrore = this.readExceptionMessageFromException(e);
  600.             if(this.generateErrorWithConnectorPrefix) {
  601.                 this.errore = "Riscontrato errore durante l'echo del messaggio: "+msgErrore;
  602.             }
  603.             else {
  604.                 this.errore = msgErrore;
  605.             }
  606.             this.logger.error("Riscontrato errore durante l'echo del messaggio: "+msgErrore,e);
  607.             return false;
  608.         }finally{
  609.                    
  610.             // *** GB ***
  611.             if(validatoreSintattico!=null){
  612.                 validatoreSintattico.setHeaderSOAP(null);
  613.             }
  614.             validatoreSintattico = null;
  615.             if(validatoreProtocollo!=null){
  616.                 if(validatoreProtocollo.getValidatoreSintattico()!=null){
  617.                     validatoreProtocollo.getValidatoreSintattico().setHeaderSOAP(null);
  618.                 }
  619.                 validatoreProtocollo.setValidatoreSintattico(null);
  620.             }
  621.             validatoreProtocollo = null;
  622.             headerProtocolloRisposta = null;
  623.             // *** GB ***
  624.            
  625.             // release database
  626.             dbManager.releaseResource(this.openspcoopProperties.getIdentitaPortaDefault(protocol, this.requestInfo),
  627.                     "ConnettoreNullEcho", resource);
  628.         }
  629.        
  630.         return true;
  631.     }
  632.    
  633.     private void setRequestHeader(String key, String value, ConnettoreLogger logger, Map<String, List<String>> propertiesTrasportoDebug) throws Exception {
  634.         List<String> list = new ArrayList<>();
  635.         list.add(value);
  636.         this.setRequestHeader(key, list, logger, propertiesTrasportoDebug);
  637.     }
  638.     private void setRequestHeader(String key, List<String> values, ConnettoreLogger logger, Map<String, List<String>> propertiesTrasportoDebug) throws Exception {
  639.        
  640.         if(this.debug) {
  641.             if(values!=null && !values.isEmpty()) {
  642.                 for (String value : values) {
  643.                     this.logger.info("Set proprietà trasporto ["+key+"]=["+value+"]",false);        
  644.                 }
  645.             }
  646.         }
  647.         setRequestHeader(key, values, propertiesTrasportoDebug);
  648.        
  649.     }
  650.     @Override
  651.     protected void setRequestHeader(String key,List<String> values) throws Exception {
  652.         this.propertiesTrasportoRisposta.put(key, values);
  653.     }
  654.    
  655.     /**
  656.      * Ritorna l'informazione su dove il connettore sta spedendo il messaggio
  657.      *
  658.      * @return location di inoltro del messaggio
  659.      */
  660.     @Override
  661.     public String getLocation() throws ConnettoreException {
  662.         // Il connettore NULL_ECHO ho possiede possibilita' di consegnare su di una url
  663.         //return ConnettoreUtils.buildLocationWithURLBasedParameter(this.requestMsg, this.propertiesUrlBased, LOCATION);
  664.         return LOCATION;
  665.     }

  666.     @Override
  667.     public void disconnect() throws ConnettoreException {
  668.         try {
  669.             if(this.requestBout!=null) {
  670.                 this.requestBout.clearResources();
  671.             }
  672.         }catch(Throwable t) {
  673.             this.logger.error("Release resources failed: "+t.getMessage(),t);
  674.         }
  675.     }
  676. }