RicezioneContenutiApplicativiService.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.Date;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import java.util.Map;

  26. import javax.xml.soap.SOAPBody;

  27. import org.apache.commons.io.output.NullOutputStream;
  28. import org.apache.commons.lang.StringUtils;
  29. import org.openspcoop2.core.commons.CoreException;
  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.OpenSPCoop2SoapMessage;
  41. import org.openspcoop2.message.constants.MessageRole;
  42. import org.openspcoop2.message.constants.MessageType;
  43. import org.openspcoop2.message.constants.ServiceBinding;
  44. import org.openspcoop2.message.exception.ParseException;
  45. import org.openspcoop2.message.exception.ParseExceptionUtils;
  46. import org.openspcoop2.message.soap.SoapUtils;
  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.RicezioneContenutiApplicativiConnector;
  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.LimitedInputStream;
  106. import org.openspcoop2.utils.LoggerWrapperFactory;
  107. import org.openspcoop2.utils.TimeoutIOException;
  108. import org.openspcoop2.utils.TimeoutInputStream;
  109. import org.openspcoop2.utils.Utilities;
  110. import org.openspcoop2.utils.date.DateManager;
  111. import org.openspcoop2.utils.io.DumpByteArrayOutputStream;
  112. import org.openspcoop2.utils.io.notifier.NotifierInputStreamParams;
  113. import org.openspcoop2.utils.transport.TransportRequestContext;
  114. import org.openspcoop2.utils.transport.http.HttpConstants;
  115. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  116. import org.slf4j.Logger;

  117. /**
  118.  * RicezioneContenutiApplicativiService
  119.  *
  120.  * @author Poli Andrea (apoli@link.it)
  121.  * @author Lorenzo Nardi (nardi@link.it)
  122.  * @author $Author$
  123.  * @version $Rev$, $Date$
  124.  */



  125. public class RicezioneContenutiApplicativiService {

  126.    
  127.     private RicezioneContenutiApplicativiInternalErrorGenerator generatoreErrore;
  128.    
  129.     public RicezioneContenutiApplicativiService(RicezioneContenutiApplicativiInternalErrorGenerator generatoreErrore){
  130.         this.generatoreErrore = generatoreErrore;
  131.     }
  132.    

  133.     public void process(ConnectorInMessage req, ConnectorOutMessage res, Date dataAccettazioneRichiesta) throws ConnectorException {

  134.         // Timestamp
  135.         Date dataIngressoRichiesta = null;
  136.        
  137.         // IDModulo
  138.         String idModulo = req.getIdModulo();
  139.         IDService idModuloAsService = req.getIdModuloAsIDService();
  140.         RequestInfo requestInfo = req.getRequestInfo();
  141.                
  142.         // Log
  143.         Logger logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  144.         if(logCore==null)
  145.             logCore = LoggerWrapperFactory.getLogger(idModulo);

  146.         OpenSPCoop2Properties openSPCoopProperties = OpenSPCoop2Properties.getInstance();
  147.        

  148.         /* ------------  PreInHandler (PreInAcceptRequestContext) ------------- */
  149.        
  150.         PreInAcceptRequestContext preInAcceptRequestContext = null;
  151.         if (openSPCoopProperties != null && OpenSPCoop2Startup.initialize) {
  152.        
  153.             // build context
  154.             preInAcceptRequestContext = new PreInAcceptRequestContext();
  155.             preInAcceptRequestContext.setTipoPorta(TipoPdD.DELEGATA);
  156.             preInAcceptRequestContext.setIdModulo(idModulo);
  157.             preInAcceptRequestContext.setRequestInfo(requestInfo);  
  158.             preInAcceptRequestContext.setLogCore(logCore);
  159.            
  160.             // valori che verranno aggiornati dopo
  161.             try {
  162.                 if(openSPCoopProperties.isConnettoriUseLimitedInputStream()) {
  163.                     SogliaDimensioneMessaggio soglia = new SogliaDimensioneMessaggio();
  164.                     soglia.setSogliaKb(openSPCoopProperties.getLimitedInputStreamThresholdKb());
  165.                     soglia.setUseContentLengthHeader(openSPCoopProperties.isLimitedInputStreamUseContentLength());
  166.                     soglia.setUseContentLengthHeaderAcceptZeroValue(openSPCoopProperties.isLimitedInputStreamUseContentLengthAcceptZeroValue());
  167.                     soglia.setPolicyGlobale(true);
  168.                     soglia.setNomePolicy("GovWayCore");
  169.                     soglia.setIdPolicyConGruppo("GovWayCore");
  170.                     req.setRequestLimitedStream(soglia);
  171.                 }
  172.                 if(openSPCoopProperties.isConnettoriUseTimeoutInputStream()) {
  173.                     SogliaReadTimeout soglia = new SogliaReadTimeout();
  174.                     soglia.setSogliaMs(openSPCoopProperties.getReadConnectionTimeout_ricezioneContenutiApplicativi());
  175.                     soglia.setConfigurazioneGlobale(true);
  176.                     soglia.setIdConfigurazione("GovWayCore");
  177.                     req.setRequestReadTimeout(soglia);
  178.                 }
  179.                 req.setThresholdContext(null,
  180.                     openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  181.             }catch(Throwable t) {
  182.                 logCore.error(t.getMessage(),t);
  183.             }
  184.             preInAcceptRequestContext.setReq(req);
  185.            
  186.             // invocazione handler
  187.             GestoreHandlers.preInRequest(preInAcceptRequestContext, logCore, logCore);
  188.            
  189.         }
  190.        
  191.        
  192.        
  193.         // GeneratoreErrore
  194.         try{
  195.             if(this.generatoreErrore==null){
  196.                 this.generatoreErrore =
  197.                         new RicezioneContenutiApplicativiInternalErrorGenerator(logCore, RicezioneContenutiApplicativiConnector.ID_MODULO, requestInfo);
  198.             }
  199.         }catch(Exception e){
  200.             String msg = "Inizializzazione Generatore Errore fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  201.             logCore.error(msg,e);
  202.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore, // il metodo doError gestisce il generatoreErrore a null
  203.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  204.                     get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  205.                     IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  206.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  207.             return;
  208.         }
  209.        
  210.         // Proprieta' OpenSPCoop
  211.         if (!OpenSPCoop2Startup.initialize || openSPCoopProperties == null) {
  212.             String msg = "Inizializzazione di GovWay non correttamente effettuata: OpenSPCoopProperties";
  213.             if(!OpenSPCoop2Startup.initialize) {
  214.                 msg = "Inizializzazione di GovWay non correttamente effettuata";
  215.             }
  216.             logCore.error(msg);
  217.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  218.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  219.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  220.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, null, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  221.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  222.             return;
  223.         }
  224.                
  225.         // Configurazione Reader
  226.         ConfigurazionePdDManager configPdDManager = null;
  227.         try{
  228.             configPdDManager = ConfigurazionePdDManager.getInstance();
  229.             if(configPdDManager==null || configPdDManager.isInitializedConfigurazionePdDReader()==false){
  230.                 throw new Exception("ConfigurazionePdDManager not initialized");
  231.             }
  232.         }catch(Throwable e){
  233.             String msg = "Inizializzazione di GovWay non correttamente effettuata: ConfigurazionePdDManager";
  234.             logCore.error(msg);
  235.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  236.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  237.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  238.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  239.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  240.             return;
  241.         }
  242.            
  243.         // PddContext from servlet
  244.         Object oPddContextFromServlet = null;
  245.         try{
  246.             oPddContextFromServlet = req.getAttribute(CostantiPdD.OPENSPCOOP2_PDD_CONTEXT_HEADER_HTTP.getValue());
  247.         }catch(Exception e){
  248.             logCore.error("req.getAttribute("+CostantiPdD.OPENSPCOOP2_PDD_CONTEXT_HEADER_HTTP+") error: "+e.getMessage(),e);
  249.         }
  250.         PdDContext pddContextFromServlet = null;
  251.         if(oPddContextFromServlet!=null){
  252.             pddContextFromServlet = (PdDContext) oPddContextFromServlet;
  253.         }
  254.        
  255.         // check requestInfo
  256.         if(requestInfo==null) {
  257.             String msg = "RequestInfo undefined";
  258.             logCore.error(msg);
  259.             return;
  260.         }
  261.        
  262.         // Identifico Servizio per comprendere correttamente il messageType
  263.         ServiceIdentificationReader serviceIdentificationReader = null;
  264.         try{
  265.             serviceIdentificationReader = ServicesUtils.getServiceIdentificationReader(logCore, requestInfo,
  266.                     configPdDManager.getRegistroServiziManager(), configPdDManager);
  267.         }catch(Exception e){
  268.             String msg = "Inizializzazione RegistryReader fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  269.             logCore.error(msg,e);
  270.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  271.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  272.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  273.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  274.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  275.             return;
  276.         }
  277.        
  278.         // Provo a creare un context (per l'id di transazione nei diagnostici)
  279.         RicezioneContenutiApplicativiContext context = null;
  280.         IProtocolFactory<?> protocolFactory = null;
  281.         String idTransazione = null;
  282.         try {
  283.             context = new RicezioneContenutiApplicativiContext(idModuloAsService,dataAccettazioneRichiesta,requestInfo);
  284.             protocolFactory = req.getProtocolFactory();
  285.             idTransazione = (String)context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  286.         }catch(Throwable e) {
  287.             context = null;
  288.             protocolFactory = null;
  289.             // non loggo l'errore tanto poi provo a ricreare il context subito dopo e li verra' registrato l'errore
  290.         }
  291.        
  292.         try{
  293.             GestoreRichieste.readRequestConfig(requestInfo);
  294.         }catch(Exception e){
  295.             String msg = "GestoreRichieste readRequestConfig fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  296.             logCore.error(msg,e);
  297.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  298.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  299.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_500_ERRORE_INTERNO),
  300.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  301.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  302.             return;
  303.         }
  304.        
  305.         if(idTransazione!=null) {
  306.             try {
  307.                 if(openSPCoopProperties.isTransazioniEnabled()) {
  308.                     TransactionContext.createTransaction(idTransazione, "RicezioneContenutiApplicativi.1");
  309.                 }
  310.                 requestInfo.setIdTransazione(idTransazione);
  311.                
  312.                 req.setThresholdContext((context!=null ? context.getPddContext(): null),
  313.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  314.                
  315.             }catch(Throwable e) {
  316.                 context = null;
  317.                 protocolFactory = null;
  318.                 // non loggo l'errore tanto poi provo a ricreare il context subito dopo e li verra' registrato l'errore
  319.             }
  320.         }
  321.                
  322.         // Logger dei messaggi diagnostici
  323.         String nomePorta = requestInfo.getProtocolContext().getInterfaceName();
  324.         MsgDiagnostico msgDiag = MsgDiagnostico.newInstance(TipoPdD.DELEGATA,idModulo,nomePorta,requestInfo);
  325.         msgDiag.setPrefixMsgPersonalizzati(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_CONTENUTI_APPLICATIVI);
  326.         if(context!=null && protocolFactory!=null) {
  327.             msgDiag.setPddContext(context.getPddContext(), protocolFactory);
  328.         }
  329.        
  330.         try{
  331.             msgDiag.logPersonalizzato("ricezioneRichiesta.firstLog");
  332.         }catch(Exception e){
  333.             logCore.error("Errore generazione diagnostico di ingresso",e);
  334.         }
  335.        
  336.         try{
  337.             req.setDiagnosticProducer(context!=null ? context.getPddContext(): null, msgDiag);
  338.         }catch(Throwable e){
  339.             logCore.error("Errore registrazione diagnostico sulla richiesta",e);
  340.         }
  341.        
  342.         // emitDiagnostic preAccept handler
  343.         GestoreHandlers.emitDiagnostic(msgDiag, preInAcceptRequestContext, context!=null ? context.getPddContext() : null,
  344.                 logCore, logCore);
  345.        
  346.         // Aggiorno RequestInfo
  347.         try{
  348.             msgDiag.mediumDebug("Accesso configurazione della richiesta in corso...");
  349.         }catch(Exception e){
  350.             logCore.error("Errore generazione diagnostico",e);
  351.         }
  352.         ConnectorDispatcherInfo cInfo = RicezioneContenutiApplicativiServiceUtils.updatePortaDelegataRequestInfo(requestInfo, logCore, req, res,
  353.                 this.generatoreErrore, serviceIdentificationReader, msgDiag,
  354.                 context!=null ? context.getPddContext(): null);
  355.         if(cInfo!=null){
  356.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(context, logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  357.             return; // l'errore in response viene impostato direttamente dentro il metodo
  358.         }
  359.         req.updateRequestInfo(requestInfo);
  360.                    
  361.         // Timeout, DimensioneMessaggi e DumpRaw
  362.         DumpRaw dumpRaw = null;
  363.         try{
  364.             try{
  365.                 msgDiag.mediumDebug("Lettura configurazione dump binario ...");
  366.             }catch(Exception e){
  367.                 logCore.error("Errore generazione diagnostico",e);
  368.             }
  369.             boolean dumpBinario = configPdDManager.dumpBinarioPD();
  370.             PortaDelegata pd = null;
  371.             if(requestInfo!=null && requestInfo.getProtocolContext()!=null && requestInfo.getProtocolContext().getInterfaceName()!=null) {
  372.                 IDPortaDelegata idPD = new IDPortaDelegata();
  373.                 idPD.setNome(requestInfo.getProtocolContext().getInterfaceName());
  374.                 pd = configPdDManager.getPortaDelegataSafeMethod(idPD,requestInfo);
  375.             }

  376.             // Limited
  377.             try{
  378.                 msgDiag.mediumDebug("Lettura configurazione dimensione massima della richiesta ...");
  379.             }catch(Exception e){
  380.                 logCore.error("Errore generazione diagnostico",e);
  381.             }
  382.             String azione = (requestInfo!=null && requestInfo.getIdServizio()!=null) ? requestInfo.getIdServizio().getAzione() : null;
  383.             SoglieDimensioneMessaggi limitedInputStream = configPdDManager.getSoglieLimitedInputStream(pd, azione, idModulo,
  384.                     (context!=null && context.getPddContext()!=null) ? context.getPddContext() : null,
  385.                     requestInfo,
  386.                     protocolFactory, logCore);
  387.             if(limitedInputStream!=null) {
  388.                 req.setRequestLimitedStream(limitedInputStream.getRichiesta());
  389.                 if(context!=null && context.getPddContext()!=null) {
  390.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.LIMITED_STREAM, limitedInputStream.getRisposta());
  391.                 }
  392.             }
  393.             else {
  394.                 if(!openSPCoopProperties.isLimitedInputStreamThresholdDefined()) {
  395.                     req.disableLimitedStream();
  396.                 }
  397.             }
  398.            
  399.             // Timeout
  400.             try{
  401.                 msgDiag.mediumDebug("Lettura configurazione timeout per la lettura della richiesta ...");
  402.             }catch(Exception e){
  403.                 logCore.error("Errore generazione diagnostico",e);
  404.             }
  405.             boolean useTimeoutInputStream = configPdDManager.isConnettoriUseTimeoutInputStream(pd);
  406.             if(useTimeoutInputStream) {
  407.                 SogliaReadTimeout timeout = configPdDManager.getRequestReadTimeout(pd,
  408.                         requestInfo,
  409.                         protocolFactory,
  410.                         context!=null ? context.getPddContext() : null,
  411.                         null);
  412.                 if(timeout!=null && timeout.getSogliaMs()>0) {
  413.                     req.setRequestReadTimeout(timeout);
  414.                 }
  415.                 else {
  416.                     req.disableReadTimeout();
  417.                 }
  418.             }
  419.             else {
  420.                 req.disableReadTimeout();
  421.             }
  422.            
  423.             // DumpRaw
  424.             try{
  425.                 msgDiag.mediumDebug("Lettura configurazione dump ...");
  426.             }catch(Exception e){
  427.                 logCore.error("Errore generazione diagnostico",e);
  428.             }
  429.             DumpConfigurazione dumpConfigurazione = configPdDManager.getDumpConfigurazione(pd);
  430.             ConfigurazioneTracciamento configurazioneTracciamento = new ConfigurazioneTracciamento(logCore, configPdDManager, pd);
  431.             boolean fileTraceHeaders = configurazioneTracciamento.isTransazioniFileTraceDumpBinarioHeaderEnabled();
  432.             boolean fileTracePayload = configurazioneTracciamento.isTransazioniFileTraceDumpBinarioPayloadEnabled();
  433.             dumpRaw = new DumpRaw(logCore,requestInfo.getIdentitaPdD(), idModulo, TipoPdD.DELEGATA,
  434.                     dumpBinario,
  435.                     dumpConfigurazione,
  436.                     fileTraceHeaders, fileTracePayload);
  437.             if(dumpRaw.isActiveDumpRichiesta()) {
  438.                 req = new DumpRawConnectorInMessage(logCore, req,
  439.                         (context!=null ? context.getPddContext(): null),
  440.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  441.             }
  442.             if(dumpRaw.isActiveDumpRisposta()) {
  443.                 res = new DumpRawConnectorOutMessage(logCore, res,
  444.                         (context!=null ? context.getPddContext(): null),
  445.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository(),
  446.                         dumpRaw);
  447.             }
  448.         }catch(Throwable e){
  449.             String msg = "Inizializzazione di GovWay non correttamente effettuata: DumpRaw";
  450.             logCore.error(msg,  e);
  451.             cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  452.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  453.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  454.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  455.             RicezioneContenutiApplicativiServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  456.             return;
  457.         }
  458.        
  459.         // API Soap supporta solo POST e ?wsdl
  460.         if(ServiceBinding.SOAP.equals(requestInfo.getIntegrationServiceBinding())){
  461.             HttpRequestMethod method = null;
  462.             if(req!=null && req.getURLProtocolContext()!=null && req.getURLProtocolContext().getRequestType()!=null) {
  463.                 try {
  464.                     method = HttpRequestMethod.valueOf(req.getURLProtocolContext().getRequestType());
  465.                 }catch(Exception e) {
  466.                     // ignore
  467.                 }
  468.             }
  469.             if(method!=null && !HttpRequestMethod.POST.equals(method)){
  470.                 if(ServicesUtils.isRequestWsdl(req, logCore)) {
  471.                     try {
  472.                         ServicesUtils.writeWsdl(res, requestInfo, RicezioneContenutiApplicativiConnector.ID_SERVICE, serviceIdentificationReader, logCore);
  473.                     }catch(Exception e) {
  474.                         String msg = "Lettura wsdl fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  475.                         logCore.error(msg,e);
  476.                         cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  477.                                 ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  478.                                     get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_500_ERRORE_INTERNO),
  479.                                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  480.                         // nel caso di wsdl request non emetto la transazione
  481.                         //RicezioneContenutiApplicativiServiceUtils.emitTransaction(context,logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  482.                     }finally {
  483.                         // FIX devo però rilasciare dalla memoria la transazione:
  484.                         if(openSPCoopProperties.isTransazioniEnabled()) {
  485.                             idTransazione = (String)context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  486.                             TransactionContext.removeTransaction(idTransazione);
  487.                         }
  488.                     }
  489.                     return;
  490.                 }
  491.                 else {
  492.                     String msg = "Metodo http '"+method+"' non supportato dall'API SOAP invocata";
  493.                     logCore.error(msg);
  494.                     ConnectorDispatcherErrorInfo cInfoError =  ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  495.                             ErroriIntegrazione.ERRORE_439_FUNZIONALITA_NOT_SUPPORTED_BY_PROTOCOL.getErrore439_FunzionalitaNotSupportedByProtocol(msg, protocolFactory),
  496.                             IntegrationFunctionError.NOT_SUPPORTED_BY_PROTOCOL, null, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  497.                     RicezioneContenutiApplicativiServiceUtils.emitTransaction(context,logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfoError);
  498.                     return;
  499.                 }
  500.             }
  501.         }
  502.        
  503.        


  504.        
  505.         /* ------------  Lettura parametri della richiesta ------------- */

  506.         //  Risposta Soap
  507.         OpenSPCoop2Message responseMessage = null;
  508.                
  509.         // PostOutResponseContext
  510.         PostOutResponseContext postOutResponseContext = null;
  511.        
  512.         PdDContext pddContext = null;
  513.         OpenSPCoop2Message requestMessage = null;
  514.         String protocol = null;
  515.         MessageType messageTypeReq = null;
  516.         ServiceBinding integrationServiceBinding = null;
  517.         try{
  518.            
  519.             /* --------------- Creo il context che genera l'id univoco ----------------------- */
  520.            
  521.             try{
  522.                 msgDiag.mediumDebug("Creazione contesto ...");
  523.             }catch(Exception e){
  524.                 logCore.error("Errore generazione diagnostico",e);
  525.             }
  526.            
  527.             if(protocolFactory==null) {
  528.                 protocolFactory = req.getProtocolFactory();
  529.             }
  530.             protocol = protocolFactory.getProtocol();
  531.                    
  532.             integrationServiceBinding = requestInfo.getIntegrationServiceBinding();
  533.            
  534.             if(context==null) {
  535.                 context = new RicezioneContenutiApplicativiContext(idModuloAsService,dataAccettazioneRichiesta,requestInfo);
  536.             }
  537.             if(preInAcceptRequestContext!=null && preInAcceptRequestContext.getPreContext()!=null && !preInAcceptRequestContext.getPreContext().isEmpty()) {
  538.                 context.getPddContext().addAll(preInAcceptRequestContext.getPreContext(), false);
  539.             }
  540.             context.setTipoPorta(TipoPdD.DELEGATA);
  541.             context.setIdModulo(idModulo);
  542.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  543.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO, req.getRequestInfo());
  544.             RicezionePropertiesConfig rConfig = RicezioneContenutiApplicativiServiceUtils.readPropertiesConfig(req.getRequestInfo(), logCore,null);
  545.             if(rConfig!=null) {
  546.                 if (rConfig.getApiImplementation() != null && !rConfig.getApiImplementation().isEmpty()) {
  547.                    context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_CONFIGURAZIONE, rConfig.getApiImplementation());
  548.                 }
  549.                 if (rConfig.getSoggettoFruitore() != null && !rConfig.getSoggettoFruitore().isEmpty()) {
  550.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_FRUITORE, rConfig.getSoggettoFruitore());
  551.                 }
  552.                 if (rConfig.getSoggettoErogatore() != null && !rConfig.getSoggettoErogatore().isEmpty()) {
  553.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_EROGATORE, rConfig.getSoggettoErogatore());
  554.                 }
  555.             }
  556.             context.setProprietaErroreAppl(this.generatoreErrore.getProprietaErroreAppl());
  557.             msgDiag.setPddContext(context.getPddContext(), protocolFactory);
  558.             pddContext = context.getPddContext();
  559.            
  560.             try{
  561.                 if(openSPCoopProperties.isTransazioniEnabled()) {
  562.                     // NOTA: se gia' esiste con l'id di transazione, non viene ricreata
  563.                     TransactionContext.createTransaction((String)pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE), "RicezioneContenutiApplicativi.2");
  564.                 }
  565.             }catch(Exception e){
  566.                 logCore.error("Errore durante la creazione della transazione",e);
  567.             }
  568.            
  569.             try{
  570.                 msgDiag.logPersonalizzato("ricezioneRichiesta.firstAccessRequestStream");
  571.             }catch(Exception e){
  572.                 logCore.error("Errore generazione diagnostico di ingresso (stream access)",e);
  573.             }
  574.            
  575.             if(dumpRaw!=null && dumpRaw.isActiveDump()){
  576.                 dumpRaw.setPddContext(msgDiag.getPorta(), context.getPddContext());
  577.                 dumpRaw.serializeContext(context, protocol);
  578.             }
  579.            
  580.             DirectVMConnectorInMessage vm = null;
  581.             if(req instanceof DirectVMConnectorInMessage){
  582.                 vm = (DirectVMConnectorInMessage) req;
  583.             }
  584.             else if(req instanceof DumpRawConnectorInMessage){
  585.                 if( ((DumpRawConnectorInMessage)req).getWrappedConnectorInMessage() instanceof DirectVMConnectorInMessage ){
  586.                     vm = (DirectVMConnectorInMessage) ((DumpRawConnectorInMessage)req).getWrappedConnectorInMessage();
  587.                 }
  588.             }
  589.             if(vm!=null && vm.getDirectVMProtocolInfo()!=null){
  590.                 vm.getDirectVMProtocolInfo().setInfo(pddContext);
  591.             }
  592.            
  593.            
  594.            
  595.            
  596.             /* ------------  PostOutResponseContext ------------- */
  597.            
  598.             postOutResponseContext = new PostOutResponseContext(logCore,protocolFactory);
  599.             postOutResponseContext.setTipoPorta(TipoPdD.DELEGATA);
  600.             postOutResponseContext.setPddContext(pddContext);
  601.             postOutResponseContext.setIdModulo(idModulo);
  602.            
  603.            
  604.            
  605.            
  606.             /* ------------  PreInHandler ------------- */
  607.            
  608.             // build context
  609.             PreInRequestContext preInRequestContext = new PreInRequestContext(pddContext);
  610.             if(pddContextFromServlet!=null){
  611.                 preInRequestContext.getPddContext().addAll(pddContextFromServlet, true);
  612.             }
  613.             preInRequestContext.setTipoPorta(TipoPdD.DELEGATA);
  614.             preInRequestContext.setIdModulo(idModulo);
  615.             preInRequestContext.setProtocolFactory(protocolFactory);
  616.             preInRequestContext.setRequestInfo(requestInfo);
  617.             Map<String, Object> transportContext = new HashMap<>();
  618.             transportContext.put(PreInRequestContext.SERVLET_REQUEST, req);
  619.             transportContext.put(PreInRequestContext.SERVLET_RESPONSE, res);
  620.             preInRequestContext.setTransportContext(transportContext);  
  621.             preInRequestContext.setLogCore(logCore);
  622.            
  623.             // invocazione handler
  624.             GestoreHandlers.preInRequest(preInRequestContext, msgDiag, logCore);
  625.            
  626.             // aggiungo eventuali info inserite nel preInHandler
  627.             pddContext.addAll(preInRequestContext.getPddContext(), false);
  628.            
  629.             // Lettura risposta parametri NotifierInputStream
  630.             NotifierInputStreamParams notifierInputStreamParams = preInRequestContext.getNotifierInputStreamParams();
  631.             context.setNotifierInputStreamParams(notifierInputStreamParams);
  632.            
  633.             // Controllo Content Length se attiva una policy di rate limiting
  634.             req.checkContentLengthLimit();
  635.            
  636.             // Lettura richiesta con il dump
  637.             if(dumpRaw!=null && dumpRaw.isActiveDumpRichiesta()){
  638.                 dumpRaw.serializeRequest(((DumpRawConnectorInMessage)req), true, notifierInputStreamParams);
  639.                 dataIngressoRichiesta = req.getDataIngressoRichiesta();
  640.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  641.             }
  642.            
  643.            
  644.                
  645.            
  646.            
  647.             /* ------------ Controllo ContentType -------------------- */
  648.            
  649.             msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.tipologiaMessaggio");
  650.            
  651.             messageTypeReq = requestInfo.getIntegrationRequestMessageType();
  652.             if(ServiceBinding.SOAP.equals(integrationServiceBinding) && messageTypeReq!=null){
  653.                 msgDiag.addKeyword(CostantiPdD.KEY_SOAP_VERSION, messageTypeReq.getMessageVersionAsString());
  654.                 msgDiag.addKeyword(CostantiPdD.KEY_SOAP_ENVELOPE_NAMESPACE_ATTESO, SoapUtils.getSoapEnvelopeNS(messageTypeReq));
  655.             }
  656.            
  657.             String contentTypeReq = req.getContentType();
  658.             boolean contentTypeSupportato = messageTypeReq!=null;
  659.             msgDiag.addKeyword(CostantiPdD.KEY_CONTENT_TYPES_ATTESI,
  660.                     requestInfo.getBindingConfig().getContentTypesSupportedAsString(integrationServiceBinding,
  661.                             MessageRole.REQUEST,requestInfo.getProtocolContext()));
  662.             List<String> supportedContentTypes = requestInfo.getBindingConfig().getContentTypesSupported(integrationServiceBinding,
  663.                     MessageRole.REQUEST,requestInfo.getProtocolContext());
  664.             msgDiag.addKeyword(CostantiPdD.KEY_HTTP_HEADER, contentTypeReq);
  665.            
  666.             if(ServiceBinding.SOAP.equals(integrationServiceBinding)){
  667.                 if(openSPCoopProperties.isControlloContentTypeAbilitatoRicezioneContenutiApplicativi() == false){
  668.                     if(!contentTypeSupportato){
  669.                         if(HttpConstants.CONTENT_TYPE_NON_PRESENTE.equals(contentTypeReq)){
  670.                             msgDiag.logPersonalizzato("contentType.notDefined");
  671.                         }else{
  672.                             msgDiag.logPersonalizzato("contentType.unsupported");
  673.                         }
  674.                         messageTypeReq = MessageType.SOAP_11;
  675.                         contentTypeReq = SoapUtils.getSoapContentTypeForMessageWithoutAttachments(messageTypeReq); // Forzo text/xml;
  676.                         logCore.warn("Content-Type non supportato, viene utilizzato forzatamente il tipo: "+contentTypeReq);
  677.                         contentTypeSupportato = true;
  678.                     }
  679.                 }
  680.             }
  681.             if(!contentTypeSupportato){
  682.                
  683.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  684.                
  685.                 // Leggo content Type dall'header HTTP per capire se l'header proprio non esiste o se e' il valore errato.
  686.                 if(HttpConstants.CONTENT_TYPE_NON_PRESENTE.equals(contentTypeReq)){
  687.                     //ContentType del messaggio non presente
  688.                     msgDiag.logPersonalizzato("contentType.notDefined");
  689.                     responseMessage = this.generatoreErrore.build(pddContext, IntegrationFunctionError.CONTENT_TYPE_NOT_PROVIDED,
  690.                             ErroriIntegrazione.ERRORE_433_CONTENT_TYPE_NON_PRESENTE.
  691.                             getErrore433_ContentTypeNonPresente(supportedContentTypes),null,null);
  692.                 }
  693.                 else{
  694.                     //ContentType del messaggio non supportato
  695.                     msgDiag.logPersonalizzato("contentType.unsupported");
  696.                     responseMessage = this.generatoreErrore.build(pddContext, IntegrationFunctionError.CONTENT_TYPE_NOT_SUPPORTED,
  697.                             ErroriIntegrazione.ERRORE_429_CONTENT_TYPE_NON_SUPPORTATO.
  698.                             getErrore429_ContentTypeNonSupportato(contentTypeReq,supportedContentTypes),null,null);
  699.                 }
  700.             }
  701.             else{
  702.                 /* ------------ Check Charset ------------- */
  703.                 try {
  704.                     boolean checkEnabled = false;
  705.                     List<String> ctDefault = null;
  706.                     if(ServiceBinding.SOAP.equals(integrationServiceBinding)){
  707.                         if(openSPCoopProperties.isControlloCharsetContentTypeAbilitatoRicezioneContenutiApplicativiSoap()) {
  708.                             checkEnabled = true;
  709.                             ctDefault = openSPCoopProperties.getControlloCharsetContentTypeAbilitatoRicezioneContenutiApplicativiSoap();
  710.                         }
  711.                     }
  712.                     else {
  713.                         if(openSPCoopProperties.isControlloCharsetContentTypeAbilitatoRicezioneContenutiApplicativiRest()) {
  714.                             checkEnabled = true;
  715.                             ctDefault = openSPCoopProperties.getControlloCharsetContentTypeAbilitatoRicezioneContenutiApplicativiRest();
  716.                         }
  717.                     }
  718.                     if(checkEnabled) {
  719.                         ServicesUtils.checkCharset(contentTypeReq, ctDefault, msgDiag, true, TipoPdD.DELEGATA);
  720.                     }
  721.                    
  722.                 }catch(Throwable t) {
  723.                     logCore.error("Avvenuto errore durante il controllo del charset della richiesta: "+t.getMessage(),t);
  724.                 }
  725.                
  726.                 /* ------------  SoapAction check 1 (controlla che non sia null e ne ritorna il valore) ------------- */            
  727.                 String soapAction = null;
  728.                 try{
  729.                     if(ServiceBinding.SOAP.equals(integrationServiceBinding)){
  730.                         soapAction = req.getSOAPAction();
  731.                     }
  732.                 }catch(Exception e){
  733.                     if(dataIngressoRichiesta==null) {
  734.                         dataIngressoRichiesta=DateManager.getDate();
  735.                     }
  736.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  737.                     throw e;
  738.                 }
  739.                
  740.                 /* ------------ Costruzione Messaggio -------------------- */
  741.                 msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.inCorso");
  742.                 Utilities.printFreeMemory("RicezioneContenutiApplicativi - Pre costruzione richiesta");
  743.                 OpenSPCoop2MessageParseResult pr = req.getRequest(notifierInputStreamParams);
  744.                 if(pr.getParseException()!=null){
  745.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION, pr.getParseException());
  746.                 }
  747.                 dataIngressoRichiesta = req.getDataIngressoRichiesta();
  748.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  749.                 requestMessage = pr.getMessage_throwParseException();
  750.                 Utilities.printFreeMemory("RicezioneContenutiApplicativi - Post costruzione richiesta");
  751.                 requestMessage.setProtocolName(protocolFactory.getProtocol());
  752.                 requestMessage.setTransactionId(PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext));
  753.                 requestMessage.addContextProperty(org.openspcoop2.core.constants.Costanti.REQUEST_INFO,requestInfo); // serve nelle comunicazione non stateless (es. riscontro salvato) per poterlo rispedire
  754.                 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
  755.                 Object nomePortaInvocataObject = context.getPddContext().getObject(CostantiPdD.NOME_PORTA_INVOCATA);
  756.                 if(nomePortaInvocataObject!=null && nomePortaInvocataObject instanceof String) {
  757.                     requestMessage.addContextProperty(CostantiPdD.NOME_PORTA_INVOCATA, (String) nomePortaInvocataObject );
  758.                 }
  759.                                
  760.                 /* ------------ Controllo Soap namespace -------------------- */
  761.                 String soapEnvelopeNamespaceVersionMismatch = null;
  762.                 try{
  763.                     if(ServiceBinding.SOAP.equals(integrationServiceBinding)){
  764.                         soapEnvelopeNamespaceVersionMismatch = ServicesUtils.checkSOAPEnvelopeNamespace(requestMessage.castAsSoap(), messageTypeReq);
  765.                     }
  766.                 }catch(Exception e){
  767.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  768.                     throw e;
  769.                 }
  770.                
  771.                 /* ------------ Controllo MustUnderstand -------------------- */
  772.                 String mustUnderstandError = null;
  773.                 if(soapEnvelopeNamespaceVersionMismatch==null) {
  774.                     try{
  775.                         if(ServiceBinding.SOAP.equals(integrationServiceBinding)){
  776.                             mustUnderstandError = ServicesUtils.checkMustUnderstand(requestMessage.castAsSoap(),protocolFactory);
  777.                         }
  778.                     }catch(Exception e){
  779.                         pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  780.                         throw e;
  781.                     }
  782.                 }
  783.                
  784.                 /* ------------  SoapAction check 2 ------------- */
  785.                 if(soapAction!=null){
  786.                     if(openSPCoopProperties.checkSoapActionQuotedString_ricezioneContenutiApplicativi()){
  787.                         try{
  788.                             SoapUtils.checkSoapActionQuotedString(soapAction, messageTypeReq);
  789.                         }catch(Exception e){
  790.                             pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  791.                             throw e;
  792.                         }
  793.                     }
  794.                 }
  795.                
  796.                 /* --------------- SecurityToken --------------- */
  797.                 try {
  798.                     if(requestInfo!=null && requestInfo.getProtocolContext()!=null && requestInfo.getProtocolContext().getCredential()!=null &&
  799.                             requestInfo.getProtocolContext().getCredential().getCertificate()!=null &&
  800.                             requestInfo.getProtocolContext().getCredential().getCertificate().getCertificate()!=null) {
  801.                         SecurityTokenUtilities.newSecurityToken(pddContext);
  802.                     }
  803.                 }catch(Exception e){
  804.                     logCore.error("Costruzione SecurityToken non riuscito: "+e.getMessage(),e);
  805.                 }
  806.                            
  807.                 /* ------------  Elaborazione ------------- */
  808.            
  809.                 if(mustUnderstandError==null && soapEnvelopeNamespaceVersionMismatch==null){
  810.                
  811.                     // Contesto di Richiesta
  812.                     context.setCredenziali(new Credenziali(req.getCredential()));
  813.                     context.setGestioneRisposta(true); // siamo in una servlet, la risposta deve essere aspettata
  814.                     context.setInvocazionePDPerRiferimento(false); // la PD con questa servlet non effettuera' mai invocazioni per riferimento.
  815.                     context.setMessageRequest(requestMessage);
  816.                     context.setUrlProtocolContext(requestInfo.getProtocolContext());
  817.                     context.setMsgDiagnostico(msgDiag);
  818.    
  819.                     // Log elaborazione dati completata
  820.                     msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.completata");
  821.            
  822.                     // se il tracciamento lo prevedo emetto un log
  823.                     registraTracciaInRequest(context, protocolFactory, logCore, msgDiag);
  824.                    
  825.                     // Invocazione...
  826.                     RicezioneContenutiApplicativi gestoreRichiesta = new RicezioneContenutiApplicativi(context, this.generatoreErrore);
  827.                     gestoreRichiesta.process(req);
  828.                     responseMessage = context.getMessageResponse();
  829.                 }  
  830.                 else{
  831.                     if(mustUnderstandError!=null){
  832.                         pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  833.                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, mustUnderstandError);
  834.                         msgDiag.logPersonalizzato("mustUnderstand.unknown");
  835.                         responseMessage = this.generatoreErrore.build(pddContext, IntegrationFunctionError.SOAP_MUST_UNDERSTAND_UNKNOWN,
  836.                                 ErroriIntegrazione.ERRORE_427_MUSTUNDERSTAND_ERROR.
  837.                                 getErrore427_MustUnderstandHeaders(mustUnderstandError),null,null);
  838.                     }
  839.                     else{
  840.                         pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  841.                         msgDiag.addKeyword(CostantiPdD.KEY_SOAP_ENVELOPE_NAMESPACE, soapEnvelopeNamespaceVersionMismatch);
  842.                         msgDiag.logPersonalizzato("soapEnvelopeNamespace.versionMismatch");
  843.                         responseMessage = this.generatoreErrore.build(pddContext, IntegrationFunctionError.SOAP_VERSION_MISMATCH,
  844.                                 ErroriIntegrazione.ERRORE_430_SOAP_ENVELOPE_NAMESPACE_ERROR.
  845.                                 getErrore430_SoapNamespaceNonSupportato(messageTypeReq, soapEnvelopeNamespaceVersionMismatch),null,null);
  846.                     }
  847.                 }
  848.             }
  849.            
  850.         }
  851.         catch (Throwable e) {
  852.            
  853.             if(context==null){
  854.                 // Errore durante la generazione dell'id
  855.                 context = RicezioneContenutiApplicativiContext.newRicezioneContenutiApplicativiContext(idModuloAsService,dataAccettazioneRichiesta,requestInfo);
  856.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  857.                 context.setTipoPorta(TipoPdD.DELEGATA);
  858.                 context.setIdModulo(idModulo);
  859.                 context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  860.                 pddContext = context.getPddContext();
  861.                 if(postOutResponseContext!=null){
  862.                     postOutResponseContext.setPddContext(pddContext);
  863.                 }
  864.                 msgDiag.setPddContext(pddContext, protocolFactory);
  865.             }
  866.            
  867.             // Se viene lanciata una eccezione, riguarda la richiesta, altrimenti è gestita dopo nel finally.
  868.             Throwable tParsing = null;
  869.             ParseException parseException = null;
  870.             if(pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION)){
  871.                 parseException = (ParseException) pddContext.removeObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);            
  872.                 if(parseException!=null) {
  873.                     tParsing = parseException.getParseException();
  874.                 }
  875.             }
  876.             if(tParsing==null && (requestMessage==null || requestMessage.getParseException() == null)){
  877.                 tParsing = ParseExceptionUtils.getParseException(e);
  878.             }
  879.            
  880.             // Genero risposta con errore
  881.             String msgErrore = e.getMessage();
  882.             if(msgErrore==null){
  883.                 msgErrore = e.toString();
  884.             }
  885.             if( ServiceBinding.SOAP.equals(integrationServiceBinding) &&
  886.                 messageTypeReq!=null &&
  887.                     (
  888.                             // Messaggio lanciato dallo streaming engine
  889.                         msgErrore.equals("Transport level information does not match with SOAP Message namespace URI") ||
  890.                         // ?
  891.                         msgErrore.equals("I dati ricevuti non rappresentano un messaggio SOAP 1.1 valido: ") ||
  892.                         // I seguenti due errori invece vengono lanciati dalle classi 'com/sun/xml/messaging/saaj/soap/ver1_2/SOAPPart1_2Impl.java' e com/sun/xml/messaging/saaj/soap/ver1_1/SOAPPart1_1Impl.java
  893.                         // Proprio nel caso il namespace non corrisponde al tipo atteso.
  894.                         msgErrore.equals("InputStream does not represent a valid SOAP 1.1 Message") ||
  895.                         msgErrore.equals("InputStream does not represent a valid SOAP 1.2 Message")
  896.                     )
  897.                 ){
  898.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  899.                 msgDiag.addKeyword(CostantiPdD.KEY_SOAP_ENVELOPE_NAMESPACE, "Impossibile recuperare il valore del namespace");
  900.                 msgDiag.logPersonalizzato("soapEnvelopeNamespace.versionMismatch");
  901.                 responseMessage = this.generatoreErrore.build(pddContext, IntegrationFunctionError.SOAP_VERSION_MISMATCH,
  902.                         ErroriIntegrazione.ERRORE_430_SOAP_ENVELOPE_NAMESPACE_ERROR.
  903.                         getErrore430_SoapNamespaceNonSupportato(messageTypeReq, "Impossibile recuperare il valore del namespace"),e,null);
  904.             } else if(tParsing!=null){
  905.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  906.                 msgErrore = tParsing.getMessage();
  907.                 if(msgErrore==null){
  908.                     msgErrore = tParsing.toString();
  909.                 }
  910.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  911.                 logCore.error("parsingExceptionRichiesta",e);
  912.                 msgDiag.logPersonalizzato("parsingExceptionRichiesta");
  913.                
  914.                 IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_REQUEST_CONTENT;
  915.                 if( parseException!=null && parseException.getSourceException()!=null &&
  916.                         TimeoutIOException.isTimeoutIOException(parseException.getSourceException())) {
  917.                     integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  918.                 }
  919.                 else if( parseException!=null && parseException.getSourceException()!=null &&
  920.                         LimitExceededIOException.isLimitExceededIOException(parseException.getSourceException())) {
  921.                     integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  922.                 }
  923.                
  924.                 responseMessage = this.generatoreErrore.build(pddContext, integrationFunctionError,
  925.                         ErroriIntegrazione.ERRORE_432_PARSING_EXCEPTION_RICHIESTA.
  926.                         getErrore432_MessaggioRichiestaMalformato(tParsing),tParsing,null);
  927.             }
  928.             else if (e instanceof HandlerException) {
  929.                 logCore.error("ErroreGenerale (HandlerException)",e);
  930.                 HandlerException he = (HandlerException) e;
  931.                 if(he.isEmettiDiagnostico()) {
  932.                     msgDiag.logErroreGenerico(e, "Generale(richiesta-handler)");
  933.                 }
  934.                 ErroreIntegrazione errore = he.convertToErroreIntegrazione();
  935.                 if(errore==null) {
  936.                     errore = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.get5XX_ErroreProcessamento("Generale(richiesta)");
  937.                 }
  938.                 IntegrationFunctionError integrationError = he.getIntegrationFunctionError();
  939.                 if(integrationError==null) {
  940.                     integrationError = IntegrationFunctionError.BAD_REQUEST;
  941.                 }
  942.                 responseMessage = this.generatoreErrore.build(pddContext,integrationError,errore,e,null);
  943.                 he.customized(responseMessage);
  944.             }
  945.             else {
  946.                 logCore.error("ErroreGenerale",e);
  947.                 msgDiag.logErroreGenerico(e, "Generale(richiesta)");
  948.                 responseMessage = this.generatoreErrore.build(pddContext, IntegrationFunctionError.BAD_REQUEST,
  949.                         ErroriIntegrazione.ERRORE_426_SERVLET_ERROR.
  950.                         getErrore426_ServletError(true, e),e,null);
  951.             }
  952.         }
  953.         finally{
  954.            
  955.             try {
  956.                 GestoreRichieste.saveRequestConfig(requestInfo);
  957.             }catch(Throwable e) {
  958.                 logCore.error("Errore durante il salvataggio dei dati della richiesta: "+e.getMessage(),e);
  959.             }

  960.             String requestReadTimeout = null;
  961.             String responseReadTimeout = null;
  962.             if(pddContext!=null && pddContext.containsKey(TimeoutInputStream.ERROR_MSG_KEY)) {
  963.                 String timeoutMessage = PdDContext.getValue(TimeoutInputStream.ERROR_MSG_KEY, pddContext);
  964.                 if(timeoutMessage!=null && timeoutMessage.startsWith(CostantiPdD.PREFIX_TIMEOUT_REQUEST)) {
  965.                     requestReadTimeout = timeoutMessage;
  966.                 }
  967.                 else if(timeoutMessage!=null && timeoutMessage.startsWith(CostantiPdD.PREFIX_TIMEOUT_RESPONSE)) {
  968.                     responseReadTimeout = timeoutMessage;
  969.                 }
  970.             }
  971.             String requestLimitExceeded = null;
  972.             String responseLimitExceeded = null;
  973.             if(pddContext!=null && pddContext.containsKey(LimitedInputStream.ERROR_MSG_KEY)) {
  974.                 String limitedExceededMessage = PdDContext.getValue(LimitedInputStream.ERROR_MSG_KEY, pddContext);
  975.                 if(limitedExceededMessage!=null && limitedExceededMessage.startsWith(CostantiPdD.PREFIX_LIMITED_REQUEST)) {
  976.                     requestLimitExceeded = limitedExceededMessage;
  977.                 }
  978.                 else if(limitedExceededMessage!=null && limitedExceededMessage.startsWith(CostantiPdD.PREFIX_LIMITED_RESPONSE)) {
  979.                     responseLimitExceeded = limitedExceededMessage;
  980.                 }
  981.             }
  982.            
  983.             if((requestMessage!=null && requestMessage.getParseException() != null) ||
  984.                     (pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION)) ||
  985.                     requestReadTimeout!=null ||
  986.                     requestLimitExceeded!=null){
  987.                 if(pddContext!=null) {
  988.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  989.                 }
  990.                
  991.                 ParseException parseException = null;
  992.                 Throwable tParsing = null;
  993.                 Throwable sParsing = null;
  994.                 String msgErrore = null;
  995.                 if(requestReadTimeout != null) {
  996.                     tParsing = (TimeoutIOException) pddContext.getObject(TimeoutInputStream.EXCEPTION_KEY);
  997.                     sParsing = tParsing;
  998.                     msgErrore = tParsing.getMessage();
  999.                 }
  1000.                 else if(requestLimitExceeded != null) {
  1001.                     tParsing = (LimitExceededIOException) pddContext.getObject(LimitedInputStream.EXCEPTION_KEY);
  1002.                     sParsing = tParsing;
  1003.                     msgErrore = tParsing.getMessage();
  1004.                 }
  1005.                 else if( requestMessage!=null && requestMessage.getParseException() != null ){
  1006.                     parseException = requestMessage.getParseException();
  1007.                     tParsing = parseException.getParseException();
  1008.                     sParsing = parseException.getSourceException();
  1009.                     msgErrore = tParsing.getMessage();
  1010.                 }
  1011.                 else {
  1012.                     parseException = (ParseException) pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  1013.                     tParsing = parseException.getParseException();
  1014.                     sParsing = parseException.getSourceException();
  1015.                     msgErrore = tParsing.getMessage();
  1016.                 }          
  1017.                
  1018.                 if(msgErrore==null && tParsing!=null){
  1019.                     msgErrore = tParsing.toString();
  1020.                 }
  1021.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  1022.                 logCore.error("parsingExceptionRichiesta",sParsing);
  1023.                 msgDiag.logPersonalizzato("parsingExceptionRichiesta");
  1024.                
  1025.                 IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_REQUEST_CONTENT;
  1026.                 if(requestReadTimeout!=null) {
  1027.                     integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  1028.                 }
  1029.                 else if(requestLimitExceeded!=null) {
  1030.                     integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  1031.                 }
  1032.                 else if( parseException!=null && sParsing!=null &&
  1033.                         TimeoutIOException.isTimeoutIOException(sParsing)) {
  1034.                     integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  1035.                 }
  1036.                 else if( parseException!=null && sParsing!=null &&
  1037.                         LimitExceededIOException.isLimitExceededIOException(sParsing)) {
  1038.                     integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  1039.                 }
  1040.                
  1041.                 responseMessage = this.generatoreErrore.build(pddContext, integrationFunctionError,
  1042.                         ErroriIntegrazione.ERRORE_432_PARSING_EXCEPTION_RICHIESTA.
  1043.                         getErrore432_MessaggioRichiestaMalformato(tParsing),
  1044.                         tParsing,null);
  1045.             }
  1046.             else if( (responseMessage!=null && responseMessage.getParseException() != null) ||
  1047.                     (pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION)) ||
  1048.                     responseReadTimeout!=null ||
  1049.                     responseLimitExceeded!=null){
  1050.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO, true);
  1051.                
  1052.                 ParseException parseException = null;
  1053.                 Throwable tParsing = null;
  1054.                 Throwable sParsing = null;
  1055.                 String msgErrore = null;
  1056.                 if(responseReadTimeout != null) {
  1057.                     tParsing = (TimeoutIOException) pddContext.getObject(TimeoutInputStream.EXCEPTION_KEY);
  1058.                     sParsing = tParsing;
  1059.                     msgErrore = tParsing.getMessage();
  1060.                 }
  1061.                 else if(responseLimitExceeded != null) {
  1062.                     tParsing = (LimitExceededIOException) pddContext.getObject(LimitedInputStream.EXCEPTION_KEY);
  1063.                     sParsing = tParsing;
  1064.                     msgErrore = tParsing.getMessage();
  1065.                 }
  1066.                 else if( responseMessage!=null && responseMessage.getParseException() != null ){
  1067.                     parseException = responseMessage.getParseException();
  1068.                     tParsing = parseException.getParseException();
  1069.                     sParsing = parseException.getSourceException();
  1070.                     msgErrore = tParsing.getMessage();
  1071.                 }
  1072.                 else{
  1073.                     parseException = (ParseException) pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  1074.                     tParsing = parseException.getParseException();
  1075.                     sParsing = parseException.getSourceException();
  1076.                     msgErrore = tParsing.getMessage();
  1077.                 }

  1078.                 if(msgErrore==null && tParsing!=null){
  1079.                     msgErrore = tParsing.toString();
  1080.                 }          
  1081.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  1082.                 logCore.error("parsingExceptionRisposta",sParsing);
  1083.                
  1084.                 IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_RESPONSE_CONTENT;
  1085.                 if(responseReadTimeout!=null) {
  1086.                     integrationFunctionError = IntegrationFunctionError.ENDPOINT_REQUEST_TIMED_OUT;
  1087.                 }
  1088.                 else if(responseLimitExceeded!=null) {
  1089.                     integrationFunctionError = IntegrationFunctionError.RESPONSE_SIZE_EXCEEDED;
  1090.                 }
  1091.                 else if(sParsing!=null &&
  1092.                         TimeoutIOException.isTimeoutIOException(sParsing)) {
  1093.                     integrationFunctionError = IntegrationFunctionError.ENDPOINT_REQUEST_TIMED_OUT;
  1094.                 }
  1095.                 else if(sParsing!=null &&
  1096.                         LimitExceededIOException.isLimitExceededIOException(sParsing)) {
  1097.                     integrationFunctionError = IntegrationFunctionError.RESPONSE_SIZE_EXCEEDED;
  1098.                 }
  1099.                
  1100.                 msgDiag.logPersonalizzato("parsingExceptionRisposta");
  1101.                 responseMessage = this.generatoreErrore.build(pddContext, integrationFunctionError,
  1102.                         ErroriIntegrazione.ERRORE_440_PARSING_EXCEPTION_RISPOSTA.
  1103.                         getErrore440_MessaggioRispostaMalformato(tParsing),
  1104.                         tParsing,null);
  1105.             }
  1106.            
  1107.            
  1108.             try{
  1109.                 // Se non sono stati recuperati i dati delle url, provo a recuperarli
  1110.                 URLProtocolContext urlProtocolContext = context!=null ? context.getUrlProtocolContext() : null;
  1111.                 if(urlProtocolContext==null){
  1112.                     urlProtocolContext = req.getURLProtocolContext();
  1113.                 }
  1114.                 if(urlProtocolContext!=null && pddContext!=null){
  1115.                     String urlInvocazione = urlProtocolContext.getUrlInvocazione_formBased();
  1116.                     if(urlProtocolContext.getFunction()!=null){
  1117.                         urlInvocazione = "["+urlProtocolContext.getFunction()+"] "+urlInvocazione;
  1118.                     }
  1119.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.URL_INVOCAZIONE, urlInvocazione);
  1120.                 }
  1121.             }catch(Throwable t){
  1122.                 // ignore
  1123.             }
  1124.             try{
  1125.                 Credenziali credenziali = context!=null ? context.getCredenziali() : null;
  1126.                 if(credenziali==null){
  1127.                     credenziali = new Credenziali(req.getCredential());
  1128.                 }
  1129.                 if(credenziali!=null && pddContext!=null){
  1130.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CREDENZIALI_INVOCAZIONE, credenziali.toString());
  1131.                 }
  1132.             }catch(Throwable t){
  1133.                 // ignore
  1134.             }
  1135.                
  1136.            
  1137.             try{
  1138.                 req.close();
  1139.             }catch(Exception e){
  1140.                 logCore.error("Request.close() error: "+e.getMessage(),e);
  1141.             }
  1142.         }
  1143.        
  1144.         // Imposto risposta

  1145.         Date dataPrimaSpedizioneRisposta = DateManager.getDate();
  1146.         Date dataRispostaSpedita = null;
  1147.         Transazione transazioneDaAggiornare = null;
  1148.        
  1149.         if(context.getMsgDiagnostico()!=null){
  1150.             msgDiag = context.getMsgDiagnostico();
  1151.         }
  1152.         if(context.getResponseHeaders()==null) {
  1153.             context.setResponseHeaders(new HashMap<>());
  1154.         }
  1155.         ServicesUtils.setGovWayHeaderResponse(requestMessage!=null ? requestMessage.getServiceBinding() : requestInfo.getProtocolServiceBinding(),
  1156.                 responseMessage, openSPCoopProperties,
  1157.                 context.getResponseHeaders(), logCore, true, context.getPddContext(), requestInfo);
  1158.         if(context.getResponseHeaders()!=null){
  1159.             Iterator<String> keys = context.getResponseHeaders().keySet().iterator();
  1160.             while (keys.hasNext()) {
  1161.                 String key = (String) keys.next();
  1162.                 List<String> values = context.getResponseHeaders().get(key);
  1163.                 if(values!=null && !values.isEmpty()) {
  1164.                     for (int i = 0; i < values.size(); i++) {
  1165.                         String value = values.get(i);
  1166.                         String verbo = "";
  1167.                         try{
  1168.                             if(i==0) {
  1169.                                 verbo = "set";
  1170.                                 res.setHeader(key,value);
  1171.                             }
  1172.                             else {
  1173.                                 verbo = "add";
  1174.                                 res.addHeader(key,value);
  1175.                             }
  1176.                         }catch(Exception e){
  1177.                             logCore.error("Response."+verbo+"Header("+key+","+value+") error: "+e.getMessage(),e);
  1178.                         }  
  1179.                     }
  1180.                 }
  1181.             }  
  1182.         }
  1183.         if(context!=null && context.getProtocol()!=null){
  1184.            
  1185.             this.generatoreErrore.updateDominio(context.getIdentitaPdD());
  1186.        
  1187.             IDServizio idServizio = null;
  1188.             try{
  1189.                 idServizio = IDServizioFactory.getInstance().getIDServizioFromValues(context.getProtocol().getTipoServizio(),
  1190.                         context.getProtocol().getServizio(),
  1191.                         context.getProtocol().getErogatore(),
  1192.                         context.getProtocol().getVersioneServizio());
  1193.             }catch(Exception e){
  1194.                 // non dovrebbe succedere eccezione}
  1195.             }
  1196.             if(idServizio!=null){
  1197.                 idServizio.setAzione(context.getProtocol().getAzione());
  1198.                 this.generatoreErrore.updateInformazioniCooperazione(context.getProtocol().getFruitore(), idServizio);
  1199.             }
  1200.                            
  1201.             String servizioApplicativo = null;
  1202.             if(context.getIntegrazione()!=null){
  1203.                 servizioApplicativo = context.getIntegrazione().getServizioApplicativoFruitore();
  1204.             }
  1205.             this.generatoreErrore.updateInformazioniCooperazione(servizioApplicativo);
  1206.            
  1207.             this.generatoreErrore.updateProprietaErroreApplicativo(context.getProprietaErroreAppl());

  1208.         }
  1209.         DirectVMConnectorOutMessage vm = null;
  1210.         if(res instanceof DirectVMConnectorOutMessage){
  1211.             vm = (DirectVMConnectorOutMessage) res;
  1212.         }
  1213.         else if(req instanceof DumpRawConnectorOutMessage){
  1214.             if( ((DumpRawConnectorOutMessage)res).getWrappedConnectorOutMessage() instanceof DirectVMConnectorOutMessage ){
  1215.                 vm = (DirectVMConnectorOutMessage) ((DumpRawConnectorOutMessage)res).getWrappedConnectorOutMessage();
  1216.             }
  1217.         }
  1218.         if(vm!=null){
  1219.             if(context!=null && context.getPddContext()!=null){
  1220.                 DirectVMProtocolInfo pInfo = new DirectVMProtocolInfo();
  1221.                 Object oIdTransazione = context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  1222.                 if(oIdTransazione!=null){
  1223.                     pInfo.setIdTransazione((String)oIdTransazione);
  1224.                 }
  1225.                 if(context.getProtocol()!=null){
  1226.                     if(context.getProtocol().getIdRichiesta()!=null){
  1227.                         pInfo.setIdMessaggioRichiesta(context.getProtocol().getIdRichiesta());
  1228.                     }
  1229.                     if(context.getProtocol().getIdRisposta()!=null){
  1230.                         pInfo.setIdMessaggioRisposta(context.getProtocol().getIdRisposta());
  1231.                     }
  1232.                 }
  1233.                 vm.setDirectVMProtocolInfo(pInfo);
  1234.             }
  1235.         }
  1236.        
  1237.         InformazioniErroriInfrastrutturali informazioniErrori = ServicesUtils.readInformazioniErroriInfrastrutturali(pddContext);
  1238.        
  1239.         OpenSPCoop2Message responseMessageError = null;
  1240.         EsitoTransazione esito = null;
  1241.         String descrizioneSoapFault = "";
  1242.         int statoServletResponse = 200;
  1243.         Throwable erroreConsegnaRisposta = null;
  1244.         boolean httpEmptyResponse = false;
  1245.         boolean erroreConnessioneClient = false;
  1246.         boolean erroreResponseTimeout = false;
  1247.         boolean erroreResponsePayloadTooLarge = false;
  1248.         boolean sendInvoked = false;
  1249.         boolean registraTracciaOutResponse = false;
  1250.         try{
  1251.             if(responseMessage!=null && !responseMessage.isForcedEmptyResponse() && (responseMessage.getForcedResponse()==null)){
  1252.                    
  1253.                 // force response code
  1254.                 if(responseMessage.getForcedResponseCode()!=null){
  1255.                     try{
  1256.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1257.                     }catch(Exception e){
  1258.                         // ignore
  1259.                     }
  1260.                 }
  1261.                                
  1262.                 // transfer length
  1263.                 ServicesUtils.setTransferLength(openSPCoopProperties.getTransferLengthModes_ricezioneContenutiApplicativi(),
  1264.                         req, res, responseMessage);
  1265.                
  1266.                 // content type
  1267.                 // Alcune implementazioni richiedono di aggiornare il Content-Type
  1268.                 responseMessage.updateContentType();
  1269.                 ServicesUtils.setContentType(responseMessage, res);
  1270.                
  1271.                 // http status
  1272.                 boolean consume = true;
  1273.                 if(ServiceBinding.SOAP.equals(responseMessage.getServiceBinding()) ){
  1274.                     //SOAPBody body = responseMessage.castAsSoap().getSOAPBody();
  1275.                     OpenSPCoop2SoapMessage soapMessage = responseMessage.castAsSoap();
  1276.                     if(soapMessage.hasSOAPFault()){
  1277.                         consume = false; // può essere usato nel post out response handler
  1278.                         statoServletResponse = 500;
  1279.                         descrizioneSoapFault = " ("+SoapUtils.safe_toString(responseMessage.getFactory(), soapMessage.getSOAPBody().getFault(), false, logCore)+")";
  1280.                     }
  1281.                     else if(statoServletResponse==500) {
  1282.                         // in SOAP 500 deve essere associato con un fault
  1283.                         if(!soapMessage.isSOAPBodyEmpty()) {
  1284.                             statoServletResponse = 200;
  1285.                         }
  1286.                         else {
  1287.                             statoServletResponse = protocolFactory.createProtocolManager().getHttpReturnCodeEmptyResponseOneWay();
  1288.                         }
  1289.                     }
  1290.                 }
  1291.                 else if(responseMessage.castAsRest().isProblemDetailsForHttpApis_RFC7807() ||
  1292.                         (MessageRole.FAULT.equals(responseMessage.getMessageRole()) &&
  1293.                             (
  1294.                             MessageType.XML.equals(responseMessage.getMessageType())
  1295.                                     ||
  1296.                             MessageType.JSON.equals(responseMessage.getMessageType())
  1297.                             )
  1298.                         )
  1299.                     ) {
  1300.                     consume = false; // può essere usato nel post out response handler
  1301.                     String contentAsString = null;
  1302.                     try {
  1303.                         contentAsString = responseMessage.castAsRest().getContentAsString();
  1304.                     }catch(Throwable t) {
  1305.                         logCore.error("Parsing errore non riuscito: "+t.getMessage(),t);
  1306.                     }
  1307.                     if(contentAsString!=null && StringUtils.isNotEmpty(contentAsString)) {
  1308.                         descrizioneSoapFault = " ("+contentAsString+")";
  1309.                     }
  1310.                 }
  1311.                 res.setStatus(statoServletResponse);
  1312.                
  1313.                 // esito calcolato prima del sendResponse, per non consumare il messaggio
  1314.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1315.                         statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1316.                         responseMessage, context.getProprietaErroreAppl(), informazioniErrori,
  1317.                         pddContext);
  1318.                
  1319.                 // se il tracciamento lo prevedo emetto un log
  1320.                 registraTracciaOutResponse = true;
  1321.                 transazioneDaAggiornare = registraTracciaOutResponse(context, postOutResponseContext,
  1322.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1323.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1324.                         esito, statoServletResponse,
  1325.                         idModulo, req, requestMessage,
  1326.                         responseMessage, erroreConsegnaRisposta, responseMessageError,
  1327.                         msgDiag);
  1328.                
  1329.                 // contenuto
  1330.                 Utilities.printFreeMemory("RicezioneContenutiApplicativiDirect - Pre scrittura risposta");
  1331.                
  1332.                 // Il contentLenght, nel caso di TransferLengthModes.CONTENT_LENGTH e' gia' stato calcolato
  1333.                 // con una writeTo senza consume. Riuso il solito metodo per evitare differenze di serializzazione
  1334.                 // e cambiare quindi il content length effettivo.
  1335.                 sendInvoked = true;
  1336.                 if(TransferLengthModes.CONTENT_LENGTH.equals(openSPCoopProperties.getTransferLengthModes_ricezioneContenutiApplicativi())){
  1337.                     res.sendResponse(responseMessage, false);
  1338.                 } else {
  1339.                     res.sendResponse(responseMessage, consume);
  1340.                 }
  1341.                 Utilities.printFreeMemory("RicezioneContenutiApplicativiDirect - Post scrittura risposta");


  1342.             }
  1343.            
  1344.             else if(responseMessage!=null && responseMessage.getForcedResponse()!=null) {
  1345.                 byte[]response = responseMessage.getForcedResponse().getContent();
  1346. //              if(response==null) {
  1347. //                  throw new Exception("Trovata configurazione 'forcedResponse' senza una vera risposta");
  1348. //              }
  1349.            
  1350.                 if(response!=null && response.length<1024) {
  1351.                     // Se il messaggio non è troppo grande lo aggiungo al diagnostico
  1352.                     try {
  1353.                         descrizioneSoapFault = "("+new String(response)+")";
  1354.                     }catch(Throwable t) {
  1355.                         descrizioneSoapFault = "";
  1356.                     }
  1357.                 }
  1358.                
  1359.                 if(responseMessage.getForcedResponse().getHeadersValues()!=null &&
  1360.                         responseMessage.getForcedResponse().getHeadersValues().size()>0) {
  1361.                     Iterator<String> keys = responseMessage.getForcedResponse().getHeadersValues().keySet().iterator();
  1362.                     while (keys.hasNext()) {
  1363.                         String key = (String) keys.next();
  1364.                         List<String> values = responseMessage.getForcedResponse().getHeadersValues().get(key);
  1365.                         if(values!=null && !values.isEmpty()) {
  1366.                             for (int i = 0; i < values.size(); i++) {
  1367.                                 String value = values.get(i);
  1368.                                 String verbo = "";
  1369.                                 try{
  1370.                                     if(i==0) {
  1371.                                         verbo = "set";
  1372.                                         res.setHeader(key,value);
  1373.                                     }
  1374.                                     else {
  1375.                                         verbo = "add";
  1376.                                         res.addHeader(key,value);
  1377.                                     }
  1378.                                 }catch(Exception e){
  1379.                                     logCore.error("Response(Forced)."+verbo+"Header("+key+","+value+") error: "+e.getMessage(),e);
  1380.                                 }  
  1381.                             }
  1382.                         }
  1383.                     }  
  1384.                 }
  1385.                
  1386.                 if(responseMessage.getForcedResponse().getContentType()!=null) {
  1387.                     res.setContentType(responseMessage.getForcedResponse().getContentType());
  1388.                 }
  1389.                
  1390.                 if(responseMessage.getForcedResponse().getResponseCode()!=null) {
  1391.                     try{
  1392.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponse().getResponseCode());
  1393.                     }catch(Exception e){
  1394.                         // ignore
  1395.                     }
  1396.                 }
  1397.                 else if(responseMessage!=null && responseMessage.getForcedResponseCode()!=null) {
  1398.                     try{
  1399.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1400.                     }catch(Exception e){
  1401.                         // ignore
  1402.                     }
  1403.                 }
  1404.                 res.setStatus(statoServletResponse);
  1405.                
  1406.                 // esito calcolato prima del sendResponse, per non consumare il messaggio
  1407.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1408.                         statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1409.                         responseMessage, context.getProprietaErroreAppl(),informazioniErrori,
  1410.                         pddContext);
  1411.                
  1412.                 // se il tracciamento lo prevedo emetto un log
  1413.                 registraTracciaOutResponse = true;
  1414.                 transazioneDaAggiornare = registraTracciaOutResponse(context, postOutResponseContext,
  1415.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1416.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1417.                         esito, statoServletResponse,
  1418.                         idModulo, req, requestMessage,
  1419.                         responseMessage, erroreConsegnaRisposta, responseMessageError,
  1420.                         msgDiag);
  1421.                
  1422.                 if(response!=null) {
  1423.                     sendInvoked = true;
  1424.                     res.sendResponse(DumpByteArrayOutputStream.newInstance(response));
  1425.                 }
  1426.                
  1427.             }
  1428.             else{
  1429.                 if(responseMessage!=null && responseMessage.getForcedResponseCode()!=null) {
  1430.                     try{
  1431.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1432.                     }catch(Exception e){
  1433.                         // ignore
  1434.                     }
  1435.                 }
  1436.                 else {
  1437.                     statoServletResponse = protocolFactory.createProtocolManager().getHttpReturnCodeEmptyResponseOneWay();
  1438.                 }
  1439.                 res.setStatus(statoServletResponse);
  1440.                 httpEmptyResponse = true;
  1441.                
  1442.                 // carico-vuoto gestito all'interno
  1443.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1444.                         statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1445.                         responseMessage, context.getProprietaErroreAppl(), informazioniErrori,
  1446.                         pddContext);
  1447.                
  1448.                 // se il tracciamento lo prevedo emetto un log
  1449.                 registraTracciaOutResponse = true;
  1450.                 transazioneDaAggiornare = registraTracciaOutResponse(context, postOutResponseContext,
  1451.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1452.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1453.                         esito, statoServletResponse,
  1454.                         idModulo, req, requestMessage,
  1455.                         responseMessage, erroreConsegnaRisposta, responseMessageError,
  1456.                         msgDiag);

  1457.             }
  1458.         }catch(Throwable e){            
  1459.             logCore.error("ErroreGenerale",e);
  1460.             erroreConsegnaRisposta = e;
  1461.                        
  1462.             erroreConnessioneClient = ServicesUtils.isConnessioneClientNonDisponibile(e);
  1463.             if(!erroreConnessioneClient && ServicesUtils.isConnessioneServerReadTimeout(e)) {
  1464.                 erroreResponseTimeout = true; // non e' stato possibile consegnare tutta la risposta. Il client ha ricevuto 200 ma non ha ricevuto la risposta per intero
  1465.                 erroreConsegnaRisposta = new CoreException("Connessione con il backend dell'API non più disponibile: "+e.getMessage(),e);
  1466.             }
  1467.             if(!erroreConnessioneClient && !erroreResponseTimeout && ServicesUtils.isResponsePayloadTooLarge(e)) {
  1468.                 erroreResponsePayloadTooLarge = true;  // non e' stato possibile consegnare tutta la risposta. Il client ha ricevuto 200 ma non ha ricevuto la risposta per intero
  1469.                 erroreConsegnaRisposta = new CoreException("Risposta ricevuta dal backend dell'API non gestibile: "+e.getMessage(),e);
  1470.             }
  1471.            
  1472.             // Genero risposta con errore
  1473.             try{
  1474.                 if(sendInvoked==false) {
  1475.                     // nel caso sia già stato inoltrata una risposta non e' più possibile modificarlo cosi come tutti gli header etc...
  1476.                     InformazioniErroriInfrastrutturali informazioniErrori_error = new InformazioniErroriInfrastrutturali();
  1477.                     if( (responseMessage!=null && responseMessage.getParseException() != null) ||
  1478.                             (pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION))){
  1479.                         informazioniErrori_error.setContenutoRispostaNonRiconosciuto(true);
  1480.                         ParseException parseException = null;
  1481.                         if( responseMessage!=null && responseMessage.getParseException() != null ){
  1482.                             parseException = responseMessage.getParseException();
  1483.                         }
  1484.                         else{
  1485.                             parseException = (ParseException) pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  1486.                         }
  1487.                         String msgErrore = parseException.getParseException().getMessage();
  1488.                         if(msgErrore==null){
  1489.                             msgErrore = parseException.getParseException().toString();
  1490.                         }
  1491.                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  1492.                         logCore.error("parsingExceptionRisposta",parseException.getSourceException());
  1493.                         msgDiag.logPersonalizzato("parsingExceptionRisposta");
  1494.                         responseMessageError = this.generatoreErrore.build(pddContext, IntegrationFunctionError.UNPROCESSABLE_RESPONSE_CONTENT,
  1495.                                 ErroriIntegrazione.ERRORE_440_PARSING_EXCEPTION_RISPOSTA.
  1496.                                 getErrore440_MessaggioRispostaMalformato(parseException.getParseException()),
  1497.                                 parseException.getParseException(),null);
  1498.                     } else{
  1499.                         IntegrationFunctionError ife = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  1500.                         if(e instanceof HandlerException) {
  1501.                             HandlerException he = (HandlerException) e;
  1502.                             if(he.getIntegrationFunctionError()!=null) {
  1503.                                 ife = he.getIntegrationFunctionError();
  1504.                             }
  1505.                         }
  1506.                         responseMessageError = this.generatoreErrore.build(pddContext, ife,
  1507.                                 ErroriIntegrazione.ERRORE_426_SERVLET_ERROR.
  1508.                                 getErrore426_ServletError(false, e),
  1509.                                 e,null);
  1510.                     }
  1511.                    
  1512.                     // transfer length
  1513.                     ServicesUtils.setTransferLength(openSPCoopProperties.getTransferLengthModes_ricezioneContenutiApplicativi(),
  1514.                             req, res, responseMessageError);
  1515.                    
  1516.                     // content type
  1517.                     ServicesUtils.setContentType(responseMessageError, res);
  1518.                    
  1519.                     // http status
  1520.                     if(responseMessageError!=null && responseMessageError.getForcedResponseCode()!=null) {
  1521.                         try{
  1522.                             statoServletResponse = Integer.parseInt(responseMessageError.getForcedResponseCode());
  1523.                             res.setStatus(statoServletResponse);
  1524.                         }catch(Exception eStatus){
  1525.                             // ignore
  1526.                         }
  1527.                     }
  1528.                     if(responseMessageError!=null && ServiceBinding.SOAP.equals(responseMessageError.getServiceBinding()) ){
  1529.                         SOAPBody body = responseMessageError.castAsSoap().getSOAPBody();
  1530.                         if(body!=null && body.hasFault()){
  1531.                             statoServletResponse = 500;
  1532.                             res.setStatus(statoServletResponse);
  1533.                             descrizioneSoapFault = " ("+SoapUtils.safe_toString(responseMessageError.getFactory(), body.getFault(), false, logCore)+")";
  1534.                         }
  1535.                     }
  1536.                    
  1537.                     // esito calcolato prima del sendResponse, per non consumare il messaggio
  1538.                     esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1539.                             statoServletResponse, requestInfo.getIntegrationServiceBinding(),
  1540.                             responseMessageError, context.getProprietaErroreAppl(), informazioniErrori_error,
  1541.                             pddContext);
  1542.                    
  1543.                     // se il tracciamento lo prevedo emetto un log
  1544.                     // se ho già provato prima a tracciare non lo faccio un'altra volta
  1545.                     if(!registraTracciaOutResponse) {
  1546.                         transazioneDaAggiornare = registraTracciaOutResponse(context, postOutResponseContext,
  1547.                             dataAccettazioneRichiesta, dataIngressoRichiesta,
  1548.                             dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1549.                             esito, statoServletResponse,
  1550.                             idModulo, req, requestMessage,
  1551.                             responseMessage, erroreConsegnaRisposta, responseMessageError,
  1552.                             msgDiag);
  1553.                     }
  1554.                    
  1555.                     // contenuto
  1556.                     // Il contentLenght, nel caso di TransferLengthModes.CONTENT_LENGTH e' gia' stato calcolato
  1557.                     // con una writeTo senza consume. Riuso il solito metodo per evitare differenze di serializzazione
  1558.                     // e cambiare quindi il content length effettivo.
  1559.                     //if(TransferLengthModes.CONTENT_LENGTH.equals(openSPCoopProperties.getTransferLengthModes_ricezioneContenutiApplicativi())){
  1560.                     //  res.sendResponse(responseMessageError, false);
  1561.                     //} else {
  1562.                         //res.sendResponse(responseMessageError, true);
  1563.                         res.sendResponse(responseMessageError, false); // può essere usato nel post out response handler
  1564.                     //}
  1565.                 }
  1566.                                                                
  1567.             }catch(Throwable error){
  1568.                
  1569.                 if(!erroreConnessioneClient){
  1570.                     erroreConnessioneClient = ServicesUtils.isConnessioneClientNonDisponibile(error);
  1571.                 }
  1572.                
  1573.                 logCore.error("Generazione di un risposta errore non riuscita",error);
  1574.                 statoServletResponse = 500;
  1575.                 try{
  1576.                     IntegrationFunctionError ife = null;
  1577.                     if(error instanceof HandlerException) {
  1578.                         HandlerException he = (HandlerException) error;
  1579.                         if(he.getIntegrationFunctionError()!=null) {
  1580.                             ife = he.getIntegrationFunctionError();
  1581.                         }
  1582.                     }
  1583.                     if(ife!=null) {
  1584.                         responseMessageError = this.generatoreErrore.buildFault(error, pddContext, ife);
  1585.                     }else {
  1586.                         responseMessageError = this.generatoreErrore.buildFault(error, pddContext);
  1587.                     }
  1588.                     if(responseMessageError!=null && responseMessageError.getForcedResponseCode()!=null) {
  1589.                         try{
  1590.                             statoServletResponse = Integer.parseInt(responseMessageError.getForcedResponseCode());
  1591.                         }catch(Exception eStatus){
  1592.                             // ignore
  1593.                         }
  1594.                     }
  1595.                    
  1596.                     try{
  1597.                         res.setStatus(statoServletResponse);
  1598.                     }catch(Exception eStatus){
  1599.                         logCore.error("Response.setStatus("+statoServletResponse+") error: "+eStatus.getMessage(),eStatus);
  1600.                     }
  1601.                    
  1602.                     res.sendResponse(responseMessageError, false); // può essere usato nel post out response handler
  1603.                 }catch(Throwable  eError){
  1604.                     if(!erroreConnessioneClient){
  1605.                         erroreConnessioneClient = ServicesUtils.isConnessioneClientNonDisponibile(eError);
  1606.                     }
  1607.                     try {
  1608.                         res.setStatus(statoServletResponse);
  1609.                     }catch(Throwable t) {
  1610.                         // ignore
  1611.                     }
  1612.                     try{
  1613.                         res.sendResponse(DumpByteArrayOutputStream.newInstance(error.toString().getBytes()));
  1614.                     }catch(Exception erroreStreamChiuso){
  1615.                         erroreConnessioneClient = true;
  1616.                         //se lo stream non e' piu' disponibile non si potra' consegnare alcuna risposta
  1617.                     }
  1618.                 }
  1619.                 try{
  1620.                     esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX);
  1621.                 }catch(Exception eBuildError){
  1622.                     esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1623.                 }
  1624.             }
  1625.            
  1626.         }finally{
  1627.                        
  1628.             if(sendInvoked==false) {
  1629.                 // nel caso sia già stato inoltrata una risposta non e' più possibile modificarlo cosi come tutti gli header etc...
  1630.                 statoServletResponse = res.getResponseStatus(); // puo' essere "trasformato" da api engine
  1631.             }
  1632.             msgDiag.addKeyword(CostantiPdD.KEY_CODICE_CONSEGNA, ""+statoServletResponse);
  1633.             msgDiag.addKeyword(CostantiPdD.KEY_SOAP_FAULT, descrizioneSoapFault);
  1634.            
  1635.             try{

  1636.                 // Flush and close response
  1637.                 // NOTA: per poter ottenere l'errore di BrokenPipe sempre, deve essere disabilitato il socketBufferOutput sul servlet container.
  1638.                 // Se non lo si disabilta, l'errore viene ritornato solo se il messaggio supera la dimensione del buffer (default: 8192K)
  1639.                 // Ad esempio in tomcat utilizzare (socketBuffer="-1"):
  1640.                 //    <Connector protocol="HTTP/1.1" port="8080" address="${jboss.bind.address}"
  1641.                 //       connectionTimeout="20000" redirectPort="8443" socketBuffer="-1" />
  1642.                 res.flush(true);
  1643.                 res.close(true);
  1644.                
  1645.                 dataRispostaSpedita = DateManager.getDate();
  1646.                
  1647.                 // Emetto diagnostico
  1648.                 if(erroreConsegnaRisposta!=null){
  1649.                    
  1650.                     // Risposta non ritornata al servizio applicativo, il socket verso il servizio applicativo era chiuso o cmq inutilizzabile
  1651.                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_CONSEGNA, erroreConsegnaRisposta.toString()); // NOTA: lasciare e.toString()
  1652.                     msgDiag.logPersonalizzato("consegnaRispostaApplicativaFallita");
  1653.                    
  1654.                 }else{
  1655.                     if(httpEmptyResponse){
  1656.                         msgDiag.logPersonalizzato("consegnaRispostaApplicativaVuota");
  1657.                     }else{
  1658.                         if(statoServletResponse>=300)
  1659.                             msgDiag.logPersonalizzato("consegnaRispostaApplicativaKoEffettuata");
  1660.                         else
  1661.                             msgDiag.logPersonalizzato("consegnaRispostaApplicativaOkEffettuata");
  1662.                     }
  1663.                 }
  1664.                
  1665.             }catch(Exception e){
  1666.                
  1667.                 erroreConnessioneClient = true;
  1668.                
  1669.                 logCore.error("Chiusura stream non riuscita",e);
  1670.                
  1671.                 // Risposta non ritornata al servizio applicativo, il socket verso il servizio applicativo era chiuso o cmq inutilizzabile
  1672.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_CONSEGNA, e.toString()); // NOTA: lasciare e.toString()
  1673.                
  1674.                 msgDiag.logPersonalizzato("consegnaRispostaApplicativaFallita");
  1675.                
  1676.                 erroreConsegnaRisposta = e;
  1677.                
  1678.                 if(esito!=null){
  1679.                     if(EsitoTransazioneName.OK.equals(esito.getName())){
  1680.                         // non è ok, essendo andato in errore il flush
  1681.                         try{
  1682.                             esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX);
  1683.                         }catch(Exception eBuildError){
  1684.                             esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1685.                         }
  1686.                     }
  1687.                 }
  1688.                 else{
  1689.                     // non dovrebbe mai essere null
  1690.                 }
  1691.                
  1692.             } finally {
  1693.                 if(dataRispostaSpedita==null) {
  1694.                     dataRispostaSpedita = DateManager.getDate();
  1695.                 }
  1696.             }
  1697.            
  1698.             if(dumpRaw!=null && dumpRaw.isActiveDumpRisposta()){
  1699.                 dumpRaw.serializeResponse(((DumpRawConnectorOutMessage)res));
  1700.             }
  1701.         }
  1702.        
  1703.         if(erroreConnessioneClient){
  1704.             // forzo esito errore connessione client
  1705.             try{
  1706.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_CONNESSIONE_CLIENT_NON_DISPONIBILE);
  1707.             }catch(Exception eBuildError){
  1708.                 esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1709.             }
  1710.         }
  1711.         else if(erroreResponseTimeout){
  1712.             // forzo esito errore response timeout
  1713.             try{
  1714.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_RESPONSE_TIMEOUT);
  1715.             }catch(Exception eBuildError){
  1716.                 esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1717.             }
  1718.         }
  1719.         else if(erroreResponsePayloadTooLarge){
  1720.             // forzo esito errore dovuto alla policy di rate limiting
  1721.             try{
  1722.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.CONTROLLO_TRAFFICO_POLICY_VIOLATA);
  1723.             }catch(Exception eBuildError){
  1724.                 esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1725.             }
  1726.         }
  1727.         else if(EsitoTransazioneName.OK.equals(esito.getName()) && context!=null && context.getPddContext()!=null && context.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.EMESSI_DIAGNOSTICI_ERRORE)) {
  1728.             // caso di errore generato durante il tracciamento dopo aver calcolato l'esito, in cui non viene sollevata una eccezione
  1729.             esito = ServicesUtils.updateEsitoConAnomalie(esito, logCore, protocolFactory);
  1730.         }
  1731.        
  1732.        
  1733.        
  1734.        
  1735.        
  1736.        
  1737.         // *** Chiudo connessione verso PdD Destinazione per casi stateless ***
  1738.         String location = "...";
  1739.         try{
  1740.             IConnettore c = null;
  1741.             if(context!=null && context.getPddContext()!=null && context.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) {
  1742.                 idTransazione = (String)context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  1743.             }
  1744.             if(idTransazione!=null) {
  1745.             //if(context.getIdMessage()!=null){
  1746.                 c = RepositoryConnettori.removeConnettorePD(
  1747.                         //context.getIdMessage()
  1748.                         idTransazione
  1749.                         );
  1750.             }
  1751.             if(c!=null){
  1752.                 location = c.getLocation();
  1753.                 c.disconnect();
  1754.             }
  1755.         }catch(Exception e){
  1756.             msgDiag.logDisconnectError(e, location);
  1757.         }
  1758.        
  1759.        

  1760.        
  1761.        
  1762.        
  1763.        
  1764.        
  1765.        
  1766.        
  1767.         /* ------------  PostOutResponseHandler ------------- */
  1768.        
  1769.         if(postOutResponseContext!=null){
  1770.             try {
  1771.                 updateContext(context, postOutResponseContext,
  1772.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1773.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1774.                         esito, statoServletResponse,
  1775.                         idModulo, req, requestMessage,
  1776.                         responseMessage, erroreConsegnaRisposta, responseMessageError);
  1777.                 postOutResponseContext.setTransazioneDaAggiornare(transazioneDaAggiornare);
  1778.             }catch(Exception e){
  1779.                 msgDiag.logErroreGenerico(e,"postOutResponse, preparazione contesto");
  1780.             }

  1781.             GestoreHandlers.postOutResponse(postOutResponseContext, msgDiag, logCore);
  1782.         }
  1783.        
  1784.        
  1785.        
  1786.        
  1787.        
  1788.        
  1789.        
  1790.        
  1791.        
  1792.        
  1793.         // *** Rilascio risorse NotifierInputStream ***
  1794.        
  1795.         // request
  1796.         try{
  1797.             if(requestMessage!=null && requestMessage.getNotifierInputStream()!=null){
  1798.                 requestMessage.getNotifierInputStream().close();
  1799.             }
  1800.         }catch(Exception e){
  1801.             msgDiag.logErroreGenerico(e,"Rilascio risorse NotifierInputStream richiesta");
  1802.         }
  1803.        
  1804.         // response
  1805.         try{
  1806.             if(responseMessage!=null && responseMessage.getNotifierInputStream()!=null){
  1807.                 responseMessage.getNotifierInputStream().close();
  1808.             }
  1809.         }catch(Exception e){
  1810.             msgDiag.logErroreGenerico(e,"Rilascio risorse NotifierInputStream risposta");
  1811.         }
  1812.        
  1813.        
  1814.        
  1815.        
  1816.        
  1817.        
  1818.        
  1819.        
  1820.        
  1821.         // *** GB ***
  1822.         requestMessage = null;
  1823.         responseMessage = null;
  1824.         responseMessageError = null;
  1825.         // *** GB ***
  1826.        
  1827.         return;

  1828.     }
  1829.    
  1830.    
  1831.     private void updateContext(RicezioneContenutiApplicativiContext context, PostOutResponseContext postOutResponseContext,
  1832.             Date dataAccettazioneRichiesta, Date dataIngressoRichiesta,
  1833.             Date dataPrimaSpedizioneRisposta, Date dataRispostaSpedita,
  1834.             EsitoTransazione esito, int statoServletResponse,
  1835.             String idModulo, ConnectorInMessage req, OpenSPCoop2Message requestMessage,
  1836.             OpenSPCoop2Message responseMessage, Throwable erroreConsegnaRisposta, OpenSPCoop2Message responseMessageError) throws ConnectorException {
  1837.         if(postOutResponseContext!=null){
  1838.             postOutResponseContext.getPddContext().addObject(CostantiPdD.DATA_ACCETTAZIONE_RICHIESTA, dataAccettazioneRichiesta);
  1839.             if(dataIngressoRichiesta!=null){
  1840.                 postOutResponseContext.getPddContext().addObject(CostantiPdD.DATA_INGRESSO_RICHIESTA, dataIngressoRichiesta);
  1841.             }
  1842.             postOutResponseContext.setDataElaborazioneMessaggio(DateManager.getDate());
  1843.             postOutResponseContext.setDataPrimaSpedizioneRisposta(dataPrimaSpedizioneRisposta);
  1844.             postOutResponseContext.setDataRispostaSpedita(dataRispostaSpedita);
  1845.             postOutResponseContext.setEsito(esito);
  1846.             postOutResponseContext.setReturnCode(statoServletResponse);
  1847.             postOutResponseContext.setResponseHeaders(context.getResponseHeaders());
  1848.             postOutResponseContext.setProtocollo(context.getProtocol());
  1849.             postOutResponseContext.setIntegrazione(context.getIntegrazione());
  1850.             if(context.getTipoPorta()!=null)
  1851.                 postOutResponseContext.setTipoPorta(context.getTipoPorta());    
  1852.             postOutResponseContext.setIdModulo(idModulo);
  1853.            
  1854.             if(requestMessage!=null){
  1855.                 long incomingRequestMessageContentLength = requestMessage.getIncomingMessageContentLength();
  1856.                 long outgoingRequestMessageContentLenght = requestMessage.getOutgoingMessageContentLength();
  1857.                 if(incomingRequestMessageContentLength<0){
  1858.                     int cl = req.getContentLength();
  1859.                     if(cl>0){
  1860.                         /**System.out.println("HTTP");*/
  1861.                         incomingRequestMessageContentLength = cl + 0l;
  1862.                     }
  1863.                     else{
  1864.                         /**System.out.println("FLUSH");*/
  1865.                         // forzo la lettura del messaggio per impostare la dimensione della richiesta
  1866.                         try{
  1867.                             requestMessage.writeTo(NullOutputStream.INSTANCE, true);
  1868.                         }catch(Exception eFlush){
  1869.                             // ignore
  1870.                         }
  1871.                         incomingRequestMessageContentLength = requestMessage.getIncomingMessageContentLength();
  1872.                     }
  1873.                 }
  1874.                 postOutResponseContext.setInputRequestMessageSize(incomingRequestMessageContentLength);
  1875.                 postOutResponseContext.setOutputRequestMessageSize(outgoingRequestMessageContentLenght);
  1876.             }else{
  1877.                 postOutResponseContext.setInputRequestMessageSize(req.getContentLength()+0l);
  1878.             }
  1879.            
  1880.             if(erroreConsegnaRisposta!=null){
  1881.                 if(responseMessageError!=null){
  1882.                     postOutResponseContext.setInputResponseMessageSize(responseMessageError.getIncomingMessageContentLength());
  1883.                     postOutResponseContext.setOutputResponseMessageSize(responseMessageError.getOutgoingMessageContentLength());
  1884.                     postOutResponseContext.setMessaggio(responseMessageError);
  1885.                 }else{
  1886.                     if(responseMessage!=null && !responseMessage.isForcedEmptyResponse() && responseMessage.getForcedResponse()==null){
  1887.                         postOutResponseContext.setInputResponseMessageSize(responseMessage.getIncomingMessageContentLength());
  1888.                         postOutResponseContext.setOutputResponseMessageSize(responseMessage.getOutgoingMessageContentLength());
  1889.                         postOutResponseContext.setMessaggio(responseMessage);
  1890.                     }
  1891.                 }
  1892.                 postOutResponseContext.setErroreConsegna(erroreConsegnaRisposta.toString()); // NOTA: lasciare e.toString()
  1893.             }
  1894.             else if(responseMessage!=null && !responseMessage.isForcedEmptyResponse() && responseMessage.getForcedResponse()==null){
  1895.                 postOutResponseContext.setInputResponseMessageSize(responseMessage.getIncomingMessageContentLength());
  1896.                 postOutResponseContext.setOutputResponseMessageSize(responseMessage.getOutgoingMessageContentLength());
  1897.                 postOutResponseContext.setMessaggio(responseMessage);
  1898.             }
  1899.             else if(responseMessage!=null && responseMessage.getForcedResponse()!=null &&
  1900.                     responseMessage.getForcedResponse().getContent()!=null) {
  1901.                 postOutResponseContext.setInputResponseMessageSize(responseMessage.getIncomingMessageContentLength());
  1902.                 postOutResponseContext.setOutputResponseMessageSize((long) responseMessage.getForcedResponse().getContent().length);
  1903.             }                  
  1904.         }
  1905.     }

  1906.     private Transazione registraTracciaOutResponse(RicezioneContenutiApplicativiContext context, PostOutResponseContext postOutResponseContext,
  1907.             Date dataAccettazioneRichiesta, Date dataIngressoRichiesta,
  1908.             Date dataPrimaSpedizioneRisposta, Date dataRispostaSpedita,
  1909.             EsitoTransazione esito, int statoServletResponse,
  1910.             String idModulo, ConnectorInMessage req, OpenSPCoop2Message requestMessage,
  1911.             OpenSPCoop2Message responseMessage, Throwable erroreConsegnaRisposta, OpenSPCoop2Message responseMessageError,
  1912.             MsgDiagnostico msgDiag) throws HandlerException {

  1913.         try {
  1914.        
  1915.             if(postOutResponseContext!=null) {
  1916.                 updateContext(context, postOutResponseContext,
  1917.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1918.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1919.                         esito, statoServletResponse,
  1920.                         idModulo, req, requestMessage,
  1921.                         responseMessage, erroreConsegnaRisposta, responseMessageError);
  1922.                
  1923.                 TracciamentoManager tracciamentoManager = new TracciamentoManager(FaseTracciamento.OUT_RESPONSE);
  1924.                 if(!tracciamentoManager.isTransazioniEnabled()) {
  1925.                     return null;
  1926.                 }
  1927.                
  1928.                 InformazioniTransazione info = new InformazioniTransazione(postOutResponseContext);
  1929.                
  1930.                 tracciamentoManager.invoke(info, postOutResponseContext.getEsito(), context.getResponseHeaders(), msgDiag);
  1931.                
  1932.                 return info.getTransazioneDaAggiornare();
  1933.             }
  1934.            
  1935.         }catch(Exception e) {
  1936.             ServicesUtils.processTrackingException(e, postOutResponseContext.getLogCore(), FaseTracciamento.OUT_RESPONSE, context.getPddContext());
  1937.         }
  1938.        
  1939.         return null;
  1940.     }
  1941.    
  1942.     private void registraTracciaInRequest(RicezioneContenutiApplicativiContext context,
  1943.             IProtocolFactory<?> protocolFactory, Logger log, MsgDiagnostico msgDiag) throws HandlerException {

  1944.         try {
  1945.             TracciamentoManager tracciamentoManager = new TracciamentoManager(FaseTracciamento.IN_REQUEST);
  1946.             if(!tracciamentoManager.isTransazioniEnabled()) {
  1947.                 return;
  1948.             }
  1949.                
  1950.             InformazioniTransazione info = new InformazioniTransazione();
  1951.             info.setContext(context.getPddContext());
  1952.             info.setTipoPorta(context.getTipoPorta());
  1953.             info.setProtocolFactory(protocolFactory);
  1954.             info.setProtocollo(context.getProtocol());
  1955.             info.setIntegrazione(context.getIntegrazione());
  1956.             info.setIdModulo(context.getIdModulo());
  1957.            
  1958.             TransportRequestContext transportRequestContext = null;
  1959.             if(context.getMessageRequest()!=null) {
  1960.                 transportRequestContext = context.getMessageRequest().getTransportRequestContext();
  1961.             }
  1962.             String esitoContext = EsitoBuilder.getTipoContext(transportRequestContext, EsitiProperties.getInstance(log, protocolFactory), log);
  1963.            
  1964.             tracciamentoManager.invoke(info, esitoContext, msgDiag);
  1965.         }catch(Exception e) {
  1966.             ServicesUtils.processTrackingException(e, log, FaseTracciamento.IN_REQUEST, context.getPddContext());
  1967.         }
  1968.        
  1969.     }
  1970. }