ConnettoreStatus.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.io.ByteArrayInputStream;
  22. import java.sql.Connection;
  23. import java.util.ArrayList;
  24. import java.util.Date;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Map;

  29. import org.apache.commons.lang.StringUtils;
  30. import org.openspcoop2.core.config.Connettore;
  31. import org.openspcoop2.core.config.PortaApplicativa;
  32. import org.openspcoop2.core.config.PortaApplicativaServizioApplicativo;
  33. import org.openspcoop2.core.config.PortaDelegata;
  34. import org.openspcoop2.core.config.PortaDelegataAzione;
  35. import org.openspcoop2.core.config.ResponseCachingConfigurazione;
  36. import org.openspcoop2.core.config.ServizioApplicativo;
  37. import org.openspcoop2.core.config.driver.DriverConfigurazioneException;
  38. import org.openspcoop2.core.config.driver.DriverConfigurazioneNotFound;
  39. import org.openspcoop2.core.constants.CostantiConnettori;
  40. import org.openspcoop2.core.constants.CostantiLabel;
  41. import org.openspcoop2.core.constants.TipiConnettore;
  42. import org.openspcoop2.core.constants.TipoPdD;
  43. import org.openspcoop2.core.controllo_traffico.beans.DatiTransazione;
  44. import org.openspcoop2.core.controllo_traffico.beans.RisultatoStatistico;
  45. import org.openspcoop2.core.controllo_traffico.constants.TipoPeriodoStatistico;
  46. import org.openspcoop2.core.id.IDServizio;
  47. import org.openspcoop2.core.id.IDServizioApplicativo;
  48. import org.openspcoop2.core.id.IDSoggetto;
  49. import org.openspcoop2.core.mapping.MappingErogazionePortaApplicativa;
  50. import org.openspcoop2.core.mapping.MappingFruizionePortaDelegata;
  51. import org.openspcoop2.core.registry.constants.CostantiRegistroServizi;
  52. import org.openspcoop2.core.registry.driver.DriverRegistroServiziException;
  53. import org.openspcoop2.core.registry.driver.IDServizioFactory;
  54. import org.openspcoop2.core.transazioni.constants.TipoMessaggio;
  55. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  56. import org.openspcoop2.message.OpenSPCoop2MessageParseResult;
  57. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  58. import org.openspcoop2.message.constants.Costanti;
  59. import org.openspcoop2.message.constants.MessageRole;
  60. import org.openspcoop2.message.constants.MessageType;
  61. import org.openspcoop2.message.soap.TunnelSoapUtils;
  62. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  63. import org.openspcoop2.pdd.config.DBManager;
  64. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  65. import org.openspcoop2.pdd.config.Resource;
  66. import org.openspcoop2.pdd.core.Utilities;
  67. import org.openspcoop2.pdd.core.controllo_traffico.policy.GestoreCacheControlloTraffico;
  68. import org.openspcoop2.protocol.engine.builder.Imbustamento;
  69. import org.openspcoop2.protocol.engine.builder.Sbustamento;
  70. import org.openspcoop2.protocol.engine.driver.ProfiloDiCollaborazione;
  71. import org.openspcoop2.protocol.engine.driver.RepositoryBuste;
  72. import org.openspcoop2.protocol.engine.validator.Validatore;
  73. import org.openspcoop2.protocol.engine.validator.ValidazioneSintattica;
  74. import org.openspcoop2.protocol.sdk.Busta;
  75. import org.openspcoop2.protocol.sdk.BustaRawContent;
  76. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  77. import org.openspcoop2.protocol.sdk.Integrazione;
  78. import org.openspcoop2.protocol.sdk.ProtocolMessage;
  79. import org.openspcoop2.protocol.sdk.Riscontro;
  80. import org.openspcoop2.protocol.sdk.Trasmissione;
  81. import org.openspcoop2.protocol.sdk.config.IProtocolManager;
  82. import org.openspcoop2.protocol.sdk.constants.FaseImbustamento;
  83. import org.openspcoop2.protocol.sdk.constants.FaseSbustamento;
  84. import org.openspcoop2.protocol.sdk.constants.RuoloMessaggio;
  85. import org.openspcoop2.protocol.sdk.constants.TipoOraRegistrazione;
  86. import org.openspcoop2.protocol.sdk.state.StatefulMessage;
  87. import org.openspcoop2.protocol.sdk.validator.IValidatoreErrori;
  88. import org.openspcoop2.protocol.sdk.validator.ProprietaValidazione;
  89. import org.openspcoop2.protocol.sdk.validator.ProprietaValidazioneErrori;
  90. import org.openspcoop2.utils.UtilsException;
  91. import org.openspcoop2.utils.date.DateManager;
  92. import org.openspcoop2.utils.io.DumpByteArrayOutputStream;
  93. import org.openspcoop2.utils.rest.problem.JsonSerializer;
  94. import org.openspcoop2.utils.rest.problem.ProblemRFC7807;
  95. import org.openspcoop2.utils.rest.problem.XmlSerializer;
  96. import org.openspcoop2.utils.transport.TransportResponseContext;
  97. import org.openspcoop2.utils.transport.TransportUtils;
  98. import org.openspcoop2.utils.transport.http.HttpConstants;
  99. import org.openspcoop2.utils.transport.http.HttpUtilities;


  100. /**
  101.  * Classe utilizzata per ottenere lo status di una determinata
  102.  * erogazione/fruizione
  103.  *
  104.  *
  105.  * @author Tommaso Burlon (tommaso.burlon@link.it)
  106.  * @author $Author$
  107.  * @version $Rev$, $Date$
  108.  */

  109. public class ConnettoreStatus extends ConnettoreBaseWithResponse {
  110.    
  111.     @Override
  112.     public String getProtocollo() {
  113.         return "";
  114.     }
  115.    
  116.     public static final String LOCATION = "govway://status";
  117.    
  118.     private DumpByteArrayOutputStream requestBout = null;

  119.     public static String getMessage(ConnettoreStatusResponseType statusResponseType, MessageType messageTypeRequest) throws UtilsException {
  120.        
  121.         ProblemRFC7807 problemRFC7807 = new ProblemRFC7807();
  122.         problemRFC7807.setStatus(200);
  123.         problemRFC7807.setDetail("Il servizio funziona correttamente");
  124.         problemRFC7807.setTitle("Success");
  125.         problemRFC7807.setType("https://httpstatuses.com/200");
  126.        
  127.         switch(statusResponseType) {
  128.         case MODI:{
  129.             return getMessageModI(messageTypeRequest, problemRFC7807);
  130.         }
  131.         case VUOTO: return "";
  132.         case XML: {
  133.             XmlSerializer xmlSerializer = new XmlSerializer();  
  134.             return xmlSerializer.toString(problemRFC7807).replace("problem", "status");
  135.         }
  136.         case JSON: {
  137.             JsonSerializer jsonSerializer = new JsonSerializer();
  138.             return jsonSerializer.toString(problemRFC7807);
  139.         }
  140.         case TEXT: return "Il servizio funziona correttamente";
  141.         default: return null;
  142.         }
  143.     }
  144.     private static String getMessageModI(MessageType messageTypeRequest, ProblemRFC7807 problemRFC7807) throws UtilsException {
  145.         switch (messageTypeRequest) {
  146.             case SOAP_11:
  147.             case SOAP_12:
  148.             {
  149.                 XmlSerializer xmlSerializer = new XmlSerializer();  
  150.                 String p = xmlSerializer.toString(problemRFC7807, true);
  151.                 return "<?xml version='1.0' encoding='UTF-8'?>"
  152.                     + "<soapenv:Envelope xmlns:soapenv=\""+(MessageType.SOAP_11.equals(messageTypeRequest) ? Costanti.SOAP_ENVELOPE_NAMESPACE : Costanti.SOAP12_ENVELOPE_NAMESPACE)+"\">"
  153.                     + "<soapenv:Body>"
  154.                     + p
  155.                     + "</soapenv:Body>"
  156.                     + "</soapenv:Envelope>";
  157.             }
  158.             case XML:{
  159.                 XmlSerializer xmlSerializer = new XmlSerializer();  
  160.                 return xmlSerializer.toString(problemRFC7807);
  161.             }
  162.             case JSON:
  163.             case BINARY:
  164.             case MIME_MULTIPART:{
  165.                 // in futuro valutare se usare l'accept
  166.                 JsonSerializer jsonSerializer = new JsonSerializer();
  167.                 return jsonSerializer.toString(problemRFC7807);
  168.             }
  169.         }
  170.         throw new UtilsException("Message type unknown");
  171.     }
  172.    
  173.     public static String getContentType(ConnettoreStatusResponseType statusResponseType, MessageType messageTypeRequest) throws UtilsException {
  174.         switch(statusResponseType) {
  175.         case MODI: return getContentTypeModI(messageTypeRequest);
  176.         case VUOTO: return null;
  177.         case XML: return HttpConstants.CONTENT_TYPE_XML;
  178.         case JSON: return HttpConstants.CONTENT_TYPE_JSON;
  179.         case TEXT: return HttpConstants.CONTENT_TYPE_PLAIN;
  180.         default: return null;
  181.         }
  182.     }
  183.     private static String getContentTypeModI(MessageType messageTypeRequest) throws UtilsException {
  184.         switch (messageTypeRequest) {
  185.             case SOAP_11:{
  186.                 return HttpConstants.CONTENT_TYPE_SOAP_1_1;
  187.             }
  188.             case SOAP_12:
  189.             {
  190.                 return HttpConstants.CONTENT_TYPE_SOAP_1_2;
  191.             }
  192.             case XML:{
  193.                 return HttpConstants.CONTENT_TYPE_XML;
  194.             }
  195.             case JSON:
  196.             case BINARY:
  197.             case MIME_MULTIPART:{
  198.                 return HttpConstants.CONTENT_TYPE_JSON;
  199.             }
  200.         }
  201.         throw new UtilsException("Message type unknown");
  202.     }
  203.    
  204.     private void testConnectivityErogazione(Map<Long, String> connettoriServizio, Map<Long, String> connettoriServizioNomeConnettoreMultiplo) throws DriverRegistroServiziException, DriverConfigurazioneException, DriverConfigurazioneNotFound {
  205.         ConfigurazionePdDManager configurazioneManager = ConfigurazionePdDManager.getInstance();
  206.         IDServizio idServizio = this.getServizio();
  207.         List<MappingErogazionePortaApplicativa> mappings = configurazioneManager.getMappingErogazionePortaApplicativaList(idServizio, this.requestInfo);
  208.         for (MappingErogazionePortaApplicativa mapping : mappings) {
  209.             PortaApplicativa pa = configurazioneManager.getPortaApplicativaSafeMethod(mapping.getIdPortaApplicativa(), this.requestInfo);
  210.             if (pa.equals(this.pa))
  211.                 continue;
  212.             List<PortaApplicativaServizioApplicativo> serviziApplicativi = pa.getServizioApplicativo();
  213.            
  214.             for (PortaApplicativaServizioApplicativo sa : serviziApplicativi) {                    
  215.                 IDServizioApplicativo idServizioApplicativo = new IDServizioApplicativo();
  216.                 idServizioApplicativo.setNome(sa.getNome());
  217.                 idServizioApplicativo.setIdSoggettoProprietario(new IDSoggetto(pa.getTipoSoggettoProprietario(), pa.getNomeSoggettoProprietario()));
  218.                 ServizioApplicativo servizioApplicativo = configurazioneManager.getServizioApplicativo(idServizioApplicativo, this.requestInfo);
  219.                
  220.                 testConnectivityErogazione(connettoriServizio, connettoriServizioNomeConnettoreMultiplo,
  221.                         mapping,
  222.                         sa, servizioApplicativo);
  223.             }
  224.         }
  225.     }
  226.     private void testConnectivityErogazione(Map<Long, String> connettoriServizio, Map<Long, String> connettoriServizioNomeConnettoreMultiplo,
  227.             MappingErogazionePortaApplicativa mapping,
  228.             PortaApplicativaServizioApplicativo sa, ServizioApplicativo servizioApplicativo) {      
  229.         if (servizioApplicativo.getInvocazioneServizio() != null &&
  230.                 servizioApplicativo.getInvocazioneServizio().getConnettore() != null &&
  231.                 servizioApplicativo.getInvocazioneServizio().getConnettore().getId()!=null) {
  232.             testConnectivityErogazione(servizioApplicativo.getInvocazioneServizio().getConnettore(), mapping, connettoriServizio);
  233.             if(sa.getDatiConnettore()!=null && sa.getDatiConnettore().getNome()!=null && StringUtils.isNotEmpty(sa.getDatiConnettore().getNome())) {
  234.                 connettoriServizioNomeConnettoreMultiplo.put(servizioApplicativo.getInvocazioneServizio().getConnettore().getId(), sa.getDatiConnettore().getNome());
  235.             }
  236.         }
  237.         if (servizioApplicativo.getRispostaAsincrona() != null &&
  238.                 servizioApplicativo.getRispostaAsincrona().getConnettore() != null &&
  239.                 servizioApplicativo.getRispostaAsincrona().getConnettore().getId()!=null) {
  240.             testConnectivityErogazione(servizioApplicativo.getRispostaAsincrona().getConnettore(), mapping, connettoriServizio);
  241.             connettoriServizioNomeConnettoreMultiplo.put(servizioApplicativo.getRispostaAsincrona().getConnettore().getId(), "Risposta asincrona");
  242.         }
  243.     }
  244.     private void testConnectivityErogazione(Connettore connettore, MappingErogazionePortaApplicativa mapping, Map<Long, String> connettoriServizio) {
  245.         if (connettore != null && connettore.getId() != null && checkConnectivitySupported(connettore.getTipo())) {
  246.             String labelGruppo = mapping.getDescrizione();
  247.             if(mapping.isDefault() &&
  248.                 (labelGruppo==null || StringUtils.isEmpty(labelGruppo))) {
  249.                 labelGruppo = org.openspcoop2.core.constants.Costanti.MAPPING_DESCRIZIONE_DEFAULT;
  250.             }
  251.             connettoriServizio.put(connettore.getId(), labelGruppo);
  252.         }
  253.     }
  254.    
  255.     private void testConnectivityFruizione(Map<Long, String> connettoriServizio) throws DriverRegistroServiziException, DriverConfigurazioneException, DriverConfigurazioneNotFound {
  256.         ConfigurazionePdDManager configurazioneManager = ConfigurazionePdDManager.getInstance();
  257.         IDServizio idServizio = this.getServizio();
  258.         IDSoggetto idFruitore = new IDSoggetto(this.pd.getTipoSoggettoProprietario(), this.pd.getNomeSoggettoProprietario());
  259.        
  260.         List<MappingFruizionePortaDelegata> mappings = configurazioneManager.getMappingFruizionePortaDelegataList(idFruitore, idServizio, this.requestInfo);
  261.         for (MappingFruizionePortaDelegata mapping : mappings) {
  262.             PortaDelegata pd = configurazioneManager.getPortaDelegataSafeMethod(mapping.getIdPortaDelegata(), null);
  263.             if (pd.equals(this.pd))
  264.                 continue;                  
  265.             PortaDelegataAzione azioni = pd.getAzione();
  266.             for (String azione : azioni.getAzioneDelegataList()) {
  267.                 if (idServizio != null)
  268.                     idServizio.setAzione(azione);
  269.                 Connettore connettore = configurazioneManager.getForwardRoute(idFruitore, idServizio, false, null);
  270.                 testConnectivityFruizione(connettore, mapping, connettoriServizio);
  271.             }
  272.         }
  273.     }
  274.     private void testConnectivityFruizione(Connettore connettore, MappingFruizionePortaDelegata mapping, Map<Long, String> connettoriServizio) {
  275.         if (connettore != null && connettore.getId() != null && checkConnectivitySupported(connettore.getTipo())) {
  276.             String labelGruppo = mapping.getDescrizione();
  277.             if(mapping.isDefault() &&
  278.                 (labelGruppo==null || StringUtils.isEmpty(labelGruppo))) {
  279.                 labelGruppo = org.openspcoop2.core.constants.Costanti.MAPPING_DESCRIZIONE_DEFAULT;
  280.             }
  281.             connettoriServizio.put(connettore.getId(), labelGruppo);
  282.         }
  283.     }
  284.    
  285.     private boolean checkConnectivitySupported(String tipoConnettore) {
  286.         TipiConnettore tipo = TipiConnettore.toEnumFromName(tipoConnettore);
  287.         return tipo!=null && (TipiConnettore.HTTP.equals(tipo) || TipiConnettore.HTTPS.equals(tipo));
  288.     }
  289.    
  290.     private void testConnectivity() throws DriverRegistroServiziException, DriverConfigurazioneException, DriverConfigurazioneNotFound, ConnettoreException {
  291.         Map<Long, String> connettoriServizio = new HashMap<>();
  292.         Map<Long, String> connettoriServizioNomeConnettoreMultiplo = new HashMap<>();
  293.        
  294.         if (this.pd != null)
  295.             this.testConnectivityFruizione(connettoriServizio);
  296.        
  297.         if (this.pa != null)
  298.             this.testConnectivityErogazione(connettoriServizio, connettoriServizioNomeConnettoreMultiplo);
  299.        
  300.         if (this.debug)
  301.             this.logger.debug("Inizio test connettivita sul servizio: " + this.getServizio() + ", id connettori: {" + connettoriServizio.keySet() + "}");
  302.        
  303.         for (Map.Entry<Long, String> entry : connettoriServizio.entrySet()) {
  304.             try {
  305.                 ConnettoreCheck.check(entry.getKey(), this.pd != null, null);
  306.             } catch(ConnettoreException e) {
  307.                 String nomeConnettore = connettoriServizioNomeConnettoreMultiplo.get(entry.getKey());
  308.                 if(nomeConnettore==null || StringUtils.isEmpty(nomeConnettore)) {
  309.                     nomeConnettore="";
  310.                 }
  311.                 else {
  312.                     nomeConnettore = " '"+nomeConnettore+"'";
  313.                 }
  314.                 throw new ConnettoreException("connettività fallita verso il connettore"+nomeConnettore+" del gruppo '" + entry.getValue() + "': " + e.getMessage());
  315.             }
  316.         }
  317.     }
  318.    
  319.     private IDServizio getServizio() throws DriverRegistroServiziException {
  320.         if (this.pd != null) {
  321.             return IDServizioFactory.getInstance().getIDServizioFromValues(
  322.                     this.pd.getServizio().getTipo(),
  323.                     this.pd.getServizio().getNome(),
  324.                     this.getSoggettoErogatore(),
  325.                     this.pd.getServizio().getVersione());
  326.         }
  327.        
  328.         if (this.pa != null) {
  329.             return IDServizioFactory.getInstance().getIDServizioFromValues(
  330.                     this.pa.getServizio().getTipo(),
  331.                     this.pa.getServizio().getNome(),
  332.                     this.getSoggettoErogatore(),
  333.                     this.pa.getServizio().getVersione());
  334.         }
  335.        
  336.         return null;
  337.     }
  338.    
  339.     private IDSoggetto getSoggettoFruitore() {
  340.         return this.pd == null ? null : new IDSoggetto(this.pd.getTipoSoggettoProprietario(), this.pd.getNomeSoggettoProprietario());
  341.     }
  342.    
  343.     private IDSoggetto getSoggettoErogatore() {
  344.         if (this.pd != null)
  345.             return new IDSoggetto(this.pd.getSoggettoErogatore().getTipo(), this.pd.getSoggettoErogatore().getNome());
  346.         if (this.pa != null)
  347.             return new IDSoggetto(this.pa.getTipoSoggettoProprietario(), this.pa.getNomeSoggettoProprietario());
  348.         return null;
  349.     }
  350.    
  351.     private List<String> getOperations() {
  352.         List<String> l = null;
  353.         if (this.pd != null)
  354.             return this.pd.getAzione().getAzioneDelegata();
  355.         if (this.pa != null)
  356.             return this.pa.getAzione().getAzioneDelegata();
  357.         return l;
  358.     }
  359.    
  360.     private void testStatistics() throws Exception {
  361.         DatiTransazione datiTransazioni = new DatiTransazione();
  362.         datiTransazioni.setDominio(this.getSoggettoErogatore());
  363.         datiTransazioni.setIdTransazione(this.idTransazione);
  364.         datiTransazioni.setModulo(this.idModulo);
  365.        
  366.         String periodRaw = this.getDynamicProperty(this.tipoConnettore, false, CostantiConnettori.CONNETTORE_STATUS_PERIOD, this.dynamicMap);
  367.         String periodValueRaw = this.getDynamicProperty(this.tipoConnettore, false, CostantiConnettori.CONNETTORE_STATUS_PERIOD_VALUE, this.dynamicMap);
  368.         String lifetimeRaw = this.getDynamicProperty(this.tipoConnettore, false, CostantiConnettori.CONNETTORE_STATUS_STAT_LIFETIME, this.dynamicMap);
  369.        
  370.         if (periodRaw == null)
  371.             throw new ConnettoreException("il tipo del periodo statistico non corretto, valori possibili: " + TipoPeriodoStatistico.toArray());
  372.        
  373.         TipoPeriodoStatistico period = TipoPeriodoStatistico.valueOf(periodRaw.toUpperCase());
  374.         Integer periodValue = Integer.valueOf(periodValueRaw);
  375.         Integer lifeTime = lifetimeRaw != null ? Integer.valueOf(lifetimeRaw) : Integer.MAX_VALUE;
  376.        
  377.        
  378.         if (periodValue <= 0)
  379.             throw new ConnettoreException("il valore del periodo deve essere un valore > 1");
  380.        
  381.         if (this.debug)
  382.             this.logger.debug("Inizio analisi statistica sulle transazioni del servizio:" + this.getServizio());
  383.        
  384.         Date now = new Date();
  385.         RisultatoStatistico numOk = GestoreCacheControlloTraffico.getInstance().readNumeroEsiti(period, periodValue, now, List.of(0), this.getServizio(), this.getSoggettoFruitore(), this.getOperations(), datiTransazioni, this.state, lifeTime);
  386.         RisultatoStatistico numTot = GestoreCacheControlloTraffico.getInstance().readNumeroEsiti(period, periodValue, now, null, this.getServizio(), this.getSoggettoFruitore(), this.getOperations(), datiTransazioni, this.state, lifeTime);
  387.         if (numOk.getRisultato() == 0 && numTot.getRisultato() > 0)
  388.             throw new ConnettoreException("trovate: " + numTot.getRisultato() + " transazioni con errore, nessuna transazione ok");
  389.    
  390.     }
  391.    
  392.     /* ********  METODI  ******** */

  393.     @Override
  394.     protected boolean initializePreSend(ResponseCachingConfigurazione responseCachingConfig, ConnettoreMsg request) {
  395.         return this.initialize(request, false, responseCachingConfig);
  396.     }
  397.    
  398.    
  399.     @Override
  400.     protected boolean send(ConnettoreMsg request) {

  401.         boolean generaTrasmissione = false;
  402.         if(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE)!=null){
  403.             generaTrasmissione = "true".equalsIgnoreCase(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE).trim());
  404.         }
  405.        
  406.         boolean generaTrasmissioneInvertita = false;
  407.         if(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE_INVERTITA)!=null){
  408.             generaTrasmissioneInvertita = "true".equalsIgnoreCase(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE_INVERTITA).trim());
  409.         }
  410.        
  411.         boolean generaTrasmissioneAndataRitorno = false;
  412.         if(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE_ANDATA_RITORNO)!=null){
  413.             generaTrasmissioneAndataRitorno = "true".equalsIgnoreCase(this.properties.get(CostantiConnettori.CONNETTORE_NULL_ECHO_GENERA_TRASMISSIONE_ANDATA_RITORNO).trim());
  414.         }
  415.        
  416.         ConnettoreStatusResponseType statusResponseType = null;
  417.         boolean isStatisticalAnalysis = false;
  418.         boolean isTestConnectivity = false;
  419.         try {
  420.             String statusResponseTypeRaw = this.getDynamicProperty(this.tipoConnettore, true, CostantiConnettori.CONNETTORE_STATUS_RESPONSE_TYPE, this.dynamicMap);
  421.             String statisticalAnalysisRaw = this.getDynamicProperty(this.tipoConnettore, false, CostantiConnettori.CONNETTORE_STATUS_PERIOD, this.dynamicMap);
  422.             String testConnectivityRaw = this.getDynamicProperty(this.tipoConnettore, false, CostantiConnettori.CONNETTORE_STATUS_TEST_CONNECTIVITY, this.dynamicMap);
  423.        
  424.             isStatisticalAnalysis = (statisticalAnalysisRaw != null);
  425.             isTestConnectivity = (testConnectivityRaw != null && testConnectivityRaw.equals(Boolean.TRUE.toString()));
  426.             statusResponseType = ConnettoreStatusResponseType.fromString(statusResponseTypeRaw);
  427.         } catch(ConnettoreException e) {
  428.             statusResponseType = null;
  429.             this.logger.error("Tipologia risposta del connettore status non impostata");
  430.         }
  431.        
  432.         if (this.debug)
  433.             this.logger.debug("connettoreStatus: [type: " + statusResponseType + ", test connectivity: " + isTestConnectivity + ", statistical analysis: " + isStatisticalAnalysis);
  434.        
  435.         this.codice = 200;
  436.         DBManager dbManager = DBManager.getInstance();
  437.         Resource resource = null;
  438.        
  439.         StatefulMessage state = new StatefulMessage(null, this.logger.getLogger());
  440.        
  441.         ValidazioneSintattica validatoreSintattico = null;
  442.         Validatore validatoreProtocollo = null;
  443.         @SuppressWarnings("unused")
  444.         BustaRawContent<?> headerProtocolloRisposta = null;
  445.         String protocol = null;
  446.         try{
  447.             IProtocolFactory<?> protocolFactory = this.getProtocolFactory();
  448.             IProtocolManager protocolManager = protocolFactory.createProtocolManager();
  449.             protocol = protocolFactory.getProtocol();
  450.            
  451.             // Tipologia di servizio
  452.             MessageType requestMessageType = this.requestMsg.getMessageType();
  453.             OpenSPCoop2SoapMessage soapMessageRequest = null;
  454.             if(this.debug)
  455.                 this.logger.debug("Tipologia Servizio: "+this.requestMsg.getServiceBinding());
  456.             if(this.isSoap){
  457.                 soapMessageRequest = this.requestMsg.castAsSoap();
  458.             }
  459.            
  460.            
  461.             // Collezione header di trasporto per dump
  462.             Map<String, List<String>> propertiesTrasportoDebug = null;
  463.             if(this.isDumpBinarioRichiesta()) {
  464.                 propertiesTrasportoDebug = new HashMap<>();
  465.             }
  466.            
  467.            
  468.             // Impostazione Content-Type
  469.             String contentTypeRichiesta = null;
  470.             if(this.debug)
  471.                 this.logger.debug("Impostazione content type...");
  472.             if(this.isSoap){
  473.                 if(this.sbustamentoSoap && soapMessageRequest.countAttachments()>0 && TunnelSoapUtils.isTunnelOpenSPCoopSoap(soapMessageRequest)){
  474.                     contentTypeRichiesta = TunnelSoapUtils.getContentTypeTunnelOpenSPCoopSoap(soapMessageRequest.getSOAPBody());
  475.                 }else{
  476.                     contentTypeRichiesta = this.requestMsg.getContentType();
  477.                 }
  478.                 if(contentTypeRichiesta==null){
  479.                     throw new ConnettoreException("Content-Type del messaggio da spedire non definito");
  480.                 }
  481.             }
  482.             else{
  483.                 contentTypeRichiesta = this.requestMsg.getContentType();
  484.                 // Content-Type non obbligatorio in REST
  485.             }
  486.             if(this.debug)
  487.                 this.logger.info("Impostazione Content-Type ["+contentTypeRichiesta+"]",false);
  488.             if(contentTypeRichiesta!=null){
  489.                 setRequestHeader(HttpConstants.CONTENT_TYPE, contentTypeRichiesta, this.logger, propertiesTrasportoDebug);
  490.             }
  491.            
  492.            
  493.            
  494.             // Impostazione timeout
  495.             if(this.debug)
  496.                 this.logger.debug("Impostazione timeout...");
  497.             int readConnectionTimeout = -1;
  498.             boolean readConnectionTimeoutConfigurazioneGlobale = true;
  499.             if(this.properties.get(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT)!=null){
  500.                 try{
  501.                     readConnectionTimeout = Integer.parseInt(this.properties.get(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT));
  502.                     readConnectionTimeoutConfigurazioneGlobale = this.properties.containsKey(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT_GLOBALE);
  503.                 }catch(Exception e){
  504.                     this.logger.error("Parametro "+CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT+" errato",e);
  505.                 }
  506.             }
  507.             if(readConnectionTimeout==-1){
  508.                 readConnectionTimeout = HttpUtilities.HTTP_READ_CONNECTION_TIMEOUT;
  509.             }
  510.             if(this.debug)
  511.                 this.logger.info("Impostazione read timeout ["+readConnectionTimeout+"]",false);
  512.            
  513.            
  514.             // Impostazione Proprieta del trasporto
  515.             if(this.debug)
  516.                 this.logger.debug("Impostazione header di trasporto...");
  517.             this.forwardHttpRequestHeader();
  518.             if(this.propertiesTrasporto != null){
  519.                 Iterator<String> keys = this.propertiesTrasporto.keySet().iterator();
  520.                 while (keys.hasNext()) {
  521.                     String key = keys.next();
  522.                     List<String> values = this.propertiesTrasporto.get(key);
  523.                     if(this.debug && values!=null && !values.isEmpty()) {
  524.                             for (String value : values) {
  525.                                 this.logger.info("Set proprietà trasporto ["+key+"]=["+value+"]",false);
  526.                             }
  527.                         }
  528.                     setRequestHeader(key, values, this.logger, propertiesTrasportoDebug);
  529.                 }
  530.             }
  531.            
  532.            
  533.            
  534.             // Aggiunga del SoapAction Header in caso di richiesta SOAP
  535.             // spostato sotto il forwardHeader per consentire alle trasformazioni di modificarla
  536.             if(this.isSoap && !this.sbustamentoSoap){
  537.                 if(this.debug)
  538.                     this.logger.debug("Impostazione soap action...");
  539.                 boolean existsTransportProperties = false;
  540.                 if(TransportUtils.containsKey(this.propertiesTrasporto, Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION)){
  541.                     this.soapAction = TransportUtils.getFirstValue(this.propertiesTrasporto, Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION);
  542.                     existsTransportProperties = (this.soapAction!=null);
  543.                 }
  544.                 if(!existsTransportProperties) {
  545.                     this.soapAction = soapMessageRequest.getSoapAction();
  546.                 }
  547.                 if(this.soapAction==null){
  548.                     this.soapAction="\"OpenSPCoop\"";
  549.                 }
  550.                 if(MessageType.SOAP_11.equals(this.requestMsg.getMessageType()) && !existsTransportProperties){
  551.                     // NOTA non quotare la soap action, per mantenere la trasparenza della PdD
  552.                     setRequestHeader(Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION,this.soapAction, propertiesTrasportoDebug);
  553.                 }
  554.                 if(this.debug)
  555.                     this.logger.info("SOAP Action inviata ["+this.soapAction+"]",false);
  556.             }
  557.            
  558.            
  559.            
  560.             // SIMULAZIONE WRITE_TO
  561.             boolean consumeRequestMessage = true;
  562.             if(this.debug)
  563.                 this.logger.debug("Serializzazione (consume-request-message:"+consumeRequestMessage+")...");
  564.             if(this.isDumpBinarioRichiesta()) {
  565.                 this.requestBout = new DumpByteArrayOutputStream(this.dumpBinario_soglia, this.dumpBinario_repositoryFile, this.idTransazione,
  566.                         "NullEcho-"+TipoMessaggio.RICHIESTA_USCITA_DUMP_BINARIO.getValue());
  567.                
  568.                 this.emitDiagnosticStartDumpBinarioRichiestaUscita();
  569.                
  570.                 if(this.isSoap && this.sbustamentoSoap){
  571.                     this.logger.debug("Sbustamento...");
  572.                     TunnelSoapUtils.sbustamentoMessaggio(soapMessageRequest,this.requestBout);
  573.                 }else{
  574.                     this.requestMsg.writeTo(this.requestBout, consumeRequestMessage);
  575.                 }
  576.                 this.requestBout.flush();
  577.                 this.requestBout.close();
  578.                                    
  579.                 this.dataRichiestaInoltrata = DateManager.getDate();
  580.                
  581.                 this.dumpBinarioRichiestaUscita(this.requestBout, requestMessageType, contentTypeRichiesta, this.location, propertiesTrasportoDebug);
  582.             }
  583.             else {
  584.                 this.requestBout = new DumpByteArrayOutputStream(this.dumpBinario_soglia, this.dumpBinario_repositoryFile, this.idTransazione,
  585.                         "NullEcho-"+TipoMessaggio.RICHIESTA_USCITA_DUMP_BINARIO.getValue());
  586.                 if(this.isSoap && this.sbustamentoSoap){
  587.                     this.logger.debug("Sbustamento...");
  588.                     TunnelSoapUtils.sbustamentoMessaggio(soapMessageRequest,this.requestBout);
  589.                 }else{
  590.                     this.requestMsg.writeTo(this.requestBout, consumeRequestMessage);
  591.                 }
  592.                 this.requestBout.flush();
  593.                 this.requestBout.close();
  594.                
  595.                 this.dataRichiestaInoltrata = DateManager.getDate();
  596.             }
  597.            
  598.            
  599.            
  600.            
  601.            
  602.            
  603.             /* ------------  PostOutRequestHandler ------------- */
  604.             this.postOutRequest();
  605.            
  606.            
  607.            
  608.             /* ------------  PreInResponseHandler ------------- */
  609.             this.preInResponse();
  610.            
  611.             // Lettura risposta parametri NotifierInputStream per la risposta
  612.             org.openspcoop2.utils.io.notifier.NotifierInputStreamParams notifierInputStreamParams = null;
  613.             if(this.preInResponseContext!=null){
  614.                 notifierInputStreamParams = this.preInResponseContext.getNotifierInputStreamParams();
  615.             }
  616.            
  617.             // verifica connettivita
  618.             if (isTestConnectivity) {
  619.                 this.testConnectivity();
  620.             }
  621.            
  622.             // analisi statistica
  623.             if (isStatisticalAnalysis) {
  624.                 this.testStatistics();
  625.             }
  626.            
  627.             this.isResponse = new ByteArrayInputStream(ConnettoreStatus.getMessage(statusResponseType, this.requestMsg.getMessageType()).getBytes());
  628.             this.tipoRisposta = ConnettoreStatus.getContentType(statusResponseType, this.requestMsg.getMessageType());
  629.            
  630.             this.normalizeInputStreamResponse(readConnectionTimeout, readConnectionTimeoutConfigurazioneGlobale);
  631.            
  632.             this.initCheckContentTypeConfiguration();
  633.            
  634.             this.messageTypeResponse = this.requestMsg.getMessageType();
  635.            
  636.             if(this.isDumpBinarioRisposta()){
  637.                 this.dumpResponse(this.propertiesTrasportoRisposta);
  638.             }
  639.            
  640.             if(this.isResponse!=null) {
  641.                 this.emitDiagnosticResponseRead(this.isResponse);
  642.             }
  643.            
  644.             OpenSPCoop2MessageFactory messageFactory = Utilities.getOpenspcoop2MessageFactory(this.logger.getLogger(),this.requestMsg, this.requestInfo, MessageRole.RESPONSE);
  645.             OpenSPCoop2MessageParseResult pr;
  646.            
  647.             if (this.isResponse != null) {
  648.                 pr = messageFactory.createMessage(this.messageTypeResponse, MessageRole.RESPONSE,
  649.                         this.tipoRisposta,
  650.                         this.isResponse,notifierInputStreamParams,
  651.                         this.openspcoopProperties.getAttachmentsProcessingMode());
  652.             } else {
  653.                 TransportResponseContext responseContext = new TransportResponseContext(this.logger.getLogger());
  654.                 responseContext.setCodiceTrasporto(this.codice+"");
  655.                 responseContext.setContentLength(0);
  656.                
  657.                 pr = messageFactory.createMessage(this.messageTypeResponse,responseContext,
  658.                         this.isResponse,notifierInputStreamParams,
  659.                         this.openspcoopProperties.getAttachmentsProcessingMode());
  660.             }
  661.             if(pr.getParseException()!=null){
  662.                 this.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION, pr.getParseException());
  663.             }
  664.             this.responseMsg = pr.getMessage_throwParseException();
  665.            
  666.             validatoreSintattico = new ValidazioneSintattica(this.getPddContext(),state,this.responseMsg, this.openspcoopProperties.isReadQualifiedAttribute(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD), protocolFactory);

  667.             if(validatoreSintattico.verifyProtocolPresence(TipoPdD.APPLICATIVA,null,RuoloMessaggio.RISPOSTA) &&
  668.                     !CostantiLabel.SDI_PROTOCOL_NAME.equals(protocolFactory.getProtocol())){ // evitare sdi per far funzionare il protocollo sdi con la sonda.
  669.                
  670.                 // getBusta
  671.                 ProprietaValidazione property = new ProprietaValidazione();
  672.                 property.setValidazioneConSchema(false);
  673.                 property.setValidazioneProfiloCollaborazione(false);
  674.                 property.setValidazioneManifestAttachments(false);
  675.                
  676.                 validatoreProtocollo = new Validatore(this.responseMsg,this.getPddContext(),property,null,
  677.                         this.openspcoopProperties.isReadQualifiedAttribute(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD), protocolFactory);
  678.                
  679.                 if(!validatoreProtocollo.validazioneSintattica()){
  680.                     throw new ConnettoreException("Busta non presente: "+validatoreProtocollo.getErrore().getDescrizione(protocolFactory));
  681.                 }
  682.                
  683.                 // Leggo busta di richiesta
  684.                 Busta busta = validatoreProtocollo.getBusta();
  685.                
  686.                 // informazione spcoopErrore
  687.                 IValidatoreErrori validatoreErrori = protocolFactory.createValidatoreErrori(state);
  688.                 ProprietaValidazioneErrori pValidazioneErrori = new ProprietaValidazioneErrori();
  689.                 pValidazioneErrori.setIgnoraEccezioniNonGravi(protocolManager.isIgnoraEccezioniNonGravi());
  690.                 boolean isBustaSPCoopErrore = validatoreErrori.isBustaErrore(busta,this.responseMsg,pValidazioneErrori);
  691.                
  692.                 // Gestisco il manifest se il messaggio lo possiede
  693.                 boolean gestioneManifest = false;
  694.                 // La gestione manifest non la devo fare a questo livello.
  695.                 // Se mi arriva un messaggio senza manifest, vuol dire che era disabilitata e quindi anche nella risposta non ci deve essere
  696.                 // In egual misura se arriva un messaggio con manifest, significa che ci deve essere anche nella risposta
  697.                 // Poiche' la risposta e' esattamente uguale (nel body e negli allegati) alla richiesta,
  698.                 // venendo costruita dai bytes della richiesta
  699.                
  700.                 // rimozione vecchia busta
  701.                 Sbustamento sbustatore = new Sbustamento(protocolFactory,state);
  702.                 ProtocolMessage protocolMessage = sbustatore.sbustamento(this.responseMsg,this.getPddContext(),
  703.                         busta,RuoloMessaggio.RICHIESTA, gestioneManifest,
  704.                         this.openspcoopProperties.getProprietaManifestAttachments(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD),
  705.                         FaseSbustamento.PRE_CONSEGNA_RICHIESTA,this.requestInfo);
  706.                 if(protocolMessage!=null) {
  707.                     headerProtocolloRisposta = protocolMessage.getBustaRawContent();
  708.                     this.responseMsg = protocolMessage.getMessage(); // updated
  709.                 }
  710.                
  711.                 // Creo busta di risposta solo se la busta di richiesta non conteneva una busta Errore
  712.                 if(!isBustaSPCoopErrore){
  713.            
  714.                     TipoOraRegistrazione tipoOraRegistrazione = this.openspcoopProperties.getTipoTempoBusta(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD);
  715.                     Busta bustaRisposta = busta.invertiBusta(tipoOraRegistrazione,protocolFactory.createTraduttore().toString(tipoOraRegistrazione));
  716.                
  717.                     bustaRisposta.setProfiloDiCollaborazione(busta.getProfiloDiCollaborazione());
  718.                     bustaRisposta.setServizio(busta.getServizio());
  719.                     bustaRisposta.setVersioneServizio(busta.getVersioneServizio());
  720.                     bustaRisposta.setTipoServizio(busta.getTipoServizio());
  721.                     bustaRisposta.setAzione(busta.getAzione());
  722.                    
  723.                     bustaRisposta.setInoltro(busta.getInoltro(),busta.getInoltroValue());
  724.                     bustaRisposta.setConfermaRicezione(busta.isConfermaRicezione());
  725.                    
  726.                     if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ONEWAY.equals(busta.getProfiloDiCollaborazione()) &&
  727.                             busta.isConfermaRicezione() &&
  728.                             this.openspcoopProperties.isGestioneRiscontri(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD)){
  729.                         // Attendono riscontro
  730.                         Riscontro r = new Riscontro();
  731.                         r.setID(busta.getID());
  732.                         r.setOraRegistrazione(DateManager.getDate());
  733.                         r.setTipoOraRegistrazione(TipoOraRegistrazione.SINCRONIZZATO);
  734.                         bustaRisposta.addRiscontro(r);
  735.                        
  736.                     } else if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_ASIMMETRICO.equals(busta.getProfiloDiCollaborazione()) &&
  737.                             busta.getRiferimentoMessaggio()==null){
  738.                         // devo generare ricevuta
  739.                         bustaRisposta.setTipoServizioCorrelato("SPC");
  740.                         bustaRisposta.setServizioCorrelato(busta.getServizio()+"Correlato");
  741.                     } else if(org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione.ASINCRONO_SIMMETRICO.equals(busta.getProfiloDiCollaborazione()) &&
  742.                             busta.getRiferimentoMessaggio()==null){
  743.                    
  744.                         // salvo messaggio sul database asincrono/repositoryBuste
  745.                    
  746.                         // get database
  747.                         try{
  748.                             resource = dbManager.getResource(this.openspcoopProperties.getIdentitaPortaDefault(protocolFactory.getProtocol(), this.requestInfo),"ConnettoreStatus",busta.getID());
  749.                         }catch(Exception e){
  750.                             throw new ConnettoreException("Risorsa non ottenibile",e);
  751.                         }
  752.                         if(resource==null)
  753.                             throw new ConnettoreException("Risorsa is null");
  754.                         if(resource.getResource() == null)
  755.                             throw new ConnettoreException("Connessione is null");
  756.                         Connection connectionDB = (Connection) resource.getResource();
  757.                        
  758.                         state.setConnectionDB(connectionDB);
  759.                        
  760.                         // repository
  761.                         RepositoryBuste repositoryBuste = new RepositoryBuste(state, true,protocolFactory);
  762.                         repositoryBuste.registraBustaIntoInBox(busta, new ArrayList<>() ,
  763.                                 OpenSPCoop2Properties.getInstance().getRepositoryIntervalloScadenzaMessaggi());
  764.                         Integrazione infoIntegrazione = new Integrazione();
  765.                         infoIntegrazione.setIdModuloInAttesa(null);
  766.                         repositoryBuste.aggiornaInfoIntegrazioneIntoInBox(busta.getID(),infoIntegrazione);
  767.                    
  768.                         // asincrono
  769.                         ProfiloDiCollaborazione profiloCollaborazione = new ProfiloDiCollaborazione(state,protocolFactory);
  770.                         profiloCollaborazione.asincronoSimmetrico_registraRichiestaRicevuta(busta.getID(),busta.getCollaborazione(),
  771.                                 busta.getTipoServizioCorrelato(),busta.getServizioCorrelato(),busta.getVersioneServizioCorrelato(),true,
  772.                                 this.openspcoopProperties.getRepositoryIntervalloScadenzaMessaggi());
  773.                    
  774.                         // commit
  775.                         try{
  776.                             connectionDB.setAutoCommit(false);
  777.                             state.executePreparedStatement();
  778.                
  779.                             connectionDB.commit();
  780.                             connectionDB.setAutoCommit(true);
  781.                         }catch (Exception e) {  
  782.                             this.logger.error("Riscontrato errore durante la gestione transazione del DB per la richiesta: "+e.getMessage());
  783.                             // Rollback quanto effettuato (se l'errore e' avvenuto sul commit, o prima nell'execute delle PreparedStatement)
  784.                             try{
  785.                                 connectionDB.rollback();
  786.                             }catch(Exception er){
  787.                                 // ignore
  788.                             }
  789.                             state.closePreparedStatement(); // Chiude le PreparedStatement aperte(e non eseguite) per il save del Msg
  790.                         }finally {
  791.                             // Ripristino connessione
  792.                             try{
  793.                                 connectionDB.setAutoCommit(true);
  794.                             }catch(Exception er){
  795.                                 // ignore
  796.                             }
  797.                         }
  798.                    
  799.                     }
  800.                
  801.                     // Riferimento Messaggio
  802.                     bustaRisposta.setRiferimentoMessaggio(busta.getID());
  803.                    
  804.                     // Identificativo Messaggio
  805.                     String dominio = null;
  806.                     if(request.getConnectorProperties()!=null)
  807.                         dominio = request.getConnectorProperties().get("identificativo-porta");
  808.                     if(dominio==null){
  809.                         dominio = protocolFactory.createTraduttore().getIdentificativoPortaDefault(new IDSoggetto(busta.getTipoDestinatario(), busta.getDestinatario()));
  810.                     }
  811.                     String idBustaRisposta = null;
  812.                     Imbustamento imbustatore = new Imbustamento(this.logger.getLogger(), protocolFactory, state);
  813.                     try{
  814.                         idBustaRisposta =
  815.                             imbustatore.buildID(new IDSoggetto(busta.getTipoDestinatario(), busta.getDestinatario(), dominio),
  816.                                     null,
  817.                                     this.openspcoopProperties.getGestioneSerializableDBAttesaAttiva(),
  818.                                     this.openspcoopProperties.getGestioneSerializableDBCheckInterval(),
  819.                                     RuoloMessaggio.RISPOSTA);
  820.                     }catch(Exception e){
  821.                         // rilancio
  822.                         throw new ConnettoreException(e);
  823.                     }
  824.                     bustaRisposta.setID(idBustaRisposta);
  825.                    
  826.                     if(generaTrasmissioneAndataRitorno){
  827.                         Trasmissione t = new Trasmissione();
  828.                         t.setTipoOrigine(busta.getTipoMittente());
  829.                         t.setOrigine(busta.getMittente());
  830.                         t.setIdentificativoPortaOrigine(busta.getIdentificativoPortaMittente());
  831.                         t.setIndirizzoOrigine(busta.getIndirizzoMittente());
  832.                        
  833.                         t.setTipoDestinazione(busta.getTipoDestinatario());
  834.                         t.setDestinazione(busta.getDestinatario());
  835.                         t.setIdentificativoPortaDestinazione(busta.getIdentificativoPortaDestinatario());
  836.                         t.setIndirizzoDestinazione(busta.getIndirizzoDestinatario());
  837.                        
  838.                         t.setOraRegistrazione(busta.getOraRegistrazione());
  839.                         t.setTempo(busta.getTipoOraRegistrazione(), busta.getTipoOraRegistrazioneValue());
  840.                         bustaRisposta.addTrasmissione(t);
  841.                     }
  842.                     if(generaTrasmissione || generaTrasmissioneInvertita || generaTrasmissioneAndataRitorno){
  843.                         Trasmissione t = new Trasmissione();
  844.                         if(generaTrasmissione || generaTrasmissioneAndataRitorno){
  845.                             t.setTipoOrigine(bustaRisposta.getTipoMittente());
  846.                             t.setOrigine(bustaRisposta.getMittente());
  847.                             t.setIdentificativoPortaOrigine(bustaRisposta.getIdentificativoPortaMittente());
  848.                             t.setIndirizzoOrigine(bustaRisposta.getIndirizzoMittente());
  849.                            
  850.                             t.setTipoDestinazione(bustaRisposta.getTipoDestinatario());
  851.                             t.setDestinazione(bustaRisposta.getDestinatario());
  852.                             t.setIdentificativoPortaDestinazione(bustaRisposta.getIdentificativoPortaDestinatario());
  853.                             t.setIndirizzoDestinazione(bustaRisposta.getIndirizzoDestinatario());
  854.                         }
  855.                         if(generaTrasmissioneInvertita){
  856.                             // invertita
  857.                             t.setTipoOrigine(bustaRisposta.getTipoDestinatario());
  858.                             t.setOrigine(bustaRisposta.getDestinatario());
  859.                             t.setIdentificativoPortaOrigine(bustaRisposta.getIdentificativoPortaDestinatario());
  860.                             t.setIndirizzoOrigine(bustaRisposta.getIndirizzoDestinatario());
  861.                            
  862.                             t.setTipoDestinazione(bustaRisposta.getTipoMittente());
  863.                             t.setDestinazione(bustaRisposta.getMittente());
  864.                             t.setIdentificativoPortaDestinazione(bustaRisposta.getIdentificativoPortaMittente());
  865.                             t.setIndirizzoDestinazione(bustaRisposta.getIndirizzoMittente());
  866.                         }
  867.                         t.setOraRegistrazione(bustaRisposta.getOraRegistrazione());
  868.                         t.setTempo(bustaRisposta.getTipoOraRegistrazione(), bustaRisposta.getTipoOraRegistrazioneValue());
  869.                         bustaRisposta.addTrasmissione(t);
  870.                     }
  871.                                
  872.                     // imbustamento nuova busta
  873.                     Integrazione integrazione = new Integrazione();
  874.                     integrazione.setStateless(true);
  875.                    
  876.                     ProtocolMessage protocolMessageRisposta = imbustatore.imbustamentoRisposta(this.responseMsg,this.getPddContext(),
  877.                             bustaRisposta,busta,integrazione,gestioneManifest,false,
  878.                             this.openspcoopProperties.getProprietaManifestAttachments(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD),
  879.                             FaseImbustamento.PRIMA_SICUREZZA_MESSAGGIO);
  880.                     if(protocolMessageRisposta!=null && !protocolMessageRisposta.isPhaseUnsupported()) {
  881.                         this.responseMsg = protocolMessageRisposta.getMessage(); // updated
  882.                     }
  883.                    
  884.                     protocolMessageRisposta = imbustatore.imbustamentoRisposta(this.responseMsg,this.getPddContext(),
  885.                             bustaRisposta,busta,integrazione,gestioneManifest,false,
  886.                             this.openspcoopProperties.getProprietaManifestAttachments(CostantiRegistroServizi.IMPLEMENTAZIONE_STANDARD),
  887.                             FaseImbustamento.DOPO_SICUREZZA_MESSAGGIO);
  888.                     if(protocolMessageRisposta!=null && !protocolMessageRisposta.isPhaseUnsupported()) {
  889.                         this.responseMsg = protocolMessageRisposta.getMessage(); // updated
  890.                     }

  891.                 }
  892.                 else{
  893.                     // rimuovo il FAULT.
  894.                     if(this.responseMsg instanceof OpenSPCoop2SoapMessage){
  895.                         OpenSPCoop2SoapMessage soapMessage = this.responseMsg.castAsSoap();
  896.                         if(soapMessage.hasSOAPFault()){
  897.                             soapMessage.getSOAPBody().removeChild(soapMessage.getSOAPBody().getFault());
  898.                         }
  899.                     }
  900.                 }
  901.             }
  902.            
  903.             // content length
  904.             if(this.responseMsg!=null){
  905.                 this.contentLength = this.responseMsg.getIncomingMessageContentLength();
  906.             }
  907.            
  908.         }catch(Exception e){
  909.             this.eccezioneProcessamento = e;
  910.             String msgErrore = this.readExceptionMessageFromException(e);
  911.             if(this.generateErrorWithConnectorPrefix) {
  912.                 this.errore = "rilevata anomalia; "+msgErrore;
  913.             }
  914.             else {
  915.                 this.errore = msgErrore;
  916.             }
  917.             this.logger.error("Rilevata anomalia: "+msgErrore,e);
  918.             return false;
  919.         }finally{
  920.                    
  921.             // *** GB ***
  922.             if(validatoreSintattico!=null){
  923.                 validatoreSintattico.setHeaderSOAP(null);
  924.             }
  925.             validatoreSintattico = null;
  926.             if(validatoreProtocollo!=null){
  927.                 if(validatoreProtocollo.getValidatoreSintattico()!=null){
  928.                     validatoreProtocollo.getValidatoreSintattico().setHeaderSOAP(null);
  929.                 }
  930.                 validatoreProtocollo.setValidatoreSintattico(null);
  931.             }
  932.             validatoreProtocollo = null;
  933.             headerProtocolloRisposta = null;
  934.             // *** GB ***
  935.            
  936.             // release database
  937.             dbManager.releaseResource(this.openspcoopProperties.getIdentitaPortaDefault(protocol, this.requestInfo),
  938.                     "ConnettoreStatus", resource);
  939.         }
  940.        
  941.         return true;
  942.     }
  943.    
  944.     private void setRequestHeader(String key, String value, ConnettoreLogger logger, Map<String, List<String>> propertiesTrasportoDebug) throws Exception {
  945.         List<String> list = new ArrayList<>();
  946.         list.add(value);
  947.         this.setRequestHeader(key, list, logger, propertiesTrasportoDebug);
  948.     }
  949.    
  950.     private void setRequestHeader(String key, List<String> values, ConnettoreLogger logger, Map<String, List<String>> propertiesTrasportoDebug) throws Exception {
  951.        
  952.         if(this.debug && values!=null && !values.isEmpty()) {
  953.             for (String value : values) {
  954.                 logger.info("Set proprietà trasporto ["+key+"]=["+value+"]",false);    
  955.             }
  956.         }
  957.         setRequestHeader(key, values, propertiesTrasportoDebug);
  958.        
  959.     }
  960.     @Override
  961.     protected void setRequestHeader(String key,List<String> values) throws Exception {
  962.         this.propertiesTrasportoRisposta.put(key, values);
  963.     }
  964.    
  965.     /**
  966.      * Ritorna l'informazione su dove il connettore sta spedendo il messaggio
  967.      *
  968.      * @return location di inoltro del messaggio
  969.      */
  970.     @Override
  971.     public String getLocation() throws ConnettoreException {
  972.         return LOCATION;
  973.     }

  974.     @Override
  975.     public void disconnect() throws ConnettoreException {
  976.         try {
  977.             if(this.requestBout!=null) {
  978.                 this.requestBout.clearResources();
  979.             }
  980.         }catch(Exception e) {
  981.             this.logger.error("Release resources failed: "+e.getMessage(), e);
  982.         }
  983.     }
  984. }