RicezioneContenutiApplicativiHTTPtoSOAPService.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.services.service;

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

  27. import javax.xml.soap.SOAPBody;
  28. import javax.xml.soap.SOAPElement;

  29. import org.apache.commons.lang.StringUtils;
  30. import org.openspcoop2.core.config.DumpConfigurazione;
  31. import org.openspcoop2.core.config.PortaDelegata;
  32. import org.openspcoop2.core.constants.TipoPdD;
  33. import org.openspcoop2.core.constants.TransferLengthModes;
  34. import org.openspcoop2.core.id.IDPortaDelegata;
  35. import org.openspcoop2.core.id.IDServizio;
  36. import org.openspcoop2.core.registry.driver.IDServizioFactory;
  37. import org.openspcoop2.core.transazioni.Transazione;
  38. import org.openspcoop2.message.OpenSPCoop2Message;
  39. import org.openspcoop2.message.OpenSPCoop2MessageParseResult;
  40. import org.openspcoop2.message.constants.MessageRole;
  41. import org.openspcoop2.message.constants.MessageType;
  42. import org.openspcoop2.message.constants.ServiceBinding;
  43. import org.openspcoop2.message.exception.ParseException;
  44. import org.openspcoop2.message.exception.ParseExceptionUtils;
  45. import org.openspcoop2.message.soap.SoapUtils;
  46. import org.openspcoop2.message.soap.TunnelSoapUtils;
  47. import org.openspcoop2.monitor.sdk.transaction.FaseTracciamento;
  48. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  49. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  50. import org.openspcoop2.pdd.core.CostantiPdD;
  51. import org.openspcoop2.pdd.core.GestoreRichieste;
  52. import org.openspcoop2.pdd.core.PdDContext;
  53. import org.openspcoop2.pdd.core.connettori.IConnettore;
  54. import org.openspcoop2.pdd.core.connettori.RepositoryConnettori;
  55. import org.openspcoop2.pdd.core.controllo_traffico.SogliaDimensioneMessaggio;
  56. import org.openspcoop2.pdd.core.controllo_traffico.SogliaReadTimeout;
  57. import org.openspcoop2.pdd.core.controllo_traffico.SoglieDimensioneMessaggi;
  58. import org.openspcoop2.pdd.core.credenziali.Credenziali;
  59. import org.openspcoop2.pdd.core.handlers.GestoreHandlers;
  60. import org.openspcoop2.pdd.core.handlers.HandlerException;
  61. import org.openspcoop2.pdd.core.handlers.PostOutResponseContext;
  62. import org.openspcoop2.pdd.core.handlers.PreInAcceptRequestContext;
  63. import org.openspcoop2.pdd.core.handlers.PreInRequestContext;
  64. import org.openspcoop2.pdd.core.transazioni.TransactionContext;
  65. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  66. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  67. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  68. import org.openspcoop2.pdd.logger.transazioni.ConfigurazioneTracciamento;
  69. import org.openspcoop2.pdd.logger.transazioni.InformazioniTransazione;
  70. import org.openspcoop2.pdd.logger.transazioni.TracciamentoManager;
  71. import org.openspcoop2.pdd.services.DirectVMProtocolInfo;
  72. import org.openspcoop2.pdd.services.DumpRaw;
  73. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  74. import org.openspcoop2.pdd.services.ServicesUtils;
  75. import org.openspcoop2.pdd.services.connector.ConnectorDispatcherErrorInfo;
  76. import org.openspcoop2.pdd.services.connector.ConnectorDispatcherInfo;
  77. import org.openspcoop2.pdd.services.connector.ConnectorDispatcherUtils;
  78. import org.openspcoop2.pdd.services.connector.ConnectorException;
  79. import org.openspcoop2.pdd.services.connector.RicezioneContenutiApplicativiHTTPtoSOAPConnector;
  80. import org.openspcoop2.pdd.services.connector.messages.ConnectorInMessage;
  81. import org.openspcoop2.pdd.services.connector.messages.ConnectorOutMessage;
  82. import org.openspcoop2.pdd.services.connector.messages.DirectVMConnectorInMessage;
  83. import org.openspcoop2.pdd.services.connector.messages.DirectVMConnectorOutMessage;
  84. import org.openspcoop2.pdd.services.connector.messages.DumpRawConnectorInMessage;
  85. import org.openspcoop2.pdd.services.connector.messages.DumpRawConnectorOutMessage;
  86. import org.openspcoop2.pdd.services.core.RicezioneContenutiApplicativi;
  87. import org.openspcoop2.pdd.services.core.RicezioneContenutiApplicativiContext;
  88. import org.openspcoop2.pdd.services.error.RicezioneContenutiApplicativiInternalErrorGenerator;
  89. import org.openspcoop2.protocol.basic.builder.EsitoBuilder;
  90. import org.openspcoop2.protocol.basic.registry.ServiceIdentificationReader;
  91. import org.openspcoop2.protocol.engine.SecurityTokenUtilities;
  92. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  93. import org.openspcoop2.protocol.sdk.builder.EsitoTransazione;
  94. import org.openspcoop2.protocol.sdk.builder.InformazioniErroriInfrastrutturali;
  95. import org.openspcoop2.protocol.sdk.constants.CodiceErroreIntegrazione;
  96. import org.openspcoop2.protocol.sdk.constants.ErroreIntegrazione;
  97. import org.openspcoop2.protocol.sdk.constants.ErroriIntegrazione;
  98. import org.openspcoop2.protocol.sdk.constants.EsitoTransazioneName;
  99. import org.openspcoop2.protocol.sdk.constants.IDService;
  100. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  101. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  102. import org.openspcoop2.protocol.sdk.state.URLProtocolContext;
  103. import org.openspcoop2.protocol.utils.EsitiProperties;
  104. import org.openspcoop2.utils.LimitExceededIOException;
  105. import org.openspcoop2.utils.LoggerWrapperFactory;
  106. import org.openspcoop2.utils.TimeoutIOException;
  107. import org.openspcoop2.utils.Utilities;
  108. import org.openspcoop2.utils.date.DateManager;
  109. import org.openspcoop2.utils.dch.MailcapActivationReader;
  110. import org.openspcoop2.utils.io.DumpByteArrayOutputStream;
  111. import org.openspcoop2.utils.io.notifier.NotifierInputStreamParams;
  112. import org.openspcoop2.utils.transport.TransportRequestContext;
  113. import org.openspcoop2.utils.transport.TransportUtils;
  114. import org.openspcoop2.utils.transport.http.HttpConstants;
  115. import org.slf4j.Logger;

  116. /**
  117.  * Servlet che serve per creare un tunnel da un servizio che non conosce SOAP verso OpenSPCoop (che utilizza SOAP)
  118.  *
  119.  * @author Poli Andrea (apoli@link.it)
  120.  * @author $Author$
  121.  * @version $Rev$, $Date$
  122.  */

  123. public class RicezioneContenutiApplicativiHTTPtoSOAPService  {

  124.     private RicezioneContenutiApplicativiInternalErrorGenerator generatoreErrore;
  125.    
  126.     public static void forceXmlResponse(RicezioneContenutiApplicativiInternalErrorGenerator generatoreErrore) {
  127.         generatoreErrore.setForceMessageTypeResponse(MessageType.XML); // forzo xml
  128.         if(generatoreErrore.getProprietaErroreAppl()!=null) {
  129.             generatoreErrore.getProprietaErroreAppl().setFaultAsXML(true); // siamo in una richiesta http senza SOAP, un SoapFault non ha senso
  130.         }
  131.     }
  132.    
  133.     public RicezioneContenutiApplicativiHTTPtoSOAPService(RicezioneContenutiApplicativiInternalErrorGenerator generatoreErrore){
  134.         this.generatoreErrore = generatoreErrore;
  135.         if(this.generatoreErrore!=null) {
  136.             RicezioneContenutiApplicativiHTTPtoSOAPService.forceXmlResponse(this.generatoreErrore);
  137.         }
  138.     }
  139.    
  140.     public void process(ConnectorInMessage req, ConnectorOutMessage res, Date dataAccettazioneRichiesta) throws ConnectorException {
  141.        
  142.         // Timestamp
  143.         Date dataIngressoRichiesta = null;
  144.        
  145.         // IDModulo
  146.         String idModulo = req.getIdModulo();
  147.         IDService idModuloAsService = req.getIdModuloAsIDService();
  148.         RequestInfo requestInfo = req.getRequestInfo();

  149.         // Log
  150.         Logger logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  151.         if(logCore==null)
  152.             logCore = LoggerWrapperFactory.getLogger(idModulo);

  153.         OpenSPCoop2Properties openSPCoopProperties = OpenSPCoop2Properties.getInstance();
  154.        

  155.         /* ------------  PreInHandler (PreInAcceptRequestContext) ------------- */
  156.        
  157.         PreInAcceptRequestContext preInAcceptRequestContext = null;
  158.         if (openSPCoopProperties != null && OpenSPCoop2Startup.initialize) {
  159.            
  160.             // build context
  161.             preInAcceptRequestContext = new PreInAcceptRequestContext();
  162.             preInAcceptRequestContext.setTipoPorta(TipoPdD.DELEGATA);
  163.             preInAcceptRequestContext.setIdModulo(idModulo);
  164.             preInAcceptRequestContext.setRequestInfo(requestInfo);  
  165.             preInAcceptRequestContext.setLogCore(logCore);
  166.            
  167.             // valori che verranno aggiornati dopo
  168.             try {
  169.                 if(openSPCoopProperties.isConnettoriUseLimitedInputStream()) {
  170.                     SogliaDimensioneMessaggio soglia = new SogliaDimensioneMessaggio();
  171.                     soglia.setSogliaKb(openSPCoopProperties.getLimitedInputStreamThresholdKb());
  172.                     soglia.setUseContentLengthHeader(openSPCoopProperties.isLimitedInputStreamUseContentLength());
  173.                     soglia.setUseContentLengthHeaderAcceptZeroValue(openSPCoopProperties.isLimitedInputStreamUseContentLengthAcceptZeroValue());
  174.                     soglia.setPolicyGlobale(true);
  175.                     soglia.setNomePolicy("GovWayCore");
  176.                     soglia.setIdPolicyConGruppo("GovWayCore");
  177.                     req.setRequestLimitedStream(soglia);
  178.                 }
  179.                 if(openSPCoopProperties.isConnettoriUseTimeoutInputStream()) {
  180.                     SogliaReadTimeout soglia = new SogliaReadTimeout();
  181.                     soglia.setSogliaMs(openSPCoopProperties.getReadConnectionTimeout_ricezioneContenutiApplicativi());
  182.                     soglia.setConfigurazioneGlobale(true);
  183.                     soglia.setIdConfigurazione("GovWayCore");
  184.                     req.setRequestReadTimeout(soglia);
  185.                 }
  186.                 req.setThresholdContext(null,
  187.                     openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  188.             }catch(Throwable t) {
  189.                 logCore.error(t.getMessage(),t);
  190.             }
  191.             preInAcceptRequestContext.setReq(req);
  192.            
  193.             // invocazione handler
  194.             GestoreHandlers.preInRequest(preInAcceptRequestContext, logCore, logCore);
  195.            
  196.         }
  197.        
  198.        
  199.         // GeneratoreErrore
  200.         try{
  201.             if(this.generatoreErrore==null){
  202.                 this.generatoreErrore =
  203.                         new RicezioneContenutiApplicativiInternalErrorGenerator(logCore, RicezioneContenutiApplicativiHTTPtoSOAPConnector.ID_MODULO, requestInfo);
  204.                 this.generatoreErrore.getProprietaErroreAppl().setFaultAsXML(true); // siamo in una richiesta http senza SOAP, un SoapFault non ha senso
  205.             }
  206.         }catch(Exception e){
  207.             String msg = "Inizializzazione Generatore Errore fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  208.             logCore.error(msg,e);
  209.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore, // il metodo doError gestisce il generatoreErrore a null
  210.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  211.                     get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  212.                     IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  213.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  214.             return;
  215.         }
  216.        
  217.         //  Proprieta' OpenSPCoop
  218.         if (!OpenSPCoop2Startup.initialize || openSPCoopProperties == null) {
  219.             String msg = "Inizializzazione di GovWay non correttamente effettuata: OpenSPCoopProperties";
  220.             if(!OpenSPCoop2Startup.initialize) {
  221.                 msg = "Inizializzazione di GovWay non correttamente effettuata";
  222.             }
  223.             logCore.error(msg);
  224.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  225.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  226.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  227.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, null, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  228.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  229.             return;
  230.         }
  231.        
  232.         // Configurazione Reader
  233.         ConfigurazionePdDManager configPdDManager = null;
  234.         try{
  235.             configPdDManager = ConfigurazionePdDManager.getInstance();
  236.             if(configPdDManager==null || configPdDManager.isInitializedConfigurazionePdDReader()==false){
  237.                 throw new Exception("ConfigurazionePdDManager not initialized");
  238.             }
  239.         }catch(Throwable e){
  240.             String msg = "Inizializzazione di GovWay non correttamente effettuata: ConfigurazionePdDManager";
  241.             logCore.error(msg);
  242.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  243.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  244.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  245.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  246.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  247.             return;
  248.         }
  249.            
  250.         // PddContext from servlet
  251.         Object oPddContextFromServlet = null;
  252.         try{
  253.             oPddContextFromServlet = req.getAttribute(CostantiPdD.OPENSPCOOP2_PDD_CONTEXT_HEADER_HTTP.getValue());
  254.         }catch(Exception e){
  255.             logCore.error("req.getAttribute("+CostantiPdD.OPENSPCOOP2_PDD_CONTEXT_HEADER_HTTP+") error: "+e.getMessage(),e);
  256.         }
  257.         PdDContext pddContextFromServlet = null;
  258.         if(oPddContextFromServlet!=null){
  259.             pddContextFromServlet = (PdDContext) oPddContextFromServlet;
  260.         }
  261.                
  262.         // check requestInfo
  263.         if(requestInfo==null) {
  264.             String msg = "RequestInfo undefined";
  265.             logCore.error(msg);
  266.             return;
  267.         }
  268.        
  269.         // Identifico Servizio per comprendere correttamente il messageType
  270.         ServiceIdentificationReader serviceIdentificationReader = null;
  271.         try{
  272.             serviceIdentificationReader = ServicesUtils.getServiceIdentificationReader(logCore, requestInfo,
  273.                     configPdDManager.getRegistroServiziManager(), configPdDManager);
  274.         }catch(Exception e){
  275.             String msg = "Inizializzazione RegistryReader fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  276.             logCore.error(msg,e);
  277.             ConnectorDispatcherErrorInfo cInfo =  ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  278.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  279.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  280.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  281.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  282.             return;
  283.         }
  284.    
  285.         // Provo a creare un context (per l'id di transazione nei diagnostici)
  286.         RicezioneContenutiApplicativiContext context = null;
  287.         IProtocolFactory<?> protocolFactory = null;
  288.         String idTransazione = null;
  289.         try {
  290.             context = new RicezioneContenutiApplicativiContext(idModuloAsService,dataAccettazioneRichiesta,requestInfo);
  291.             protocolFactory = req.getProtocolFactory();
  292.             idTransazione = (String)context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  293.         }catch(Throwable e) {
  294.             context = null;
  295.             protocolFactory = null;
  296.             // non loggo l'errore tanto poi provo a ricreare il context subito dopo e li verra' registrato l'errore
  297.         }

  298.         try{
  299.             GestoreRichieste.readRequestConfig(requestInfo);
  300.         }catch(Exception e){
  301.             String msg = "GestoreRichieste readRequestConfig fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  302.             logCore.error(msg,e);
  303.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  304.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  305.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_500_ERRORE_INTERNO),
  306.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  307.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  308.             return;
  309.         }
  310.        
  311.         if(idTransazione!=null) {
  312.             try {
  313.                 if(openSPCoopProperties.isTransazioniEnabled()) {
  314.                     TransactionContext.createTransaction(idTransazione,"RicezioneContenutiApplicativiHTTPtoSOAP.1");
  315.                 }
  316.                 requestInfo.setIdTransazione(idTransazione);
  317.                
  318.                 req.setThresholdContext((context!=null ? context.getPddContext(): null),
  319.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  320.            
  321.             }catch(Throwable e) {
  322.                 context = null;
  323.                 protocolFactory = null;
  324.                 // non loggo l'errore tanto poi provo a ricreare il context subito dopo e li verra' registrato l'errore
  325.             }
  326.         }
  327.        
  328.         // Logger dei messaggi diagnostici
  329.         String nomePorta = requestInfo.getProtocolContext().getInterfaceName();
  330.         MsgDiagnostico msgDiag = MsgDiagnostico.newInstance(TipoPdD.DELEGATA,idModulo,nomePorta,requestInfo);
  331.         msgDiag.setPrefixMsgPersonalizzati(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_CONTENUTI_APPLICATIVI);
  332.         if(context!=null && protocolFactory!=null) {
  333.             msgDiag.setPddContext(context.getPddContext(), protocolFactory);
  334.         }
  335.        
  336.         try{
  337.             msgDiag.logPersonalizzato("ricezioneRichiesta.firstLog");
  338.         }catch(Exception e){
  339.             logCore.error("Errore generazione diagnostico di ingresso",e);
  340.         }
  341.        
  342.         try{
  343.             req.setDiagnosticProducer(context!=null ? context.getPddContext(): null, msgDiag);
  344.         }catch(Throwable e){
  345.             logCore.error("Errore registrazione diagnostico sulla richiesta",e);
  346.         }
  347.        
  348.         // emitDiagnostic preAccept handler
  349.         GestoreHandlers.emitDiagnostic(msgDiag, preInAcceptRequestContext, context!=null ? context.getPddContext() : null,
  350.                 logCore, logCore);
  351.        
  352.         // Aggiorno RequestInfo
  353.         try{
  354.             msgDiag.mediumDebug("Accesso configurazione della richiesta in corso...");
  355.         }catch(Exception e){
  356.             logCore.error("Errore generazione diagnostico",e);
  357.         }
  358.         ConnectorDispatcherInfo cInfo = RicezioneContenutiApplicativiServiceUtils.updatePortaDelegataRequestInfo(requestInfo, logCore, req, res,
  359.                 this.generatoreErrore, serviceIdentificationReader, msgDiag,
  360.                 context!=null ? context.getPddContext(): null);
  361.         if(cInfo!=null){
  362.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(context, logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  363.             return; // l'errore in response viene impostato direttamente dentro il metodo
  364.         }
  365.         req.updateRequestInfo(requestInfo);

  366.         // Timeout e DumpRaw
  367.         DumpRaw dumpRaw = null;
  368.         try{
  369.             try{
  370.                 msgDiag.mediumDebug("Lettura configurazione dump binario ...");
  371.             }catch(Exception e){
  372.                 logCore.error("Errore generazione diagnostico",e);
  373.             }
  374.             boolean dumpBinario = configPdDManager.dumpBinarioPD();
  375.             PortaDelegata pd = null;
  376.             if(requestInfo!=null && requestInfo.getProtocolContext()!=null && requestInfo.getProtocolContext().getInterfaceName()!=null) {
  377.                 IDPortaDelegata idPD = new IDPortaDelegata();
  378.                 idPD.setNome(requestInfo.getProtocolContext().getInterfaceName());
  379.                 pd = configPdDManager.getPortaDelegataSafeMethod(idPD, requestInfo);
  380.             }

  381.             // Limited
  382.             try{
  383.                 msgDiag.mediumDebug("Lettura configurazione dimensione massima della richiesta ...");
  384.             }catch(Exception e){
  385.                 logCore.error("Errore generazione diagnostico",e);
  386.             }
  387.             String azione = (requestInfo!=null && requestInfo.getIdServizio()!=null) ? requestInfo.getIdServizio().getAzione() : null;
  388.             SoglieDimensioneMessaggi limitedInputStream = configPdDManager.getSoglieLimitedInputStream(pd, azione, idModulo,
  389.                     (context!=null && context.getPddContext()!=null) ? context.getPddContext() : null,
  390.                     requestInfo,
  391.                     protocolFactory, logCore);
  392.             if(limitedInputStream!=null) {
  393.                 req.setRequestLimitedStream(limitedInputStream.getRichiesta());
  394.                 if(context!=null && context.getPddContext()!=null) {
  395.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.LIMITED_STREAM, limitedInputStream.getRisposta());
  396.                 }
  397.             }
  398.             else {
  399.                 if(!openSPCoopProperties.isLimitedInputStreamThresholdDefined()) {
  400.                     req.disableLimitedStream();
  401.                 }
  402.             }
  403.            
  404.             // Timeout
  405.             try{
  406.                 msgDiag.mediumDebug("Lettura configurazione timeout per la lettura della richiesta ...");
  407.             }catch(Exception e){
  408.                 logCore.error("Errore generazione diagnostico",e);
  409.             }
  410.             boolean useTimeoutInputStream = configPdDManager.isConnettoriUseTimeoutInputStream(pd);
  411.             if(useTimeoutInputStream) {
  412.                 SogliaReadTimeout timeout = configPdDManager.getRequestReadTimeout(pd,
  413.                         requestInfo,
  414.                         protocolFactory,
  415.                         context!=null ? context.getPddContext() : null,
  416.                                 null);
  417.                 if(timeout!=null && timeout.getSogliaMs()>0) {
  418.                     req.setRequestReadTimeout(timeout);
  419.                 }
  420.                 else {
  421.                     req.disableReadTimeout();
  422.                 }
  423.             }
  424.             else {
  425.                 req.disableReadTimeout();
  426.             }
  427.            
  428.             // DumpRaw
  429.             try{
  430.                 msgDiag.mediumDebug("Lettura configurazione dump ...");
  431.             }catch(Exception e){
  432.                 logCore.error("Errore generazione diagnostico",e);
  433.             }
  434.             DumpConfigurazione dumpConfigurazione = configPdDManager.getDumpConfigurazione(pd);
  435.             ConfigurazioneTracciamento configurazioneTracciamento = new ConfigurazioneTracciamento(logCore, configPdDManager, pd);
  436.             boolean fileTraceHeaders = configurazioneTracciamento.isTransazioniFileTraceDumpBinarioHeaderEnabled();
  437.             boolean fileTracePayload = configurazioneTracciamento.isTransazioniFileTraceDumpBinarioPayloadEnabled();
  438.             dumpRaw = new DumpRaw(logCore, requestInfo.getIdentitaPdD(), idModulo, TipoPdD.DELEGATA,
  439.                     dumpBinario,
  440.                     dumpConfigurazione,
  441.                     fileTraceHeaders, fileTracePayload);
  442.             if(dumpRaw.isActiveDumpRichiesta()) {
  443.                 req = new DumpRawConnectorInMessage(logCore, req,
  444.                         (context!=null ? context.getPddContext(): null),
  445.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  446.             }
  447.             if(dumpRaw.isActiveDumpRisposta()) {
  448.                 res = new DumpRawConnectorOutMessage(logCore, res,
  449.                         (context!=null ? context.getPddContext(): null),
  450.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository(),
  451.                         dumpRaw);
  452.             }
  453.         }catch(Throwable e){
  454.             String msg = "Inizializzazione di GovWay non correttamente effettuata: DumpRaw";
  455.             logCore.error(msg,  e);
  456.             cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  457.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  458.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  459.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  460.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  461.             return;
  462.         }
  463.        
  464.         // Questo servizio è invocabile solo con API Soap
  465.         if(!ServiceBinding.SOAP.equals(requestInfo.getIntegrationServiceBinding())){
  466.             String msg = "Servizio utilizzabile solamente con API SOAP, riscontrata API REST";
  467.             logCore.error(msg);
  468.             ConnectorDispatcherErrorInfo cInfoError =  ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  469.                     ErroriIntegrazione.ERRORE_439_FUNZIONALITA_NOT_SUPPORTED_BY_PROTOCOL.getErrore439_FunzionalitaNotSupportedByProtocol(msg, protocolFactory),
  470.                     IntegrationFunctionError.NOT_SUPPORTED_BY_PROTOCOL, null, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  471.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(context, logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfoError);
  472.             return;
  473.         }
  474.        
  475.        
  476.        
  477.        
  478.        
  479.        
  480.         /* ------------  Lettura parametri della richiesta ------------- */
  481.        
  482.         // PostOutResponseContext
  483.         PostOutResponseContext postOutResponseContext = null;
  484.        
  485.         PdDContext pddContext = null;
  486.         String errorImbustamentoSoapNonRiuscito = null;
  487.         MessageType messageTypeReq = null;
  488.         OpenSPCoop2Message requestMessage = null;
  489.         OpenSPCoop2Message responseMessage = null;
  490.         String protocol = null;
  491.         byte[] inputBody = null;
  492.        
  493.         try{
  494.            
  495.             /* --------------- Creo il context che genera l'id univoco ----------------------- */
  496.            
  497.             try{
  498.                 msgDiag.mediumDebug("Creazione contesto ...");
  499.             }catch(Exception e){
  500.                 logCore.error("Errore generazione diagnostico",e);
  501.             }
  502.            
  503.             if(protocolFactory==null) {
  504.                 protocolFactory = req.getProtocolFactory();
  505.             }
  506.             protocol = protocolFactory.getProtocol();
  507.            
  508.             if(context==null) {
  509.                 context = new RicezioneContenutiApplicativiContext(idModuloAsService,dataAccettazioneRichiesta,requestInfo);
  510.             }
  511.             if(preInAcceptRequestContext!=null && preInAcceptRequestContext.getPreContext()!=null && !preInAcceptRequestContext.getPreContext().isEmpty()) {
  512.                 context.getPddContext().addAll(preInAcceptRequestContext.getPreContext(), false);
  513.             }
  514.             context.setTipoPorta(TipoPdD.DELEGATA);
  515.             context.setForceFaultAsXML(true); // siamo in una richiesta http senza SOAP, un SoapFault non ha senso
  516.             context.setIdModulo(idModulo);
  517.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  518.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO, req.getRequestInfo());
  519.             RicezionePropertiesConfig rConfig = RicezioneContenutiApplicativiServiceUtils.readPropertiesConfig(req.getRequestInfo(), logCore,null);
  520.             if(rConfig!=null) {
  521.                 if (rConfig.getApiImplementation() != null && !rConfig.getApiImplementation().isEmpty()) {
  522.                    context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_CONFIGURAZIONE, rConfig.getApiImplementation());
  523.                 }
  524.                 if (rConfig.getSoggettoFruitore() != null && !rConfig.getSoggettoFruitore().isEmpty()) {
  525.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_FRUITORE, rConfig.getSoggettoFruitore());
  526.                 }
  527.                 if (rConfig.getSoggettoErogatore() != null && !rConfig.getSoggettoErogatore().isEmpty()) {
  528.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_EROGATORE, rConfig.getSoggettoErogatore());
  529.                 }
  530.             }
  531.             msgDiag.setPddContext(context.getPddContext(),protocolFactory);    
  532.             pddContext = context.getPddContext();
  533.            
  534.             try{
  535.                 if(openSPCoopProperties.isTransazioniEnabled()) {
  536.                     // NOTA: se gia' esiste con l'id di transazione, non viene ricreata
  537.                     TransactionContext.createTransaction((String)pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE),"RicezioneContenutiApplicativiHTTPtoSOAP.2");
  538.                 }
  539.             }catch(Exception e){
  540.                 logCore.error("Errore durante la creazione della transazione",e);
  541.             }
  542.            
  543.             try{
  544.                 msgDiag.logPersonalizzato("ricezioneRichiesta.firstAccessRequestStream");
  545.             }catch(Exception e){
  546.                 logCore.error("Errore generazione diagnostico di ingresso (stream access)",e);
  547.             }
  548.            
  549.             if(dumpRaw!=null && dumpRaw.isActiveDump()){
  550.                 dumpRaw.setPddContext(msgDiag.getPorta(), context.getPddContext());
  551.                 dumpRaw.serializeContext(context, protocol);
  552.             }
  553.            
  554.             DirectVMConnectorInMessage vm = null;
  555.             if(req instanceof DirectVMConnectorInMessage){
  556.                 vm = (DirectVMConnectorInMessage) req;
  557.             }
  558.             else if(req instanceof DumpRawConnectorInMessage){
  559.                 if( ((DumpRawConnectorInMessage)req).getWrappedConnectorInMessage() instanceof DirectVMConnectorInMessage ){
  560.                     vm = (DirectVMConnectorInMessage) ((DumpRawConnectorInMessage)req).getWrappedConnectorInMessage();
  561.                 }
  562.             }
  563.             if(vm!=null && vm.getDirectVMProtocolInfo()!=null){
  564.                 vm.getDirectVMProtocolInfo().setInfo(pddContext);
  565.             }
  566.            
  567.            
  568.            
  569.            
  570.             /* ------------  PostOutResponseContext ------------- */
  571.             postOutResponseContext = new PostOutResponseContext(logCore,protocolFactory);
  572.             postOutResponseContext.setTipoPorta(TipoPdD.DELEGATA);
  573.             postOutResponseContext.setPddContext(pddContext);
  574.             postOutResponseContext.setIdModulo(idModulo);
  575.            
  576.            
  577.            
  578.            
  579.             /* ------------  PreInHandler ------------- */
  580.            
  581.             // build context
  582.             PreInRequestContext preInRequestContext = new PreInRequestContext(pddContext);
  583.             if(pddContextFromServlet!=null){
  584.                 preInRequestContext.getPddContext().addAll(pddContextFromServlet, true);
  585.             }
  586.             preInRequestContext.setTipoPorta(TipoPdD.DELEGATA);
  587.             preInRequestContext.setIdModulo(idModulo);
  588.             preInRequestContext.setProtocolFactory(protocolFactory);
  589.             preInRequestContext.setRequestInfo(requestInfo);
  590.             Map<String, Object> transportContext = new HashMap<>();
  591.             transportContext.put(PreInRequestContext.SERVLET_REQUEST, req);
  592.             transportContext.put(PreInRequestContext.SERVLET_RESPONSE, res);
  593.             preInRequestContext.setTransportContext(transportContext);  
  594.             preInRequestContext.setLogCore(logCore);
  595.            
  596.             // invocazione handler
  597.             GestoreHandlers.preInRequest(preInRequestContext, msgDiag, logCore);
  598.            
  599.             // aggiungo eventuali info inserite nel preInHandler
  600.             pddContext.addAll(preInRequestContext.getPddContext(), false);
  601.            
  602.             // Lettura risposta parametri NotifierInputStream
  603.             NotifierInputStreamParams notifierInputStreamParams = preInRequestContext.getNotifierInputStreamParams();
  604.             context.setNotifierInputStreamParams(notifierInputStreamParams);
  605.            
  606.             // Controllo Content Length se attiva una policy di rate limiting
  607.             req.checkContentLengthLimit();
  608.            
  609.             // Lettura richiesta con il dump
  610.             if(dumpRaw!=null && dumpRaw.isActiveDumpRichiesta()){
  611.                 dumpRaw.serializeRequest(((DumpRawConnectorInMessage)req), false, notifierInputStreamParams);
  612.                 dataIngressoRichiesta = req.getDataIngressoRichiesta();
  613.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  614.             }

  615.            
  616.            
  617.            


  618.            
  619.            
  620.            
  621.            
  622.             /* ------------ Controllo ContentType -------------------- */
  623.            
  624.             msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.tipologiaMessaggio");
  625.             messageTypeReq = MessageType.SOAP_11; // rendere parametrico ?
  626.            
  627.            
  628.            
  629.            
  630.             /* ------------  Imbustamento Messaggio di Richiesta ------------- */
  631.             boolean imbustamentoConAttachment = false;
  632.             String tipoAttachment =  HttpConstants.CONTENT_TYPE_OPENSPCOOP2_TUNNEL_SOAP;
  633.             // HeaderTrasporto
  634.             String imb = TransportUtils.getFirstValue(req.getHeaderValues(openSPCoopProperties.getTunnelSOAPKeyWord_headerTrasporto()));
  635.             if(imb!=null && "true".equals(imb.trim())){
  636.                 imbustamentoConAttachment = true;
  637.                 String mime = TransportUtils.getFirstValue(req.getHeaderValues(openSPCoopProperties.getTunnelSOAPKeyWordMimeType_headerTrasporto()));
  638.                 if(mime!=null) {
  639.                     tipoAttachment = mime.trim();
  640.                 }
  641.             }
  642.             if(imb==null){
  643.                 // Proprieta FORMBased
  644.                 imb = TransportUtils.getFirstValue(req.getParameterValues(openSPCoopProperties.getTunnelSOAPKeyWord_urlBased()));
  645.                 if(imb!=null && "true".equals(imb.trim())){
  646.                     imbustamentoConAttachment = true;
  647.                     // lettura eventuale tipo di attachment
  648.                     String mime = TransportUtils.getFirstValue(req.getParameterValues(openSPCoopProperties.getTunnelSOAPKeyWordMimeType_urlBased()));
  649.                     if(mime!=null){
  650.                         tipoAttachment = mime.trim();
  651.                     }
  652.                 }
  653.             }
  654.             if(imb==null){
  655.                 // Vedo se fosse indicato nel transport Context
  656.                 if(transportContext.get(openSPCoopProperties.getTunnelSOAPKeyWord_urlBased())!=null){
  657.                     if("true".equalsIgnoreCase((String)transportContext.get(openSPCoopProperties.getTunnelSOAPKeyWord_urlBased()))){
  658.                         imbustamentoConAttachment = true;
  659.                         // lettura eventuale tipo di attachment
  660.                         if(transportContext.get(openSPCoopProperties.getTunnelSOAPKeyWordMimeType_urlBased())!=null){
  661.                             tipoAttachment = (String) transportContext.get(openSPCoopProperties.getTunnelSOAPKeyWordMimeType_urlBased());
  662.                         }
  663.                     }
  664.                 }
  665.             }

  666.             String tipoLetturaRisposta = null;
  667.             try{
  668.                 Utilities.printFreeMemory("RicezioneContenutiApplicativiHTTPtoSOAP - Pre costruzione richiesta");
  669.                 msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.inCorso");
  670.                 DumpByteArrayOutputStream bout = req.getRequest();
  671.                 if(bout!=null && bout.size()>0) {
  672.                     inputBody = bout.toByteArray();
  673.                     bout.clearResources();
  674.                     bout=null;
  675.                 }
  676.                 if( inputBody == null || inputBody.length<=0 ){
  677.                     throw new Exception("Ricevuto nessun contenuto da imbustare");
  678.                 }
  679.                 req.close();
  680.                 dataIngressoRichiesta = req.getDataIngressoRichiesta();
  681.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  682.                
  683.                 if(imbustamentoConAttachment){
  684.                     tipoLetturaRisposta = "Costruzione messaggio SOAP per Tunnel con mimeType "+tipoAttachment;
  685.                     requestMessage = TunnelSoapUtils.imbustamentoMessaggioConAttachment(org.openspcoop2.pdd.core.Utilities.getOpenspcoop2MessageFactory(logCore,requestInfo, MessageRole.REQUEST),
  686.                             messageTypeReq,MessageRole.REQUEST,inputBody,tipoAttachment,
  687.                             MailcapActivationReader.existsDataContentHandler(tipoAttachment),req.getContentType(), openSPCoopProperties.getHeaderSoapActorIntegrazione());                  
  688.                     requestMessage.setTransportRequestContext(requestInfo.getProtocolContext());                
  689.                 }else{
  690.                     tipoLetturaRisposta = "Imbustamento messaggio in un messaggio SOAP";
  691.                     String contentTypeForEnvelope = null; // todo renderlo parametrico soprattutto per soap1.2
  692.                     //String soapAction = "\"OpenSPCoop2\""; // todo renderlo parametrico
  693.                     String soapAction = "\"GovWay\""; // todo renderlo parametrico
  694.                     OpenSPCoop2MessageParseResult pr = org.openspcoop2.pdd.core.Utilities.getOpenspcoop2MessageFactory(logCore,requestInfo, MessageRole.REQUEST).
  695.                             envelopingMessage(messageTypeReq, contentTypeForEnvelope, soapAction,
  696.                             requestInfo.getProtocolContext(), inputBody, notifierInputStreamParams,
  697.                             openSPCoopProperties.getAttachmentsProcessingMode(),
  698.                             openSPCoopProperties.isDeleteInstructionTargetMachineXml(),
  699.                             openSPCoopProperties.useSoapMessageReader(), openSPCoopProperties.getSoapMessageReaderBufferThresholdKb());
  700.                     if(pr.getParseException()!=null){
  701.                         pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION, pr.getParseException());
  702.                     }
  703.                     requestMessage = pr.getMessage_throwParseException();
  704.                 }
  705.                
  706.                 if(requestInfo.getProtocolContext().getHeaders()==null) {
  707.                     requestInfo.getProtocolContext().setHeaders(new HashMap<>());
  708.                 }
  709.                 requestInfo.getProtocolContext().removeHeader(HttpConstants.CONTENT_TYPE);
  710.                 TransportUtils.setHeader(requestInfo.getProtocolContext().getHeaders(),HttpConstants.CONTENT_TYPE, requestMessage.getContentType());
  711.                 requestInfo.setIntegrationRequestMessageType(requestMessage.getMessageType());
  712.                
  713.                 Utilities.printFreeMemory("RicezioneContenutiApplicativiHTTPtoSOAP - Post costruzione richiesta");
  714.                 requestMessage.setProtocolName(protocolFactory.getProtocol());
  715.                 requestMessage.setTransactionId(PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext));
  716.                 requestMessage.addContextProperty(org.openspcoop2.core.constants.Costanti.REQUEST_INFO,requestInfo); // serve nelle comunicazione non stateless (es. riscontro salvato) per poterlo rispedire
  717.                 requestMessage.addContextProperty(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE,pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)); // serve nelle comunicazione non stateless (es. riscontro salvato) per poterlo rispedire
  718.                 Object nomePortaInvocataObject = context.getPddContext().getObject(CostantiPdD.NOME_PORTA_INVOCATA);
  719.                 if(nomePortaInvocataObject!=null && nomePortaInvocataObject instanceof String) {
  720.                     requestMessage.addContextProperty(CostantiPdD.NOME_PORTA_INVOCATA, (String) nomePortaInvocataObject );
  721.                 }
  722.                                
  723.             }catch(Exception e){
  724.                 logCore.error(tipoLetturaRisposta +" con errore: "+e.getMessage(),e);
  725.                 errorImbustamentoSoapNonRiuscito=tipoLetturaRisposta +" con errore: "+e.getMessage();
  726.                 throw e;
  727.             }
  728.            
  729.            
  730.             /* --------------- SecurityToken --------------- */
  731.             try {
  732.                 if(requestInfo!=null && requestInfo.getProtocolContext()!=null && requestInfo.getProtocolContext().getCredential()!=null &&
  733.                         requestInfo.getProtocolContext().getCredential().getCertificate()!=null &&
  734.                         requestInfo.getProtocolContext().getCredential().getCertificate().getCertificate()!=null) {
  735.                     SecurityTokenUtilities.newSecurityToken(pddContext);
  736.                 }
  737.             }catch(Exception e){
  738.                 logCore.error("Costruzione SecurityToken non riuscito: "+e.getMessage(),e);
  739.             }
  740.            
  741.             /* ------------  Elaborazione ------------- */
  742.        
  743.             // Contesto di Richiesta
  744.             context.setCredenziali(new Credenziali(req.getCredential()));
  745.             context.setGestioneRisposta(true); // siamo in una servlet, la risposta deve essere aspettata
  746.             context.setInvocazionePDPerRiferimento(false); // la PD con questa servlet non effettuera' mai invocazioni per riferimento.
  747.             context.setMessageRequest(requestMessage);
  748.             context.setUrlProtocolContext(requestInfo.getProtocolContext());
  749.             context.setMsgDiagnostico(msgDiag);
  750.                    
  751.             // Log elaborazione dati completata
  752.             msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.completata");
  753.            
  754.             // se il tracciamento lo prevedo emetto un log
  755.             registraTracciaInRequest(context, protocolFactory, logCore, msgDiag);
  756.            
  757.             // Invocazione...
  758.             RicezioneContenutiApplicativi gestoreRichiesta = new RicezioneContenutiApplicativi(context, this.generatoreErrore);
  759.             gestoreRichiesta.process(req);
  760.             responseMessage = context.getMessageResponse();
  761.                        
  762.         } catch (Throwable e) {
  763.            
  764.             if(context==null){
  765.                 // Errore durante la generazione dell'id
  766.                 context = RicezioneContenutiApplicativiContext.newRicezioneContenutiApplicativiContext(idModuloAsService,dataAccettazioneRichiesta,requestInfo);
  767.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  768.                 context.setTipoPorta(TipoPdD.DELEGATA);
  769.                 context.setForceFaultAsXML(true); // siamo in una richiesta http senza SOAP, un SoapFault non ha senso
  770.                 context.setIdModulo(idModulo);
  771.                 context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  772.                 pddContext = context.getPddContext();
  773.                 msgDiag.setPddContext(pddContext,protocolFactory);
  774.                 if(postOutResponseContext!=null){
  775.                     postOutResponseContext.setPddContext(pddContext);
  776.                 }
  777.             }
  778.            
  779.             // Se viene lanciata una eccezione, riguarda la richiesta, altrimenti è gestita dopo nel finally.
  780.             Throwable tParsing = null;
  781.             ParseException parseException = null;
  782.             if(pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION)){
  783.                 parseException = (ParseException) pddContext.removeObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  784.                 if(parseException!=null) {
  785.                     tParsing = parseException.getParseException();
  786.                 }
  787.             }
  788.             if(tParsing==null && (requestMessage==null || requestMessage.getParseException() == null)){
  789.                 tParsing = ParseExceptionUtils.getParseException(e);
  790.             }
  791.                    
  792.             // Genero risposta con errore
  793.             if(errorImbustamentoSoapNonRiuscito!=null){
  794.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  795.                 logCore.error("ImbustamentoSOAP",e);
  796.                 Throwable tMessage = null;
  797.                 if(tParsing!=null){
  798.                     tMessage = tParsing;
  799.                 }
  800.                 else{
  801.                     tMessage = e;
  802.                 }
  803.                 String msgErrore = tMessage.getMessage();
  804.                 if(msgErrore==null){
  805.                     msgErrore = tMessage.toString();
  806.                 }
  807.                 msgDiag.logErroreGenerico(errorImbustamentoSoapNonRiuscito+"  "+msgErrore, "ImbustamentoSOAP");
  808.                
  809.                 IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_REQUEST_CONTENT;
  810.                 if( parseException!=null && parseException.getSourceException()!=null &&
  811.                         TimeoutIOException.isTimeoutIOException(parseException.getSourceException())) {
  812.                     integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  813.                 }
  814.                 else if( parseException!=null && parseException.getSourceException()!=null &&
  815.                         LimitExceededIOException.isLimitExceededIOException(parseException.getSourceException())) {
  816.                     integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  817.                 }
  818.                
  819.                 responseMessage = this.generatoreErrore.build(pddContext,integrationFunctionError,
  820.                         ErroriIntegrazione.ERRORE_422_IMBUSTAMENTO_SOAP_NON_RIUSCITO_RICHIESTA_APPLICATIVA.
  821.                         getErrore422_MessaggioSOAPNonGenerabileTramiteImbustamentoSOAP(errorImbustamentoSoapNonRiuscito),tMessage,null);
  822.             }
  823.             else if(tParsing!=null){
  824.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  825.                 String msgErrore = tParsing.getMessage();
  826.                 if(msgErrore==null){
  827.                     msgErrore = tParsing.toString();
  828.                 }
  829.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  830.                 logCore.error("parsingExceptionRichiesta",e);
  831.                 msgDiag.logPersonalizzato("parsingExceptionRichiesta");
  832.                
  833.                 IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_REQUEST_CONTENT;
  834.                 if( parseException!=null && parseException.getSourceException()!=null &&
  835.                         TimeoutIOException.isTimeoutIOException(parseException.getSourceException())) {
  836.                     integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  837.                 }
  838.                 else if( parseException!=null && parseException.getSourceException()!=null &&
  839.                         LimitExceededIOException.isLimitExceededIOException(parseException.getSourceException())) {
  840.                     integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  841.                 }
  842.                
  843.                 responseMessage = this.generatoreErrore.build(pddContext,integrationFunctionError,
  844.                         ErroriIntegrazione.ERRORE_432_PARSING_EXCEPTION_RICHIESTA.
  845.                         getErrore432_MessaggioRichiestaMalformato(tParsing),tParsing,null);
  846.             }
  847.             else if (e instanceof HandlerException) {
  848.                 logCore.error("ErroreGenerale (HandlerException)",e);
  849.                 HandlerException he = (HandlerException) e;
  850.                 if(he.isEmettiDiagnostico()) {
  851.                     msgDiag.logErroreGenerico(e, "Generale(richiesta-handler)");
  852.                 }
  853.                 ErroreIntegrazione errore = he.convertToErroreIntegrazione();
  854.                 if(errore==null) {
  855.                     errore = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.get5XX_ErroreProcessamento("Generale(richiesta)");
  856.                 }
  857.                 IntegrationFunctionError integrationError = he.getIntegrationFunctionError();
  858.                 if(integrationError==null) {
  859.                     integrationError = IntegrationFunctionError.BAD_REQUEST;
  860.                 }
  861.                 responseMessage = this.generatoreErrore.build(pddContext,integrationError,errore,e,null);
  862.                 he.customized(responseMessage);
  863.             }
  864.             else{
  865.                 logCore.error("ErroreGenerale",e);
  866.                 msgDiag.logErroreGenerico(e, "Generale(richiesta)");
  867.                 responseMessage = this.generatoreErrore.build(pddContext,IntegrationFunctionError.BAD_REQUEST,
  868.                         ErroriIntegrazione.ERRORE_426_SERVLET_ERROR.
  869.                         getErrore426_ServletError(true, e),e,null);
  870.             }
  871.         }
  872.         finally{

  873.             try {
  874.                 GestoreRichieste.saveRequestConfig(requestInfo);
  875.             }catch(Throwable e) {
  876.                 logCore.error("Errore durante il salvataggio dei dati della richiesta: "+e.getMessage(),e);
  877.             }          

  878.             if((requestMessage!=null && requestMessage.getParseException() != null) ||
  879.                     (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION))){
  880.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  881.                 ParseException parseException = null;
  882.                 if( requestMessage!=null && requestMessage.getParseException() != null ){
  883.                     parseException = requestMessage.getParseException();
  884.                 }
  885.                 else{
  886.                     parseException = (ParseException) pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  887.                 }
  888.                 String msgErrore = parseException.getParseException().getMessage();
  889.                 if(msgErrore==null){
  890.                     msgErrore = parseException.getParseException().toString();
  891.                 }
  892.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  893.                 logCore.error("parsingExceptionRichiesta",parseException.getSourceException());
  894.                 msgDiag.logPersonalizzato("parsingExceptionRichiesta");
  895.                
  896.                 IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_REQUEST_CONTENT;
  897.                 if( parseException!=null && parseException.getSourceException()!=null &&
  898.                         TimeoutIOException.isTimeoutIOException(parseException.getSourceException())) {
  899.                     integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  900.                 }
  901.                 else if( parseException!=null && parseException.getSourceException()!=null &&
  902.                         LimitExceededIOException.isLimitExceededIOException(parseException.getSourceException())) {
  903.                     integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  904.                 }
  905.                
  906.                 responseMessage = this.generatoreErrore.build(pddContext, integrationFunctionError,
  907.                         ErroriIntegrazione.ERRORE_432_PARSING_EXCEPTION_RICHIESTA.
  908.                         getErrore432_MessaggioRichiestaMalformato(parseException.getParseException()),
  909.                         parseException.getParseException(),null);
  910.             }
  911.             else if( (responseMessage!=null && responseMessage.getParseException() != null) ||
  912.                     (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION))){
  913.                 if(pddContext!=null) {
  914.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO, true);
  915.                 }
  916.                 ParseException parseException = null;
  917.                 if( responseMessage!=null && responseMessage.getParseException() != null ){
  918.                     parseException = responseMessage.getParseException();
  919.                 }
  920.                 else{
  921.                     parseException = (ParseException) pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  922.                 }
  923.                 String msgErrore = parseException.getParseException().getMessage();
  924.                 if(msgErrore==null){
  925.                     msgErrore = parseException.getParseException().toString();
  926.                 }
  927.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  928.                 logCore.error("parsingExceptionRisposta",parseException.getSourceException());
  929.                 msgDiag.logPersonalizzato("parsingExceptionRisposta");
  930.                 responseMessage = this.generatoreErrore.build(pddContext, IntegrationFunctionError.UNPROCESSABLE_RESPONSE_CONTENT,
  931.                         ErroriIntegrazione.ERRORE_440_PARSING_EXCEPTION_RISPOSTA.
  932.                         getErrore440_MessaggioRispostaMalformato(parseException.getParseException()),
  933.                         parseException.getParseException(),null);
  934.             }
  935.            
  936.             try{
  937.                 // Se non sono stati recuperati i dati delle url, provo a recuperarli
  938.                 URLProtocolContext urlProtocolContext = context!=null ? context.getUrlProtocolContext() : null;
  939.                 if(urlProtocolContext==null){
  940.                     urlProtocolContext = req.getURLProtocolContext();
  941.                 }
  942.                 if(urlProtocolContext!=null){
  943.                     String urlInvocazione = urlProtocolContext.getUrlInvocazione_formBased();
  944.                     if(urlProtocolContext.getFunction()!=null){
  945.                         urlInvocazione = "["+urlProtocolContext.getFunction()+"] "+urlInvocazione;
  946.                     }
  947.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.URL_INVOCAZIONE, urlInvocazione);
  948.                 }
  949.             }catch(Throwable t){}
  950.             try{
  951.                 Credenziali credenziali = context!=null ? context.getCredenziali() : null;
  952.                 if(credenziali==null){
  953.                     credenziali = new Credenziali(req.getCredential());
  954.                 }
  955.                 if(credenziali!=null && pddContext!=null){
  956.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CREDENZIALI_INVOCAZIONE, credenziali.toString());
  957.                 }
  958.             }catch(Throwable t){}
  959.            
  960.             // *** GB ***
  961.             try{
  962.                 req.close();
  963.             }catch(Exception e){
  964.                 logCore.error("Request.close() error: "+e.getMessage(),e);
  965.             }
  966.             // *** GB ***
  967.         }
  968.            
  969.            
  970.         // Imposto risposta

  971.         Date dataPrimaSpedizioneRisposta = DateManager.getDate();
  972.         Date dataRispostaSpedita = null;
  973.         Transazione transazioneDaAggiornare = null;
  974.        
  975.         if(context.getMsgDiagnostico()!=null){
  976.             msgDiag = context.getMsgDiagnostico();
  977.         }
  978.         if(context.getResponseHeaders()==null) {
  979.             context.setResponseHeaders(new HashMap<>());
  980.         }
  981.         ServicesUtils.setGovWayHeaderResponse(requestMessage!=null ? requestMessage.getServiceBinding() : requestInfo.getProtocolServiceBinding(),
  982.                 responseMessage, openSPCoopProperties,
  983.                 context.getResponseHeaders(), logCore, true, context.getPddContext(), requestInfo);
  984.         if(context.getResponseHeaders()!=null){
  985.             Iterator<String> keys = context.getResponseHeaders().keySet().iterator();
  986.             while (keys.hasNext()) {
  987.                 String key = (String) keys.next();
  988.                 List<String> values = context.getResponseHeaders().get(key);
  989.                 if(values!=null && !values.isEmpty()) {
  990.                     for (int i = 0; i < values.size(); i++) {
  991.                         String value = values.get(i);
  992.                         String verbo = "";
  993.                         try{
  994.                             if(i==0) {
  995.                                 verbo = "set";
  996.                                 res.setHeader(key,value);
  997.                             }
  998.                             else {
  999.                                 verbo = "add";
  1000.                                 res.addHeader(key,value);
  1001.                             }
  1002.                         }catch(Exception e){
  1003.                             logCore.error("Response."+verbo+"Header("+key+","+value+") error: "+e.getMessage(),e);
  1004.                         }  
  1005.                     }
  1006.                 }
  1007.             }  
  1008.         }
  1009.         if(context!=null && context.getProtocol()!=null){
  1010.            
  1011.             this.generatoreErrore.updateDominio(context.getIdentitaPdD());
  1012.            
  1013.             IDServizio idServizio = null;
  1014.             try{
  1015.                 idServizio = IDServizioFactory.getInstance().getIDServizioFromValues(context.getProtocol().getTipoServizio(),
  1016.                         context.getProtocol().getServizio(),
  1017.                         context.getProtocol().getErogatore(),
  1018.                         context.getProtocol().getVersioneServizio());
  1019.             }catch(Exception e){
  1020.                 // non dovrebbe succedere eccezione}
  1021.             }
  1022.             if(idServizio!=null){
  1023.                 idServizio.setAzione(context.getProtocol().getAzione());
  1024.                 this.generatoreErrore.updateInformazioniCooperazione(context.getProtocol().getFruitore(), idServizio);
  1025.             }
  1026.                        
  1027.             String servizioApplicativo = null;
  1028.             if(context.getIntegrazione()!=null){
  1029.                 servizioApplicativo = context.getIntegrazione().getServizioApplicativoFruitore();
  1030.             }
  1031.             this.generatoreErrore.updateInformazioniCooperazione(servizioApplicativo);
  1032.            
  1033.             this.generatoreErrore.updateProprietaErroreApplicativo(context.getProprietaErroreAppl());
  1034.            
  1035.         }
  1036.         DirectVMConnectorOutMessage vm = null;
  1037.         if(res instanceof DirectVMConnectorOutMessage){
  1038.             vm = (DirectVMConnectorOutMessage) res;
  1039.         }
  1040.         else if(req instanceof DumpRawConnectorOutMessage){
  1041.             if( ((DumpRawConnectorOutMessage)res).getWrappedConnectorOutMessage() instanceof DirectVMConnectorOutMessage ){
  1042.                 vm = (DirectVMConnectorOutMessage) ((DumpRawConnectorOutMessage)res).getWrappedConnectorOutMessage();
  1043.             }
  1044.         }
  1045.         if(vm!=null){
  1046.             if(context!=null && context.getPddContext()!=null){
  1047.                 DirectVMProtocolInfo pInfo = new DirectVMProtocolInfo();
  1048.                 Object oIdTransazione = context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  1049.                 if(oIdTransazione!=null){
  1050.                     pInfo.setIdTransazione((String)oIdTransazione);
  1051.                 }
  1052.                 if(context.getProtocol()!=null){
  1053.                     if(context.getProtocol().getIdRichiesta()!=null){
  1054.                         pInfo.setIdMessaggioRichiesta(context.getProtocol().getIdRichiesta());
  1055.                     }
  1056.                     if(context.getProtocol().getIdRisposta()!=null){
  1057.                         pInfo.setIdMessaggioRisposta(context.getProtocol().getIdRisposta());
  1058.                     }
  1059.                 }
  1060.                 vm.setDirectVMProtocolInfo(pInfo);
  1061.             }
  1062.         }
  1063.        
  1064.         InformazioniErroriInfrastrutturali informazioniErrori = ServicesUtils.readInformazioniErroriInfrastrutturali(pddContext);
  1065.        
  1066.         EsitoTransazione esito = null;
  1067.         String descrizioneSoapFault = "";
  1068.         int statoServletResponse = 200;
  1069.         Throwable erroreConsegnaRisposta = null;
  1070.         boolean httpEmptyResponse = false;
  1071.         long lengthOutResponse = -1;
  1072.         boolean erroreConnessioneClient = false;
  1073.         boolean sendInvoked = false;
  1074.         boolean registraTracciaOutResponse = false;
  1075.         try{
  1076.             if(responseMessage!=null && !responseMessage.isForcedEmptyResponse() && (responseMessage.getForcedResponse()==null)){
  1077.                    
  1078.                 // force response code
  1079.                 boolean forced = false;
  1080.                 if(responseMessage.getForcedResponseCode()!=null){
  1081.                     try{
  1082.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1083.                         forced = true;
  1084.                     }catch(Exception e){}
  1085.                 }
  1086.                
  1087.                 if(ServiceBinding.SOAP.equals(responseMessage.getServiceBinding())) {
  1088.                                        
  1089.                     SOAPBody body = responseMessage.castAsSoap().getSOAPBody();
  1090.                     String contentTypeRisposta = null;
  1091.                     byte[] risposta = null;
  1092.                     if(body!=null && body.hasFault()){
  1093.                         statoServletResponse = 500; // cmq e' un errore come l'errore applicativo
  1094.                         String msgError = SoapUtils.safe_toString(responseMessage.getFactory(), body.getFault(), false, logCore);
  1095.                         //risposta=msgError.getBytes();
  1096.                         org.openspcoop2.message.xml.MessageXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.getInstance(responseMessage.getFactory());
  1097.                         risposta=xmlUtils.toByteArray(body.getFault(), true);
  1098.                         //System.out.println("ELABORATO:"+new String(risposta));
  1099.                         contentTypeRisposta = responseMessage.getContentType();
  1100.                         descrizioneSoapFault = " ("+msgError+")";  
  1101.                     }else{
  1102.                         risposta=TunnelSoapUtils.sbustamentoMessaggio(responseMessage);
  1103.                         if(risposta==null || risposta.length<=0){
  1104.                             // Si puo' entrare in questo caso, se nel messaggio Soap vi era presente solo l'header
  1105.                             risposta = null;
  1106.                             if(!forced)
  1107.                                 statoServletResponse = 202;
  1108.                         }else{
  1109.                            
  1110.                             SOAPElement child = SoapUtils.getNotEmptyFirstChildSOAPElement(body);
  1111.                             if(child!=null){
  1112.                                 if(protocolFactory.createErroreApplicativoBuilder().isErroreApplicativo(child)){
  1113.                                     statoServletResponse = 500;
  1114.                                 }
  1115.                             }
  1116.                            
  1117.                             // Non serve la updateContentType. Il messaggio e' gia' stato serializzato ed il cType e' corretto.  
  1118.                             if(TunnelSoapUtils.isTunnelOpenSPCoopSoap(responseMessage.getFactory(), body)){
  1119.                                 contentTypeRisposta = TunnelSoapUtils.getContentTypeTunnelOpenSPCoopSoap(body);
  1120.                             }else{
  1121.                                 contentTypeRisposta = responseMessage.getContentType();
  1122.                             }
  1123.                         }
  1124.                     }
  1125.                    
  1126.                     // transfer length
  1127.                     if(risposta!=null){
  1128.                         lengthOutResponse = risposta.length;
  1129.                         ServicesUtils.setTransferLength(openSPCoopProperties.getTransferLengthModes_ricezioneContenutiApplicativi(),
  1130.                                 req, res, Long.valueOf(risposta.length));
  1131.                     }
  1132.                    
  1133.                     // httpstatus
  1134.                     res.setStatus(statoServletResponse);
  1135.                    
  1136.                     // content type
  1137.                     if(contentTypeRisposta!=null){
  1138.                         res.setContentType(contentTypeRisposta);
  1139.                     }
  1140.                    
  1141.                     // esito calcolato prima del sendResponse, per non consumare il messaggio
  1142.                     esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1143.                             statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1144.                             responseMessage, context.getProprietaErroreAppl(),informazioniErrori,
  1145.                             pddContext);
  1146.                    
  1147.                     // httpHeaders
  1148.                     res.sendResponseHeaders(responseMessage);                  
  1149.                    
  1150.                     // se il tracciamento lo prevedo emetto un log
  1151.                     registraTracciaOutResponse = true;
  1152.                     transazioneDaAggiornare = registraTracciaOutResponse(context, protocolFactory, postOutResponseContext,
  1153.                             dataAccettazioneRichiesta, dataIngressoRichiesta,
  1154.                             dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1155.                             esito, statoServletResponse,
  1156.                             idModulo, req,  requestMessage, inputBody,
  1157.                             responseMessage, erroreConsegnaRisposta, lengthOutResponse,
  1158.                             msgDiag);
  1159.                    
  1160.                     // contenuto
  1161.                     if(risposta!=null){
  1162.                         sendInvoked = true;
  1163.                         res.sendResponse(DumpByteArrayOutputStream.newInstance(risposta));
  1164.                     }
  1165.                 }
  1166.                 else {
  1167.                    
  1168.                     // transfer length
  1169.                     ServicesUtils.setTransferLength(openSPCoopProperties.getTransferLengthModes_ricezioneContenutiApplicativi(),
  1170.                             req, res, responseMessage);
  1171.                    
  1172.                     // content type
  1173.                     // Alcune implementazioni richiedono di aggiornare il Content-Type
  1174.                     responseMessage.updateContentType();
  1175.                     ServicesUtils.setContentType(responseMessage, res);
  1176.                    
  1177.                     // http status
  1178.                     boolean consume = true;
  1179.                     if(responseMessage.castAsRest().isProblemDetailsForHttpApis_RFC7807() ||
  1180.                             (MessageRole.FAULT.equals(responseMessage.getMessageRole()) &&
  1181.                                 (
  1182.                                 MessageType.XML.equals(responseMessage.getMessageType())
  1183.                                         ||
  1184.                                 MessageType.JSON.equals(responseMessage.getMessageType())
  1185.                                 )
  1186.                             )
  1187.                         ) {
  1188.                         consume = false; // può essere usato nel post out response handler
  1189.                         String contentAsString = null;
  1190.                         try {
  1191.                             contentAsString = responseMessage.castAsRest().getContentAsString();
  1192.                         }catch(Throwable t) {
  1193.                             logCore.error("Parsing errore non riuscito: "+t.getMessage(),t);
  1194.                         }
  1195.                         if(contentAsString!=null && StringUtils.isNotEmpty(contentAsString)) {
  1196.                             descrizioneSoapFault = " ("+contentAsString+")";
  1197.                         }
  1198.                     }
  1199.                     res.setStatus(statoServletResponse);
  1200.                    
  1201.                     // esito calcolato prima del sendResponse, per non consumare il messaggio
  1202.                     esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1203.                             statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1204.                             responseMessage, context.getProprietaErroreAppl(), informazioniErrori,
  1205.                             pddContext);
  1206.                    
  1207.                     // se il tracciamento lo prevedo emetto un log
  1208.                     registraTracciaOutResponse = true;
  1209.                     transazioneDaAggiornare = registraTracciaOutResponse(context, protocolFactory, postOutResponseContext,
  1210.                             dataAccettazioneRichiesta, dataIngressoRichiesta,
  1211.                             dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1212.                             esito, statoServletResponse,
  1213.                             idModulo, req,  requestMessage, inputBody,
  1214.                             responseMessage, erroreConsegnaRisposta, lengthOutResponse,
  1215.                             msgDiag);
  1216.                    
  1217.                     // contenuto
  1218.                     Utilities.printFreeMemory("RicezioneContenutiApplicativiDirect - Pre scrittura risposta");
  1219.                    
  1220.                     // Il contentLenght, nel caso di TransferLengthModes.CONTENT_LENGTH e' gia' stato calcolato
  1221.                     // con una writeTo senza consume. Riuso il solito metodo per evitare differenze di serializzazione
  1222.                     // e cambiare quindi il content length effettivo.
  1223.                     sendInvoked = true;
  1224.                     if(TransferLengthModes.CONTENT_LENGTH.equals(openSPCoopProperties.getTransferLengthModes_ricezioneContenutiApplicativi())){
  1225.                         res.sendResponse(responseMessage, false);
  1226.                     } else {
  1227.                         res.sendResponse(responseMessage, consume);
  1228.                     }
  1229.                     Utilities.printFreeMemory("RicezioneContenutiApplicativiDirect - Post scrittura risposta");
  1230.                    
  1231.                 }
  1232.                
  1233.             }
  1234.             else if(responseMessage!=null && responseMessage.getForcedResponse()!=null) {
  1235.                 byte[]response = responseMessage.getForcedResponse().getContent();
  1236. //              if(response==null) {
  1237. //                  throw new Exception("Trovata configurazione 'forcedResponse' senza una vera risposta");
  1238. //              }
  1239.                 if(response!=null) {
  1240.                     lengthOutResponse = response.length;
  1241.                 }
  1242.            
  1243.                 if(response!=null && response.length<1024) {
  1244.                     // Se il messaggio non è troppo grande lo aggiungo al diagnostico
  1245.                     try {
  1246.                         descrizioneSoapFault = "("+new String(response)+")";
  1247.                     }catch(Throwable t) {
  1248.                         descrizioneSoapFault = "";
  1249.                     }
  1250.                 }
  1251.                
  1252.                 if(responseMessage.getForcedResponse().getHeadersValues()!=null &&
  1253.                         responseMessage.getForcedResponse().getHeadersValues().size()>0) {
  1254.                     Iterator<String> keys = responseMessage.getForcedResponse().getHeadersValues().keySet().iterator();
  1255.                     while (keys.hasNext()) {
  1256.                         String key = (String) keys.next();
  1257.                         List<String> values = responseMessage.getForcedResponse().getHeadersValues().get(key);
  1258.                         if(values!=null && !values.isEmpty()) {
  1259.                             for (int i = 0; i < values.size(); i++) {
  1260.                                 String value = values.get(i);
  1261.                                 String verbo = "";
  1262.                                 try{
  1263.                                     if(i==0) {
  1264.                                         verbo = "set";
  1265.                                         res.setHeader(key,value);
  1266.                                     }
  1267.                                     else {
  1268.                                         verbo = "add";
  1269.                                         res.addHeader(key,value);
  1270.                                     }
  1271.                                 }catch(Exception e){
  1272.                                     logCore.error("Response(Forced)."+verbo+"Header("+key+","+value+") error: "+e.getMessage(),e);
  1273.                                 }  
  1274.                             }
  1275.                         }
  1276.                     }  
  1277.                 }
  1278.                
  1279.                 if(responseMessage.getForcedResponse().getContentType()!=null) {
  1280.                     res.setContentType(responseMessage.getForcedResponse().getContentType());
  1281.                 }
  1282.                
  1283.                 if(responseMessage.getForcedResponse().getResponseCode()!=null) {
  1284.                     try{
  1285.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponse().getResponseCode());
  1286.                     }catch(Exception e){}
  1287.                 }
  1288.                 else if(responseMessage!=null && responseMessage.getForcedResponseCode()!=null) {
  1289.                     try{
  1290.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1291.                     }catch(Exception e){}
  1292.                 }
  1293.                 res.setStatus(statoServletResponse);
  1294.                
  1295.                 // esito calcolato prima del sendResponse, per non consumare il messaggio
  1296.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1297.                         statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1298.                         responseMessage, context.getProprietaErroreAppl(),informazioniErrori,
  1299.                         pddContext);
  1300.                
  1301.                 // se il tracciamento lo prevedo emetto un log
  1302.                 registraTracciaOutResponse = true;
  1303.                 transazioneDaAggiornare = registraTracciaOutResponse(context, protocolFactory, postOutResponseContext,
  1304.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1305.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1306.                         esito, statoServletResponse,
  1307.                         idModulo, req,  requestMessage, inputBody,
  1308.                         responseMessage, erroreConsegnaRisposta, lengthOutResponse,
  1309.                         msgDiag);
  1310.                
  1311.                 if(response!=null) {
  1312.                     sendInvoked = true;
  1313.                     res.sendResponse(DumpByteArrayOutputStream.newInstance(response));
  1314.                 }
  1315.                
  1316.             }          
  1317.             else{
  1318.                 // httpstatus
  1319.                 if(responseMessage!=null && responseMessage.getForcedResponseCode()!=null) {
  1320.                     try{
  1321.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1322.                     }catch(Exception e){}
  1323.                 }
  1324.                 else {
  1325.                     statoServletResponse = protocolFactory.createProtocolManager().getHttpReturnCodeEmptyResponseOneWay();
  1326.                 }
  1327.                 res.setStatus(statoServletResponse);
  1328.                 httpEmptyResponse = true;
  1329.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1330.                         statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1331.                         responseMessage, context.getProprietaErroreAppl(),informazioniErrori,
  1332.                         pddContext);
  1333.                 // carico-vuoto
  1334.                
  1335.                 // se il tracciamento lo prevedo emetto un log
  1336.                 registraTracciaOutResponse = true;
  1337.                 transazioneDaAggiornare = registraTracciaOutResponse(context, protocolFactory, postOutResponseContext,
  1338.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1339.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1340.                         esito, statoServletResponse,
  1341.                         idModulo, req,  requestMessage, inputBody,
  1342.                         responseMessage, erroreConsegnaRisposta, lengthOutResponse,
  1343.                         msgDiag);

  1344.             }
  1345.            
  1346.         }catch(Throwable e){
  1347.             logCore.error("ErroreGenerale",e);
  1348.             erroreConsegnaRisposta = e;
  1349.            
  1350.             erroreConnessioneClient = ServicesUtils.isConnessioneClientNonDisponibile(e);
  1351.            
  1352.             try{
  1353.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX);
  1354.             }catch(Exception eBuildError){
  1355.                 esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1356.             }
  1357.            
  1358.             // Genero risposta con errore
  1359.             try{
  1360.                 if(sendInvoked==false) {
  1361.                     // nel caso sia già stato inoltrata una risposta non e' più possibile modificarlo cosi come tutti gli header etc...
  1362.                     byte [] rispostaErrore = null;
  1363.                     List<Integer> returnCode = new ArrayList<Integer>();
  1364.                     InformazioniErroriInfrastrutturali informazioniErrori_error = null;
  1365.                     if( (responseMessage!=null && responseMessage.getParseException() != null) ||
  1366.                             (pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION))){
  1367.                         ParseException parseException = null;
  1368.                         if( responseMessage!=null && responseMessage.getParseException() != null ){
  1369.                             parseException = responseMessage.getParseException();
  1370.                         }
  1371.                         else{
  1372.                             parseException = (ParseException) pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  1373.                         }
  1374.                         String msgErrore = parseException.getParseException().getMessage();
  1375.                         if(msgErrore==null){
  1376.                             msgErrore = parseException.getParseException().toString();
  1377.                         }
  1378.                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  1379.                         logCore.error("parsingExceptionRisposta",parseException.getSourceException());
  1380.                         msgDiag.logPersonalizzato("parsingExceptionRisposta");
  1381.                                            
  1382.                         rispostaErrore = this.generatoreErrore.buildAsByteArray(pddContext, IntegrationFunctionError.UNPROCESSABLE_RESPONSE_CONTENT,
  1383.                                 ErroriIntegrazione.ERRORE_440_PARSING_EXCEPTION_RISPOSTA.
  1384.                                 getErrore440_MessaggioRispostaMalformato(parseException.getParseException()),
  1385.                                 returnCode);
  1386.                        
  1387.                         informazioniErrori_error = new InformazioniErroriInfrastrutturali();
  1388.                         informazioniErrori_error.setContenutoRispostaNonRiconosciuto(true);
  1389.                     }
  1390.                     else{
  1391.                         IntegrationFunctionError ife = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  1392.                         if(e instanceof HandlerException) {
  1393.                             HandlerException he = (HandlerException) e;
  1394.                             if(he.getIntegrationFunctionError()!=null) {
  1395.                                 ife = he.getIntegrationFunctionError();
  1396.                             }
  1397.                         }
  1398.                         rispostaErrore = this.generatoreErrore.buildAsByteArray(pddContext, ife,
  1399.                                 ErroriIntegrazione.ERRORE_426_SERVLET_ERROR.
  1400.                                 getErrore426_ServletError(false, e),
  1401.                                 returnCode);
  1402.                     }
  1403.                    
  1404.                     // transfer length
  1405.                     lengthOutResponse = rispostaErrore.length;
  1406.                     ServicesUtils.setTransferLength(openSPCoopProperties.getTransferLengthModes_ricezioneContenutiApplicativi(),
  1407.                             req, res, Long.valueOf(rispostaErrore.length));
  1408.                    
  1409.                     // httpstatus
  1410.                     //statoServletResponse = 500; // Nella servlet con sbustamento non devo ritornare 500
  1411.                     statoServletResponse = 200;
  1412.                     if(returnCode!=null && returnCode.size()>0){
  1413.                         statoServletResponse = returnCode.get(0);
  1414.                     }
  1415.                     res.setStatus(statoServletResponse);
  1416.                    
  1417.                     // esito calcolato prima del sendResponse, per non consumare il messaggio
  1418.                     if(informazioniErrori_error!=null) {
  1419.                         esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1420.                                 statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1421.                                 null, context.getProprietaErroreAppl(), informazioniErrori_error,
  1422.                                 pddContext);
  1423.                     }
  1424.                    
  1425.                     // content type
  1426.                     res.setContentType("text/xml");
  1427.                    
  1428.                     // se il tracciamento lo prevedo emetto un log
  1429.                     // se ho già provato prima a tracciare non lo faccio un'altra volta
  1430.                     if(!registraTracciaOutResponse) {
  1431.                         transazioneDaAggiornare = registraTracciaOutResponse(context, protocolFactory, postOutResponseContext,
  1432.                             dataAccettazioneRichiesta, dataIngressoRichiesta,
  1433.                             dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1434.                             esito, statoServletResponse,
  1435.                             idModulo, req,  requestMessage, inputBody,
  1436.                             responseMessage, erroreConsegnaRisposta, lengthOutResponse,
  1437.                             msgDiag);
  1438.                     }
  1439.                    
  1440.                     // contenuto
  1441.                     res.sendResponse(DumpByteArrayOutputStream.newInstance(rispostaErrore));
  1442.                 }
  1443.                        
  1444.             }catch(Throwable error){
  1445.                
  1446.                 if(!erroreConnessioneClient){
  1447.                     erroreConnessioneClient = ServicesUtils.isConnessioneClientNonDisponibile(error);
  1448.                 }
  1449.                
  1450.                 logCore.error("Generazione di un risposta errore non riuscita",error);
  1451.                 statoServletResponse = 500; // ERRORE EFFETTIVO!
  1452.                 try{
  1453.                     res.setStatus(500);
  1454.                 }catch(Exception eStatus){
  1455.                     logCore.error("Response.setStatus(500) error: "+eStatus.getMessage(),eStatus);
  1456.                 }
  1457.                 byte[] ris = error.toString().getBytes();
  1458.                 try{
  1459.                     res.sendResponse(DumpByteArrayOutputStream.newInstance(ris));
  1460.                 }catch(Exception erroreStreamChiuso){
  1461.                     erroreConnessioneClient = true;
  1462.                     //se lo stream non e' piu' disponibile non si potra' consegnare alcuna risposta
  1463.                 }
  1464.                 lengthOutResponse = ris.length;
  1465.             }
  1466.            
  1467.         }
  1468.         finally{
  1469.             if(sendInvoked==false) {
  1470.                 // nel caso sia già stato inoltrata una risposta non e' più possibile modificarlo cosi come tutti gli header etc...        
  1471.                 statoServletResponse = res.getResponseStatus(); // puo' essere "trasformato" da api engine
  1472.             }
  1473.             msgDiag.addKeyword(CostantiPdD.KEY_CODICE_CONSEGNA, ""+statoServletResponse);
  1474.             msgDiag.addKeyword(CostantiPdD.KEY_SOAP_FAULT, descrizioneSoapFault);
  1475.            
  1476.             try{
  1477.                
  1478.                 // Flush and close response
  1479.                 // NOTA: per poter ottenere l'errore di BrokenPipe sempre, deve essere disabilitato il socketBufferOutput sul servlet container.
  1480.                 // Se non lo si disabilta, l'errore viene ritornato solo se il messaggio supera la dimensione del buffer (default: 8192K)
  1481.                 // Ad esempio in tomcat utilizzare (socketBuffer="-1"):
  1482.                 //    <Connector protocol="HTTP/1.1" port="8080" address="${jboss.bind.address}"
  1483.                 //       connectionTimeout="20000" redirectPort="8443" socketBuffer="-1" />
  1484.                 res.flush(true);
  1485.                 res.close(true);
  1486.                
  1487.                 dataRispostaSpedita = DateManager.getDate();
  1488.                
  1489.                 // Emetto diagnostico
  1490.                 if(erroreConsegnaRisposta!=null){
  1491.                    
  1492.                     // Risposta non ritornata al servizio applicativo, il socket verso il servizio applicativo era chiuso o cmq inutilizzabile
  1493.                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_CONSEGNA, erroreConsegnaRisposta.toString()); // NOTA: lasciare e.toString()
  1494.                     msgDiag.logPersonalizzato("consegnaRispostaApplicativaFallita");
  1495.                    
  1496.                 }else{
  1497.                     if(httpEmptyResponse){
  1498.                         msgDiag.logPersonalizzato("consegnaRispostaApplicativaVuota");
  1499.                     }else{
  1500.                         if(statoServletResponse>=300)
  1501.                             msgDiag.logPersonalizzato("consegnaRispostaApplicativaKoEffettuata");
  1502.                         else
  1503.                             msgDiag.logPersonalizzato("consegnaRispostaApplicativaOkEffettuata");
  1504.                     }
  1505.                 }
  1506.                
  1507.             }catch(Exception e){
  1508.                
  1509.                 erroreConnessioneClient = true;
  1510.                
  1511.                 logCore.error("Chiusura stream non riuscita",e);
  1512.                
  1513.                 // Risposta non ritornata al servizio applicativo, il socket verso il servizio applicativo era chiuso o cmq inutilizzabile
  1514.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_CONSEGNA, e.toString()); // NOTA: lasciare e.toString()
  1515.                
  1516.                 msgDiag.logPersonalizzato("consegnaRispostaApplicativaFallita");
  1517.                
  1518.                 erroreConsegnaRisposta = e;
  1519.                
  1520.                 if(esito!=null){
  1521.                     if(EsitoTransazioneName.OK.equals(esito.getName())){
  1522.                         // non è ok, essendo andato in errore il flush
  1523.                         try{
  1524.                             esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX);
  1525.                         }catch(Exception eBuildError){
  1526.                             esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1527.                         }
  1528.                     }
  1529.                 }
  1530.                 else{
  1531.                     // non dovrebbe mai essere null
  1532.                 }
  1533.                
  1534.             } finally {
  1535.                 if(dataRispostaSpedita==null) {
  1536.                     dataRispostaSpedita = DateManager.getDate();
  1537.                 }
  1538.             }
  1539.            
  1540.             if(dumpRaw!=null && dumpRaw.isActiveDumpRisposta()){
  1541.                 dumpRaw.serializeResponse(((DumpRawConnectorOutMessage)res));
  1542.             }
  1543.            
  1544.         }
  1545.        
  1546.         if(erroreConnessioneClient){
  1547.             // forzo esito errore connessione client
  1548.             try{
  1549.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_CONNESSIONE_CLIENT_NON_DISPONIBILE);
  1550.             }catch(Exception eBuildError){
  1551.                 esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1552.             }
  1553.         }
  1554.         else if(EsitoTransazioneName.OK.equals(esito.getName()) && context!=null && context.getPddContext()!=null && context.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.EMESSI_DIAGNOSTICI_ERRORE)) {
  1555.             // caso di errore generato durante il tracciamento dopo aver calcolato l'esito, in cui non viene sollevata una eccezione
  1556.             esito = ServicesUtils.updateEsitoConAnomalie(esito, logCore, protocolFactory);
  1557.         }
  1558.        
  1559.        
  1560.        
  1561.        
  1562.        
  1563.        
  1564.        
  1565.         // *** Chiudo connessione verso PdD Destinazione per casi stateless ***
  1566.         String location = "...";
  1567.         try{
  1568.             IConnettore c = null;
  1569.             if(context!=null && context.getPddContext()!=null && context.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) {
  1570.                 idTransazione = (String)context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  1571.             }
  1572.             if(idTransazione!=null) {
  1573.             //if(context.getIdMessage()!=null){
  1574.                 c = RepositoryConnettori.removeConnettorePD(
  1575.                         //context.getIdMessage()
  1576.                         idTransazione
  1577.                         );
  1578.             }
  1579.             if(c!=null){
  1580.                 location = c.getLocation();
  1581.                 c.disconnect();
  1582.             }
  1583.         }catch(Exception e){
  1584.             msgDiag.logDisconnectError(e, location);
  1585.         }
  1586.        
  1587.        

  1588.        
  1589.        
  1590.        
  1591.        
  1592.        
  1593.        
  1594.        
  1595.         /* ------------  PostOutResponseHandler ------------- */
  1596.        
  1597.         if(postOutResponseContext!=null){
  1598.             try {
  1599.                 updateContext(context, protocolFactory, postOutResponseContext,
  1600.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1601.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1602.                         esito, statoServletResponse,
  1603.                         idModulo, req,  requestMessage, inputBody,
  1604.                         responseMessage, erroreConsegnaRisposta, lengthOutResponse);
  1605.                 postOutResponseContext.setTransazioneDaAggiornare(transazioneDaAggiornare);
  1606.             }catch(Exception e){
  1607.                 msgDiag.logErroreGenerico(e,"postOutResponse, preparazione contesto");
  1608.             }
  1609.            
  1610.             GestoreHandlers.postOutResponse(postOutResponseContext, msgDiag, logCore);
  1611.         }
  1612.        
  1613.        
  1614.        
  1615.        
  1616.        
  1617.        
  1618.        
  1619.        
  1620.        
  1621.        
  1622.         // *** Rilascio risorse NotifierInputStream ***
  1623.        
  1624.         // request
  1625.         try{
  1626.             if(requestMessage!=null && requestMessage.getNotifierInputStream()!=null){
  1627.                 requestMessage.getNotifierInputStream().close();
  1628.             }
  1629.         }catch(Exception e){
  1630.             msgDiag.logErroreGenerico(e,"Rilascio risorse NotifierInputStream richiesta");
  1631.         }
  1632.        
  1633.         // response
  1634.         try{
  1635.             if(responseMessage!=null && responseMessage.getNotifierInputStream()!=null){
  1636.                 responseMessage.getNotifierInputStream().close();
  1637.             }
  1638.         }catch(Exception e){
  1639.             msgDiag.logErroreGenerico(e,"Rilascio risorse NotifierInputStream risposta");
  1640.         }
  1641.        
  1642.        
  1643.        
  1644.        
  1645.        
  1646.        
  1647.        
  1648.        
  1649.        
  1650.         // *** GB ***
  1651.         requestMessage = null;
  1652.         responseMessage = null;
  1653.         // *** GB ***
  1654.        
  1655.         return;

  1656.     }


  1657.     private void updateContext(RicezioneContenutiApplicativiContext context, IProtocolFactory<?> protocolFactory, PostOutResponseContext postOutResponseContext,
  1658.             Date dataAccettazioneRichiesta, Date dataIngressoRichiesta,
  1659.             Date dataPrimaSpedizioneRisposta, Date dataRispostaSpedita,
  1660.             EsitoTransazione esito, int statoServletResponse,
  1661.             String idModulo, ConnectorInMessage req, OpenSPCoop2Message requestMessage, byte[] inputBody,
  1662.             OpenSPCoop2Message responseMessage, Throwable erroreConsegnaRisposta, long lengthOutResponse) throws ConnectorException {
  1663.         if(postOutResponseContext!=null){
  1664.             postOutResponseContext.getPddContext().addObject(CostantiPdD.DATA_ACCETTAZIONE_RICHIESTA, dataAccettazioneRichiesta);
  1665.             if(dataIngressoRichiesta!=null){
  1666.                 postOutResponseContext.getPddContext().addObject(CostantiPdD.DATA_INGRESSO_RICHIESTA, dataIngressoRichiesta);
  1667.             }
  1668.             postOutResponseContext.setDataElaborazioneMessaggio(DateManager.getDate());
  1669.             postOutResponseContext.setDataPrimaSpedizioneRisposta(dataPrimaSpedizioneRisposta);
  1670.             postOutResponseContext.setDataRispostaSpedita(dataRispostaSpedita);
  1671.             if(erroreConsegnaRisposta==null){
  1672.                 postOutResponseContext.setEsito(esito);
  1673.             }else{
  1674.                 try{
  1675.                     esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX);
  1676.                 }catch(Exception eBuildError){
  1677.                     esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1678.                 }
  1679.                 postOutResponseContext.setEsito(esito);
  1680.             }
  1681.             postOutResponseContext.setReturnCode(statoServletResponse);
  1682.             postOutResponseContext.setResponseHeaders(context.getResponseHeaders());
  1683.             postOutResponseContext.setProtocollo(context.getProtocol());
  1684.             postOutResponseContext.setIntegrazione(context.getIntegrazione());
  1685.             if(context.getTipoPorta()!=null)
  1686.                 postOutResponseContext.setTipoPorta(context.getTipoPorta());    
  1687.             postOutResponseContext.setIdModulo(idModulo);
  1688.            
  1689.             if(inputBody!=null){
  1690.                 postOutResponseContext.setInputRequestMessageSize(Long.valueOf(inputBody.length));
  1691.             }
  1692.             if(requestMessage!=null){
  1693.                 /**postOutResponseContext.setInputRequestMessageSize(requestMessage.getIncomingMessageContentLength());*/
  1694.                 postOutResponseContext.setOutputRequestMessageSize(requestMessage.getOutgoingMessageContentLength());
  1695.             }else{
  1696.                 postOutResponseContext.setInputRequestMessageSize(req.getContentLength()+0l);
  1697.             }
  1698.            
  1699.             if(erroreConsegnaRisposta==null && responseMessage!=null  && !responseMessage.isForcedEmptyResponse() && responseMessage.getForcedResponse()==null){
  1700.                 postOutResponseContext.setInputResponseMessageSize(responseMessage.getIncomingMessageContentLength());
  1701.                 postOutResponseContext.setOutputResponseMessageSize(lengthOutResponse); // sbustata!
  1702.                 postOutResponseContext.setMessaggio(responseMessage);
  1703.             }
  1704.             else if(responseMessage!=null && responseMessage.getForcedResponse()!=null &&
  1705.                     responseMessage.getForcedResponse().getContent()!=null) {
  1706.                 postOutResponseContext.setInputResponseMessageSize(responseMessage.getIncomingMessageContentLength());
  1707.                 postOutResponseContext.setOutputResponseMessageSize((long) responseMessage.getForcedResponse().getContent().length);
  1708.             }  
  1709.         }      
  1710.     }

  1711.     private Transazione registraTracciaOutResponse(RicezioneContenutiApplicativiContext context,
  1712.             IProtocolFactory<?> protocolFactory,
  1713.             PostOutResponseContext postOutResponseContext,
  1714.             Date dataAccettazioneRichiesta, Date dataIngressoRichiesta,
  1715.             Date dataPrimaSpedizioneRisposta, Date dataRispostaSpedita,
  1716.             EsitoTransazione esito, int statoServletResponse,
  1717.             String idModulo, ConnectorInMessage req, OpenSPCoop2Message requestMessage, byte[] inputBody,
  1718.             OpenSPCoop2Message responseMessage, Throwable erroreConsegnaRisposta, long lengthOutResponse,
  1719.             MsgDiagnostico msgDiag) throws HandlerException {

  1720.         try {
  1721.        
  1722.             if(postOutResponseContext!=null) {
  1723.                 updateContext(context, protocolFactory, postOutResponseContext,
  1724.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1725.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1726.                         esito, statoServletResponse,
  1727.                         idModulo, req,  requestMessage, inputBody,
  1728.                         responseMessage, erroreConsegnaRisposta, lengthOutResponse);
  1729.                
  1730.                 TracciamentoManager tracciamentoManager = new TracciamentoManager(FaseTracciamento.OUT_RESPONSE);
  1731.                 if(!tracciamentoManager.isTransazioniEnabled()) {
  1732.                     return null;
  1733.                 }
  1734.                
  1735.                 InformazioniTransazione info = new InformazioniTransazione(postOutResponseContext);
  1736.                
  1737.                 tracciamentoManager.invoke(info, postOutResponseContext.getEsito(), context.getResponseHeaders(), msgDiag);
  1738.                
  1739.                 return info.getTransazioneDaAggiornare();
  1740.             }

  1741.         }catch(Exception e) {
  1742.             ServicesUtils.processTrackingException(e, postOutResponseContext.getLogCore(), FaseTracciamento.OUT_RESPONSE, context.getPddContext());
  1743.         }
  1744.        
  1745.         return null;
  1746.     }
  1747.    
  1748.     private void registraTracciaInRequest(RicezioneContenutiApplicativiContext context,
  1749.             IProtocolFactory<?> protocolFactory, Logger log,
  1750.             MsgDiagnostico msgDiag) throws HandlerException{
  1751.        
  1752.         try {
  1753.        
  1754.             TracciamentoManager tracciamentoManager = new TracciamentoManager(FaseTracciamento.IN_REQUEST);
  1755.             if(!tracciamentoManager.isTransazioniEnabled()) {
  1756.                 return;
  1757.             }
  1758.                
  1759.             InformazioniTransazione info = new InformazioniTransazione();
  1760.             info.setContext(context.getPddContext());
  1761.             info.setTipoPorta(context.getTipoPorta());
  1762.             info.setProtocolFactory(protocolFactory);
  1763.             info.setProtocollo(context.getProtocol());
  1764.             info.setIntegrazione(context.getIntegrazione());
  1765.             info.setIdModulo(context.getIdModulo());
  1766.            
  1767.             TransportRequestContext transportRequestContext = null;
  1768.             if(context.getMessageRequest()!=null) {
  1769.                 transportRequestContext = context.getMessageRequest().getTransportRequestContext();
  1770.             }
  1771.             String esitoContext = EsitoBuilder.getTipoContext(transportRequestContext, EsitiProperties.getInstance(log, protocolFactory), log);
  1772.            
  1773.             tracciamentoManager.invoke(info, esitoContext, msgDiag);
  1774.            
  1775.         }catch(Exception e) {
  1776.             ServicesUtils.processTrackingException(e, log, FaseTracciamento.IN_REQUEST, context.getPddContext());
  1777.         }
  1778.        
  1779.     }
  1780. }