RicezioneBusteService.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.PortaApplicativa;
  32. import org.openspcoop2.core.constants.TipoPdD;
  33. import org.openspcoop2.core.constants.TransferLengthModes;
  34. import org.openspcoop2.core.id.IDPortaApplicativa;
  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.dynamic.DynamicMapBuilderUtils;
  60. import org.openspcoop2.pdd.core.handlers.GestoreHandlers;
  61. import org.openspcoop2.pdd.core.handlers.HandlerException;
  62. import org.openspcoop2.pdd.core.handlers.PostOutResponseContext;
  63. import org.openspcoop2.pdd.core.handlers.PreInAcceptRequestContext;
  64. import org.openspcoop2.pdd.core.handlers.PreInRequestContext;
  65. import org.openspcoop2.pdd.core.transazioni.TransactionContext;
  66. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  67. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  68. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  69. import org.openspcoop2.pdd.logger.transazioni.ConfigurazioneTracciamento;
  70. import org.openspcoop2.pdd.logger.transazioni.InformazioniTransazione;
  71. import org.openspcoop2.pdd.logger.transazioni.TracciamentoManager;
  72. import org.openspcoop2.pdd.services.DirectVMProtocolInfo;
  73. import org.openspcoop2.pdd.services.DumpRaw;
  74. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  75. import org.openspcoop2.pdd.services.ServicesUtils;
  76. import org.openspcoop2.pdd.services.connector.ConnectorDispatcherErrorInfo;
  77. import org.openspcoop2.pdd.services.connector.ConnectorDispatcherInfo;
  78. import org.openspcoop2.pdd.services.connector.ConnectorDispatcherUtils;
  79. import org.openspcoop2.pdd.services.connector.ConnectorException;
  80. import org.openspcoop2.pdd.services.connector.RicezioneBusteConnector;
  81. import org.openspcoop2.pdd.services.connector.messages.ConnectorInMessage;
  82. import org.openspcoop2.pdd.services.connector.messages.ConnectorOutMessage;
  83. import org.openspcoop2.pdd.services.connector.messages.DirectVMConnectorInMessage;
  84. import org.openspcoop2.pdd.services.connector.messages.DirectVMConnectorOutMessage;
  85. import org.openspcoop2.pdd.services.connector.messages.DumpRawConnectorInMessage;
  86. import org.openspcoop2.pdd.services.connector.messages.DumpRawConnectorOutMessage;
  87. import org.openspcoop2.pdd.services.core.RicezioneBuste;
  88. import org.openspcoop2.pdd.services.core.RicezioneBusteContext;
  89. import org.openspcoop2.pdd.services.error.RicezioneBusteExternalErrorGenerator;
  90. import org.openspcoop2.protocol.basic.builder.EsitoBuilder;
  91. import org.openspcoop2.protocol.basic.registry.ServiceIdentificationReader;
  92. import org.openspcoop2.protocol.engine.SecurityTokenUtilities;
  93. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  94. import org.openspcoop2.protocol.sdk.builder.EsitoTransazione;
  95. import org.openspcoop2.protocol.sdk.builder.InformazioniErroriInfrastrutturali;
  96. import org.openspcoop2.protocol.sdk.builder.ProprietaErroreApplicativo;
  97. import org.openspcoop2.protocol.sdk.constants.CodiceErroreIntegrazione;
  98. import org.openspcoop2.protocol.sdk.constants.ErroreIntegrazione;
  99. import org.openspcoop2.protocol.sdk.constants.ErroriIntegrazione;
  100. import org.openspcoop2.protocol.sdk.constants.EsitoTransazioneName;
  101. import org.openspcoop2.protocol.sdk.constants.IDService;
  102. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  103. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  104. import org.openspcoop2.protocol.sdk.state.URLProtocolContext;
  105. import org.openspcoop2.protocol.utils.EsitiProperties;
  106. import org.openspcoop2.utils.LimitExceededIOException;
  107. import org.openspcoop2.utils.LimitedInputStream;
  108. import org.openspcoop2.utils.LoggerWrapperFactory;
  109. import org.openspcoop2.utils.TimeoutIOException;
  110. import org.openspcoop2.utils.TimeoutInputStream;
  111. import org.openspcoop2.utils.Utilities;
  112. import org.openspcoop2.utils.date.DateManager;
  113. import org.openspcoop2.utils.io.DumpByteArrayOutputStream;
  114. import org.openspcoop2.utils.io.notifier.NotifierInputStreamParams;
  115. import org.openspcoop2.utils.transport.TransportRequestContext;
  116. import org.openspcoop2.utils.transport.http.HttpConstants;
  117. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  118. import org.slf4j.Logger;


  119. /**
  120.  * Contiene la definizione di una servlet 'RicezioneBusteDirect'
  121.  * Si occupa di creare il Messaggio, applicare la logica degli handlers
  122.  * e passare il messaggio ad OpenSPCoop per lo sbustamento e consegna.
  123.  *
  124.  * @author Poli Andrea (apoli@link.it)
  125.  * @author Lorenzo Nardi (nardi@link.it)
  126.  * @author $Author$
  127.  * @version $Rev$, $Date$
  128.  */

  129. public class RicezioneBusteService  {

  130.     private RicezioneBusteExternalErrorGenerator generatoreErrore;
  131.    
  132.     public RicezioneBusteService(RicezioneBusteExternalErrorGenerator generatoreErrore){
  133.         this.generatoreErrore = generatoreErrore;
  134.     }
  135.    

  136.     public void process(ConnectorInMessage req, ConnectorOutMessage res, Date dataAccettazioneRichiesta) throws ConnectorException {
  137.        
  138.         // Timestamp
  139.         Date dataIngressoRichiesta = null;
  140.        
  141.         // IDModulo
  142.         String idModulo = req.getIdModulo();
  143.         IDService idModuloAsService = req.getIdModuloAsIDService();
  144.         RequestInfo requestInfo = req.getRequestInfo();
  145.        
  146.         // Log
  147.         Logger logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  148.         if(logCore==null)
  149.             logCore = LoggerWrapperFactory.getLogger(idModulo);
  150.        
  151.         OpenSPCoop2Properties openSPCoopProperties = OpenSPCoop2Properties.getInstance();
  152.        
  153.        
  154.         /* ------------  PreInHandler (PreInAcceptRequestContext) ------------- */
  155.        
  156.         PreInAcceptRequestContext preInAcceptRequestContext = null;
  157.         if (openSPCoopProperties != null && OpenSPCoop2Startup.initialize) {
  158.             // build context
  159.             preInAcceptRequestContext = new PreInAcceptRequestContext();
  160.             preInAcceptRequestContext.setTipoPorta(TipoPdD.APPLICATIVA);
  161.             preInAcceptRequestContext.setIdModulo(idModulo);
  162.             preInAcceptRequestContext.setRequestInfo(requestInfo);  
  163.             preInAcceptRequestContext.setLogCore(logCore);
  164.            
  165.             // valori che verranno aggiornati dopo
  166.             try {
  167.                 if(openSPCoopProperties.isConnettoriUseLimitedInputStream()) {
  168.                     SogliaDimensioneMessaggio soglia = new SogliaDimensioneMessaggio();
  169.                     soglia.setSogliaKb(openSPCoopProperties.getLimitedInputStreamThresholdKb());
  170.                     soglia.setUseContentLengthHeader(openSPCoopProperties.isLimitedInputStreamUseContentLength());
  171.                     soglia.setUseContentLengthHeaderAcceptZeroValue(openSPCoopProperties.isLimitedInputStreamUseContentLengthAcceptZeroValue());
  172.                     soglia.setPolicyGlobale(true);
  173.                     soglia.setNomePolicy("GovWayCore");
  174.                     soglia.setIdPolicyConGruppo("GovWayCore");
  175.                     req.setRequestLimitedStream(soglia);
  176.                 }
  177.                 if(openSPCoopProperties.isConnettoriUseTimeoutInputStream()) {
  178.                     SogliaReadTimeout soglia = new SogliaReadTimeout();
  179.                     soglia.setSogliaMs(openSPCoopProperties.getReadConnectionTimeout_ricezioneBuste());
  180.                     soglia.setConfigurazioneGlobale(true);
  181.                     soglia.setIdConfigurazione("GovWayCore");
  182.                     req.setRequestReadTimeout(soglia);
  183.                 }
  184.                 req.setThresholdContext(null,
  185.                     openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  186.             }catch(Throwable t) {
  187.                 logCore.error(t.getMessage(),t);
  188.             }
  189.             preInAcceptRequestContext.setReq(req);
  190.            
  191.             // invocazione handler
  192.             GestoreHandlers.preInRequest(preInAcceptRequestContext, logCore, logCore);
  193.         }
  194.        
  195.        
  196.        
  197.        
  198.         // GeneratoreErrore
  199.         try{
  200.             if(this.generatoreErrore==null){
  201.                 this.generatoreErrore =
  202.                         new RicezioneBusteExternalErrorGenerator(logCore, RicezioneBusteConnector.ID_MODULO, requestInfo, null);
  203.             }
  204.         }catch(Exception e){
  205.             String msg = "Inizializzazione Generatore Errore fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  206.             logCore.error(msg,e);
  207.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore, // il metodo doError gestisce il generatoreErrore a null
  208.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  209.                     get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  210.                     IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  211.             RicezioneBusteServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  212.             return;
  213.         }
  214.        
  215.         //  Proprieta' OpenSPCoop
  216.         if (!OpenSPCoop2Startup.initialize || openSPCoopProperties == null) {
  217.             String msg = "Inizializzazione di GovWay non correttamente effettuata: OpenSPCoopProperties";
  218.             if(!OpenSPCoop2Startup.initialize) {
  219.                 msg = "Inizializzazione di GovWay non correttamente effettuata";
  220.             }
  221.             logCore.error(msg);
  222.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  223.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  224.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  225.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, null, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  226.             RicezioneBusteServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  227.             return;
  228.         }
  229.        
  230.         // Configurazione Reader
  231.         ConfigurazionePdDManager configPdDManager = null;
  232.         try{
  233.             configPdDManager = ConfigurazionePdDManager.getInstance();
  234.             if(configPdDManager==null || configPdDManager.isInitializedConfigurazionePdDReader()==false){
  235.                 throw new Exception("ConfigurazionePdDManager not initialized");
  236.             }
  237.         }catch(Throwable e){
  238.             String msg = "Inizializzazione di GovWay non correttamente effettuata: ConfigurazionePdDManager";
  239.             logCore.error(msg);
  240.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  241.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  242.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  243.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  244.             RicezioneBusteServiceUtils.emitTransaction(logCore, req, null, dataAccettazioneRichiesta, cInfo);
  245.             return;
  246.         }
  247.        
  248.         // PddContext from servlet
  249.         Object oPddContextFromServlet = req.getAttribute(CostantiPdD.OPENSPCOOP2_PDD_CONTEXT_HEADER_HTTP.getValue());
  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.             RicezioneBusteServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  275.             return;
  276.         }
  277.        
  278.         // Provo a creare un context (per l'id di transazione nei diagnostici)
  279.         RicezioneBusteContext context = null;
  280.         IProtocolFactory<?> protocolFactory = null;
  281.         String idTransazione = null;
  282.         try {
  283.             context = new RicezioneBusteContext(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.         try{
  292.             GestoreRichieste.readRequestConfig(requestInfo);
  293.         }catch(Exception e){
  294.             String msg = "GestoreRichieste readRequestConfig fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  295.             logCore.error(msg,e);
  296.             ConnectorDispatcherErrorInfo cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  297.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  298.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_500_ERRORE_INTERNO),
  299.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  300.             RicezioneBusteServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  301.             return;
  302.         }
  303.            
  304.         if(idTransazione!=null) {
  305.             try {
  306.                 if(openSPCoopProperties.isTransazioniEnabled()) {
  307.                     TransactionContext.createTransaction(idTransazione, "RicezioneBuste.1");
  308.                 }
  309.                 requestInfo.setIdTransazione(idTransazione);
  310.                 this.generatoreErrore.getImbustamentoErrore().setIdTransazione(idTransazione);
  311.                
  312.                 req.setThresholdContext((context!=null ? context.getPddContext(): null),
  313.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  314.             }catch(Throwable e) {
  315.                 context = null;
  316.                 protocolFactory = null;
  317.                 // non loggo l'errore tanto poi provo a ricreare il context subito dopo e li verra' registrato l'errore
  318.             }
  319.         }
  320.                
  321.         // Logger dei messaggi diagnostici
  322.         String nomePorta = requestInfo.getProtocolContext().getInterfaceName();
  323.         MsgDiagnostico msgDiag = MsgDiagnostico.newInstance(TipoPdD.APPLICATIVA,idModulo,nomePorta,requestInfo);
  324.         msgDiag.setPrefixMsgPersonalizzati(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE);
  325.         if(context!=null && protocolFactory!=null) {
  326.             msgDiag.setPddContext(context.getPddContext(), protocolFactory);
  327.         }
  328.        
  329.         try{
  330.             msgDiag.logPersonalizzato("ricezioneRichiesta.firstLog");
  331.         }catch(Exception e){
  332.             logCore.error("Errore generazione diagnostico di ingresso",e);
  333.         }
  334.        
  335.         try{
  336.             req.setDiagnosticProducer(context!=null ? context.getPddContext(): null, msgDiag);
  337.         }catch(Throwable e){
  338.             logCore.error("Errore registrazione diagnostico sulla richiesta",e);
  339.         }
  340.        
  341.         // emitDiagnostic preAccept handler
  342.         GestoreHandlers.emitDiagnostic(msgDiag, preInAcceptRequestContext, context!=null ? context.getPddContext() : null,
  343.                 logCore, logCore);
  344.        
  345.         // Aggiorno RequestInfo
  346.         try{
  347.             msgDiag.mediumDebug("Accesso configurazione della richiesta in corso...");
  348.         }catch(Exception e){
  349.             logCore.error("Errore generazione diagnostico",e);
  350.         }
  351.         ConnectorDispatcherInfo cInfo = RicezioneBusteServiceUtils.updatePortaApplicativaRequestInfo(requestInfo, logCore, req, res,
  352.                 this.generatoreErrore, serviceIdentificationReader,msgDiag,
  353.                 context!=null ? context.getPddContext(): null);
  354.         if(cInfo!=null){
  355.             RicezioneBusteServiceUtils.emitTransaction(context, logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  356.             return; // l'errore in response viene impostato direttamente dentro il metodo
  357.         }
  358.         req.updateRequestInfo(requestInfo);
  359.        
  360.        
  361.         // Timeout 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.dumpBinarioPA();
  370.             PortaApplicativa pa = null;
  371.             if(requestInfo!=null && requestInfo.getProtocolContext()!=null && requestInfo.getProtocolContext().getInterfaceName()!=null) {
  372.                 IDPortaApplicativa idPA = new IDPortaApplicativa();
  373.                 idPA.setNome(requestInfo.getProtocolContext().getInterfaceName());
  374.                 pa = configPdDManager.getPortaApplicativaSafeMethod(idPA, requestInfo);
  375.             }
  376.            
  377.             // Limited
  378.             try{
  379.                 msgDiag.mediumDebug("Lettura configurazione dimensione massima della richiesta ...");
  380.             }catch(Exception e){
  381.                 logCore.error("Errore generazione diagnostico",e);
  382.             }
  383.             String azione = (requestInfo!=null && requestInfo.getIdServizio()!=null) ? requestInfo.getIdServizio().getAzione() : null;
  384.             SoglieDimensioneMessaggi limitedInputStream = configPdDManager.getSoglieLimitedInputStream(pa, azione, idModulo,
  385.                     (context!=null && context.getPddContext()!=null) ? context.getPddContext() : null,
  386.                     requestInfo,
  387.                     protocolFactory, logCore);
  388.             if(limitedInputStream!=null) {
  389.                 req.setRequestLimitedStream(limitedInputStream.getRichiesta());
  390.                 if(context!=null && context.getPddContext()!=null) {
  391.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.LIMITED_STREAM, limitedInputStream.getRisposta());
  392.                 }
  393.             }
  394.             else {
  395.                 if(!openSPCoopProperties.isLimitedInputStreamThresholdDefined()) {
  396.                     req.disableLimitedStream();
  397.                 }
  398.             }
  399.            
  400.             // Timeout
  401.             try{
  402.                 msgDiag.mediumDebug("Lettura configurazione timeout per la lettura della richiesta ...");
  403.             }catch(Exception e){
  404.                 logCore.error("Errore generazione diagnostico",e);
  405.             }
  406.             boolean useTimeoutInputStream = configPdDManager.isConnettoriUseTimeoutInputStream(pa);
  407.             if(useTimeoutInputStream) {
  408.                 SogliaReadTimeout timeout = configPdDManager.getRequestReadTimeout(pa,
  409.                         requestInfo,
  410.                         protocolFactory,
  411.                         context!=null ? context.getPddContext() : null,
  412.                         null);
  413.                 if(timeout!=null && timeout.getSogliaMs()>0) {
  414.                     req.setRequestReadTimeout(timeout);
  415.                 }
  416.                 else {
  417.                     req.disableReadTimeout();
  418.                 }
  419.             }
  420.             else {
  421.                 req.disableReadTimeout();
  422.             }
  423.            
  424.             // DumpRaw
  425.             try{
  426.                 msgDiag.mediumDebug("Lettura configurazione dump ...");
  427.             }catch(Exception e){
  428.                 logCore.error("Errore generazione diagnostico",e);
  429.             }
  430.             DumpConfigurazione dumpConfigurazione = configPdDManager.getDumpConfigurazione(pa);
  431.             ConfigurazioneTracciamento configurazioneTracciamento = new ConfigurazioneTracciamento(logCore, configPdDManager, pa);
  432.             boolean fileTraceHeaders = configurazioneTracciamento.isTransazioniFileTraceDumpBinarioHeaderEnabled();
  433.             boolean fileTracePayload = configurazioneTracciamento.isTransazioniFileTraceDumpBinarioPayloadEnabled();
  434.             dumpRaw = new DumpRaw(logCore, requestInfo.getIdentitaPdD(), idModulo, TipoPdD.APPLICATIVA,
  435.                     dumpBinario,
  436.                     dumpConfigurazione,
  437.                     fileTraceHeaders, fileTracePayload);
  438.             if(dumpRaw.isActiveDumpRichiesta()) {
  439.                 req = new DumpRawConnectorInMessage(logCore, req,
  440.                         (context!=null ? context.getPddContext(): null),
  441.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository());
  442.             }
  443.             if(dumpRaw.isActiveDumpRisposta()) {
  444.                 res = new DumpRawConnectorOutMessage(logCore, res,
  445.                         (context!=null ? context.getPddContext(): null),
  446.                         openSPCoopProperties.getDumpBinarioInMemoryThreshold(), openSPCoopProperties.getDumpBinarioRepository(),
  447.                         dumpRaw);
  448.             }
  449.         }catch(Throwable e){
  450.             String msg = "Inizializzazione di GovWay non correttamente effettuata: DumpRaw";
  451.             logCore.error(msg,  e);
  452.             cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  453.                     ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  454.                         get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  455.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  456.             RicezioneBusteServiceUtils.emitTransaction(logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  457.             return;
  458.         }
  459.        
  460.        
  461.         // API Soap supporta solo POST e ?wsdl
  462.         if(ServiceBinding.SOAP.equals(requestInfo.getProtocolServiceBinding())){
  463.             HttpRequestMethod method = null;
  464.             if(req!=null && req.getURLProtocolContext()!=null && req.getURLProtocolContext().getRequestType()!=null) {
  465.                 try {
  466.                     method = HttpRequestMethod.valueOf(req.getURLProtocolContext().getRequestType());
  467.                 }catch(Exception e) {
  468.                     // ignore
  469.                 }
  470.             }
  471.             if(method!=null && !HttpRequestMethod.POST.equals(method)){
  472.                 if(ServicesUtils.isRequestWsdl(req, logCore)) {
  473.                     try {
  474.                         ServicesUtils.writeWsdl(res, requestInfo, RicezioneBusteConnector.ID_SERVICE, serviceIdentificationReader, logCore);
  475.                     }catch(Exception e) {
  476.                         String msg = "Lettura wsdl fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  477.                         logCore.error(msg,e);
  478.                         cInfo = ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  479.                                 ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  480.                                 get5XX_ErroreProcessamento(msg,CodiceErroreIntegrazione.CODICE_500_ERRORE_INTERNO),
  481.                                 IntegrationFunctionError.INTERNAL_REQUEST_ERROR, e, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  482.                         // nel caso di wsdl request non emetto la transazione
  483.                         //RicezioneBusteServiceUtils.emitTransaction(context,logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfo);
  484.                     }finally {
  485.                         // FIX devo però rilasciare dalla memoria la transazione:
  486.                         if(openSPCoopProperties.isTransazioniEnabled()) {
  487.                             idTransazione = (String)context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  488.                             TransactionContext.removeTransaction(idTransazione);
  489.                         }
  490.                     }
  491.                     return;
  492.                 }
  493.                 else {
  494.                     String msg = "Metodo http '"+method+"' non supportato dall'API SOAP invocata";
  495.                     logCore.error(msg);
  496.                     ConnectorDispatcherErrorInfo cInfoError =  ConnectorDispatcherUtils.doError(requestInfo, this.generatoreErrore,
  497.                             ErroriIntegrazione.ERRORE_439_FUNZIONALITA_NOT_SUPPORTED_BY_PROTOCOL.getErrore439_FunzionalitaNotSupportedByProtocol(msg, protocolFactory),
  498.                             IntegrationFunctionError.NOT_SUPPORTED_BY_PROTOCOL, null, null, res, logCore, ConnectorDispatcherUtils.GENERAL_ERROR);
  499.                     RicezioneBusteServiceUtils.emitTransaction(context, logCore, req, pddContextFromServlet, dataAccettazioneRichiesta, cInfoError);
  500.                     return;
  501.                 }
  502.             }
  503.         }      
  504.        
  505.        
  506.        
  507.        

  508.        
  509.        
  510.        
  511.        
  512.        
  513.        
  514.        
  515.         /* ------------  Lettura parametri della richiesta ------------- */
  516.        
  517.        
  518.         //  Risposta Soap
  519.         OpenSPCoop2Message responseMessage = null;

  520.         // Proprieta errore applicativo
  521.         ProprietaErroreApplicativo proprietaErroreAppl = null;

  522.         // PostOutResponseContext
  523.         PostOutResponseContext postOutResponseContext = null;

  524.         PdDContext pddContext = null;
  525.         OpenSPCoop2Message requestMessage = null;
  526.        
  527.        
  528.         String protocol = null;
  529.         MessageType messageTypeReq = null;
  530.         ServiceBinding protocolServiceBinding = null;
  531.         try{
  532.            
  533.             /* --------------- Creo il context che genera l'id univoco ----------------------- */
  534.            
  535.             try{
  536.                 msgDiag.mediumDebug("Creazione contesto ...");
  537.             }catch(Exception e){
  538.                 logCore.error("Errore generazione diagnostico",e);
  539.             }
  540.             if(protocolFactory==null) {
  541.                 protocolFactory = req.getProtocolFactory();
  542.             }
  543.             protocol = protocolFactory.getProtocol();
  544.            
  545.             protocolServiceBinding = requestInfo.getProtocolServiceBinding();
  546.            
  547.             proprietaErroreAppl = openSPCoopProperties.getProprietaGestioneErrorePD(protocolFactory.createProtocolManager());
  548.             proprietaErroreAppl.setDominio(openSPCoopProperties.getIdentificativoPortaDefault(protocolFactory.getProtocol(), requestInfo));
  549.             proprietaErroreAppl.setIdModulo(idModulo);
  550.            
  551.             if(context==null) {
  552.                 context = new RicezioneBusteContext(idModuloAsService, dataAccettazioneRichiesta,requestInfo);
  553.             }
  554.             if(preInAcceptRequestContext!=null && preInAcceptRequestContext.getPreContext()!=null && !preInAcceptRequestContext.getPreContext().isEmpty()) {
  555.                 context.getPddContext().addAll(preInAcceptRequestContext.getPreContext(), false);
  556.             }
  557.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  558.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO, req.getRequestInfo());
  559.             RicezionePropertiesConfig rConfig = RicezioneBusteServiceUtils.readPropertiesConfig(req.getRequestInfo(), logCore,null);
  560.             if(rConfig!=null) {
  561.                 if (rConfig.getApiImplementation() != null && !rConfig.getApiImplementation().isEmpty()) {
  562.                    context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_CONFIGURAZIONE, rConfig.getApiImplementation());
  563.                 }
  564.                 if (rConfig.getSoggettoErogatore() != null && !rConfig.getSoggettoErogatore().isEmpty()) {
  565.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_EROGATORE, rConfig.getSoggettoErogatore());
  566.                 }
  567.             }
  568.             context.setTipoPorta(TipoPdD.APPLICATIVA);
  569.             context.setIdModulo(idModulo);
  570.             msgDiag.setPddContext(context.getPddContext(), protocolFactory);
  571.             pddContext = context.getPddContext();
  572.             DynamicMapBuilderUtils.injectDynamicMap(null, requestInfo, pddContext, logCore); // per le funzioni di generazione risposta errore
  573.                        
  574.             try{
  575.                 if(openSPCoopProperties.isTransazioniEnabled()) {
  576.                     // NOTA: se gia' esiste con l'id di transazione, non viene ricreata
  577.                     TransactionContext.createTransaction((String)pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE), "RicezioneBuste.2");
  578.                 }
  579.             }catch(Exception e){
  580.                 logCore.error("Errore durante la creazione della transazione",e);
  581.             }
  582.            
  583.             try{
  584.                 msgDiag.logPersonalizzato("ricezioneRichiesta.firstAccessRequestStream");
  585.             }catch(Exception e){
  586.                 logCore.error("Errore generazione diagnostico di ingresso (stream access)",e);
  587.             }
  588.            
  589.             if(dumpRaw!=null && dumpRaw.isActiveDump()){
  590.                 dumpRaw.setPddContext(msgDiag.getPorta(), context.getPddContext());
  591.                 dumpRaw.serializeContext(context, protocol);
  592.             }
  593.            
  594.             DirectVMConnectorInMessage vm = null;
  595.             if(req instanceof DirectVMConnectorInMessage){
  596.                 vm = (DirectVMConnectorInMessage) req;
  597.             }
  598.             else if(req instanceof DumpRawConnectorInMessage){
  599.                 if( ((DumpRawConnectorInMessage)req).getWrappedConnectorInMessage() instanceof DirectVMConnectorInMessage ){
  600.                     vm = (DirectVMConnectorInMessage) ((DumpRawConnectorInMessage)req).getWrappedConnectorInMessage();
  601.                 }
  602.             }
  603.             if(vm!=null && vm.getDirectVMProtocolInfo()!=null){
  604.                 vm.getDirectVMProtocolInfo().setInfo(pddContext);
  605.             }
  606.            
  607.            
  608.            
  609.            
  610.            
  611.             /* ------------  PostOutResponseContext ------------- */
  612.             postOutResponseContext = new PostOutResponseContext(logCore, protocolFactory);
  613.             postOutResponseContext.setTipoPorta(TipoPdD.APPLICATIVA);
  614.             postOutResponseContext.setPddContext(pddContext);
  615.             postOutResponseContext.setIdModulo(idModulo);
  616.            
  617.            
  618.            
  619.                    
  620.             /* ------------  PreInHandler ------------- */
  621.            
  622.             // build context
  623.             PreInRequestContext preInRequestContext = new PreInRequestContext(pddContext);
  624.             if(pddContextFromServlet!=null){
  625.                 preInRequestContext.getPddContext().addAll(pddContextFromServlet, true);
  626.             }
  627.             preInRequestContext.setTipoPorta(TipoPdD.APPLICATIVA);
  628.             preInRequestContext.setIdModulo(idModulo);
  629.             preInRequestContext.setProtocolFactory(protocolFactory);
  630.             preInRequestContext.setRequestInfo(requestInfo);
  631.             Map<String, Object> transportContext = new HashMap<>();
  632.             transportContext.put(PreInRequestContext.SERVLET_REQUEST, req);
  633.             transportContext.put(PreInRequestContext.SERVLET_RESPONSE, res);
  634.             preInRequestContext.setTransportContext(transportContext);  
  635.             preInRequestContext.setLogCore(logCore);
  636.                        
  637.             // invocazione handler
  638.             GestoreHandlers.preInRequest(preInRequestContext, msgDiag, logCore);
  639.            
  640.             // aggiungo eventuali info inserite nel preInHandler
  641.             pddContext.addAll(preInRequestContext.getPddContext(), false);
  642.            
  643.             // Lettura risposta parametri NotifierInputStream
  644.             NotifierInputStreamParams notifierInputStreamParams = preInRequestContext.getNotifierInputStreamParams();
  645.             context.setNotifierInputStreamParams(notifierInputStreamParams);
  646.            
  647.             // Controllo Content Length se attiva una policy di rate limiting
  648.             req.checkContentLengthLimit();
  649.            
  650.             // Lettura richiesta con il dump
  651.             if(dumpRaw!=null && dumpRaw.isActiveDumpRichiesta()){
  652.                 dumpRaw.serializeRequest(((DumpRawConnectorInMessage)req), true, notifierInputStreamParams);
  653.                 dataIngressoRichiesta = req.getDataIngressoRichiesta();
  654.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  655.             }
  656.            
  657.            

  658.            
  659.            
  660.            
  661.            
  662.            
  663.             /* ------------ Controllo ContentType -------------------- */
  664.            
  665.             msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.tipologiaMessaggio");
  666.            
  667.             messageTypeReq = requestInfo.getProtocolRequestMessageType();
  668.             if(ServiceBinding.SOAP.equals(protocolServiceBinding) && messageTypeReq!=null){
  669.                 msgDiag.addKeyword(CostantiPdD.KEY_SOAP_VERSION, messageTypeReq.getMessageVersionAsString());
  670.                 msgDiag.addKeyword(CostantiPdD.KEY_SOAP_ENVELOPE_NAMESPACE_ATTESO, SoapUtils.getSoapEnvelopeNS(messageTypeReq));
  671.             }
  672.            
  673.             String contentTypeReq = req.getContentType();
  674.             boolean contentTypeSupportato = messageTypeReq!=null;
  675.             msgDiag.addKeyword(CostantiPdD.KEY_CONTENT_TYPES_ATTESI,
  676.                     requestInfo.getBindingConfig().getContentTypesSupportedAsString(protocolServiceBinding,
  677.                             MessageRole.REQUEST,requestInfo.getProtocolContext()));
  678.             List<String> supportedContentTypes = requestInfo.getBindingConfig().getContentTypesSupported(protocolServiceBinding,
  679.                     MessageRole.REQUEST,requestInfo.getProtocolContext());
  680.             msgDiag.addKeyword(CostantiPdD.KEY_HTTP_HEADER, contentTypeReq);
  681.            
  682.             if(ServiceBinding.SOAP.equals(protocolServiceBinding)){
  683.                 if(openSPCoopProperties.isControlloContentTypeAbilitatoRicezioneBuste() == false){
  684.                     if(!contentTypeSupportato){
  685.                         if(HttpConstants.CONTENT_TYPE_NON_PRESENTE.equals(contentTypeReq)){
  686.                             msgDiag.logPersonalizzato("contentType.notDefined");
  687.                         }else{
  688.                             msgDiag.logPersonalizzato("contentType.unsupported");
  689.                         }
  690.                         messageTypeReq = MessageType.SOAP_11;
  691.                         contentTypeReq = SoapUtils.getSoapContentTypeForMessageWithoutAttachments(messageTypeReq); // Forzo text/xml;
  692.                         logCore.warn("Content-Type non supportato, viene utilizzato forzatamente il tipo: "+contentTypeReq);
  693.                         contentTypeSupportato = true;
  694.                     }
  695.                 }
  696.             }
  697.             if(!contentTypeSupportato){
  698.                
  699.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  700.                
  701.                 // Leggo content Type dall'header HTTP per capire se l'header proprio non esiste o se e' il valore errato.
  702.                 if(HttpConstants.CONTENT_TYPE_NON_PRESENTE.equals(contentTypeReq)){
  703.                     //ContentType del messaggio non presente
  704.                     msgDiag.logPersonalizzato("contentType.notDefined");
  705.                     responseMessage = this.generatoreErrore.buildErroreProcessamento(pddContext, IntegrationFunctionError.CONTENT_TYPE_NOT_PROVIDED,
  706.                             ErroriIntegrazione.ERRORE_433_CONTENT_TYPE_NON_PRESENTE.getErrore433_ContentTypeNonPresente(supportedContentTypes));    
  707.                 }  
  708.                 else{
  709.                     //ContentType del messaggio non supportato
  710.                     msgDiag.logPersonalizzato("contentType.unsupported");
  711.                     responseMessage = this.generatoreErrore.buildErroreProcessamento(pddContext, IntegrationFunctionError.CONTENT_TYPE_NOT_SUPPORTED,
  712.                             ErroriIntegrazione.ERRORE_429_CONTENT_TYPE_NON_SUPPORTATO.getErrore429_ContentTypeNonSupportato(contentTypeReq,supportedContentTypes));
  713.                 }
  714.             }
  715.             else{
  716.                 /* ------------ Check Charset ------------- */
  717.                 try {
  718.                     boolean checkEnabled = false;
  719.                     List<String> ctDefault = null;
  720.                     if(ServiceBinding.SOAP.equals(protocolServiceBinding)){
  721.                         if(openSPCoopProperties.isControlloCharsetContentTypeAbilitatoRicezioneBusteSoap()) {
  722.                             checkEnabled = true;
  723.                             ctDefault = openSPCoopProperties.getControlloCharsetContentTypeAbilitatoRicezioneBusteSoap();
  724.                         }
  725.                     }
  726.                     else {
  727.                         if(openSPCoopProperties.isControlloCharsetContentTypeAbilitatoRicezioneBusteRest()) {
  728.                             checkEnabled = true;
  729.                             ctDefault = openSPCoopProperties.getControlloCharsetContentTypeAbilitatoRicezioneBusteRest();
  730.                         }
  731.                     }
  732.                     if(checkEnabled) {
  733.                         ServicesUtils.checkCharset(contentTypeReq, ctDefault, msgDiag, true, TipoPdD.APPLICATIVA);
  734.                     }
  735.                    
  736.                 }catch(Throwable t) {
  737.                     logCore.error("Avvenuto errore durante il controllo del charset della richiesta: "+t.getMessage(),t);
  738.                 }
  739.                                
  740.                 /* ------------  SoapAction check 1 (controlla che non sia null e ne ritorna il valore) ------------- */            
  741.                 String soapAction = null;
  742.                 try{
  743.                     if(ServiceBinding.SOAP.equals(protocolServiceBinding)){
  744.                         soapAction = req.getSOAPAction();
  745.                     }
  746.                 }catch(Exception e){
  747.                     if(dataIngressoRichiesta==null) {
  748.                         dataIngressoRichiesta=DateManager.getDate();
  749.                     }
  750.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  751.                     throw e;
  752.                 }
  753.                
  754.                 /* ------------ Costruzione Messaggio -------------------- */
  755.                 msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.inCorso");
  756.                 Utilities.printFreeMemory("RicezioneBuste - Pre costruzione richiesta");
  757.                 OpenSPCoop2MessageParseResult pr = req.getRequest(notifierInputStreamParams);
  758.                 if(pr.getParseException()!=null){
  759.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION, pr.getParseException());
  760.                 }
  761.                 dataIngressoRichiesta = req.getDataIngressoRichiesta();
  762.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  763.                 requestMessage = pr.getMessage_throwParseException();
  764.                 Utilities.printFreeMemory("RicezioneBuste - Post costruzione richiesta");
  765.                 requestMessage.setProtocolName(protocolFactory.getProtocol());
  766.                 requestMessage.setTransactionId(PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext));
  767.                 requestMessage.addContextProperty(org.openspcoop2.core.constants.Costanti.REQUEST_INFO,requestInfo); // serve nelle comunicazione non stateless (es. riscontro salvato) per poterlo rispedire
  768.                 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
  769.                 Object nomePortaInvocataObject = context.getPddContext().getObject(CostantiPdD.NOME_PORTA_INVOCATA);
  770.                 if(nomePortaInvocataObject!=null && nomePortaInvocataObject instanceof String) {
  771.                     requestMessage.addContextProperty(CostantiPdD.NOME_PORTA_INVOCATA, (String) nomePortaInvocataObject );
  772.                 }              
  773.                            
  774.                 /* ------------ Controllo Soap namespace -------------------- */
  775.                 String soapEnvelopeNamespaceVersionMismatch = null;
  776.                 try{
  777.                     if(ServiceBinding.SOAP.equals(protocolServiceBinding)){
  778.                         soapEnvelopeNamespaceVersionMismatch = ServicesUtils.checkSOAPEnvelopeNamespace(requestMessage.castAsSoap(), messageTypeReq);
  779.                     }
  780.                 }catch(Exception e){
  781.                     pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  782.                     throw e;
  783.                 }
  784.    
  785.                 /* ------------ Controllo MustUnderstand -------------------- */
  786.                 String mustUnderstandError = null;
  787.                 if(soapEnvelopeNamespaceVersionMismatch==null) {
  788.                     try{
  789.                         if(ServiceBinding.SOAP.equals(protocolServiceBinding)){
  790.                             mustUnderstandError = ServicesUtils.checkMustUnderstand(requestMessage.castAsSoap(),protocolFactory);
  791.                         }
  792.                     }catch(Exception e){
  793.                         pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  794.                         throw e;
  795.                     }
  796.                 }
  797.                
  798.                 /* ------------  SoapAction check 2 ------------- */
  799.                 if(soapAction!=null){
  800.                     if(openSPCoopProperties.checkSoapActionQuotedString_ricezioneBuste()){
  801.                         try{
  802.                             SoapUtils.checkSoapActionQuotedString(soapAction, messageTypeReq);
  803.                         }catch(Exception e){
  804.                             pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  805.                             throw e;
  806.                         }
  807.                     }
  808.                 }

  809.                 /* --------------- SecurityToken --------------- */
  810.                 try {
  811.                     if(requestInfo!=null && requestInfo.getProtocolContext()!=null && requestInfo.getProtocolContext().getCredential()!=null &&
  812.                             requestInfo.getProtocolContext().getCredential().getCertificate()!=null &&
  813.                             requestInfo.getProtocolContext().getCredential().getCertificate().getCertificate()!=null) {
  814.                         SecurityTokenUtilities.newSecurityToken(pddContext);
  815.                     }
  816.                 }catch(Exception e){
  817.                     logCore.error("Costruzione SecurityToken non riuscito: "+e.getMessage(),e);
  818.                 }
  819.                                
  820.                 /* ------------  Elaborazione ------------- */
  821.                
  822.                 if(mustUnderstandError==null && soapEnvelopeNamespaceVersionMismatch==null){
  823.                    
  824.                     // Contesto di Richiesta
  825.                     context.setCredenziali(new Credenziali(req.getCredential()));
  826.                     context.setGestioneRisposta(true); // siamo in una servlet, la risposta deve essere aspettata
  827.                     context.setMessageRequest(requestMessage);
  828.                     context.setTracciamentoAbilitato(true);
  829.                     context.setUrlProtocolContext(requestInfo.getProtocolContext());
  830.                     context.setMsgDiagnostico(msgDiag);
  831.    
  832.                     // Log elaborazione dati completata
  833.                     msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.completata");
  834.            
  835.                     // se il tracciamento lo prevedo emetto un log
  836.                     registraTracciaInRequest(context, protocolFactory, logCore, msgDiag);
  837.                    
  838.                     // Invocazione...
  839.                     RicezioneBuste gestoreRichiesta = new RicezioneBuste(context, this.generatoreErrore);
  840.                     gestoreRichiesta.process(req);
  841.                     responseMessage = context.getMessageResponse();
  842.                 }  
  843.                 else{
  844.                     if(mustUnderstandError!=null){
  845.                         pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  846.                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, mustUnderstandError);
  847.                         msgDiag.logPersonalizzato("mustUnderstand.unknown");
  848.                         responseMessage = this.generatoreErrore.buildErroreProcessamento(pddContext, IntegrationFunctionError.SOAP_MUST_UNDERSTAND_UNKNOWN,
  849.                                 ErroriIntegrazione.ERRORE_427_MUSTUNDERSTAND_ERROR.getErrore427_MustUnderstandHeaders(mustUnderstandError));
  850.                     }
  851.                     else{
  852.                         pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  853.                         msgDiag.addKeyword(CostantiPdD.KEY_SOAP_ENVELOPE_NAMESPACE, soapEnvelopeNamespaceVersionMismatch);
  854.                         msgDiag.logPersonalizzato("soapEnvelopeNamespace.versionMismatch");
  855.                         responseMessage = this.generatoreErrore.buildErroreProcessamento(pddContext, IntegrationFunctionError.SOAP_VERSION_MISMATCH,
  856.                                 ErroriIntegrazione.ERRORE_430_SOAP_ENVELOPE_NAMESPACE_ERROR.
  857.                                     getErrore430_SoapNamespaceNonSupportato(messageTypeReq, soapEnvelopeNamespaceVersionMismatch));
  858.                     }
  859.                 }
  860.             }
  861.                
  862.         } catch (Throwable e) {
  863.            
  864.             if(context==null){
  865.                 // Errore durante la generazione dell'id
  866.                 context = RicezioneBusteContext.newRicezioneBusteContext(idModuloAsService,dataAccettazioneRichiesta,requestInfo);
  867.                 context.setDataIngressoRichiesta(dataIngressoRichiesta);
  868.                 context.setTipoPorta(TipoPdD.APPLICATIVA);
  869.                 context.setIdModulo(idModulo);
  870.                 context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  871.                 pddContext = context.getPddContext();
  872.                 msgDiag.setPddContext(pddContext,protocolFactory);
  873.                 if(postOutResponseContext!=null){
  874.                     postOutResponseContext.setPddContext(pddContext);
  875.                 }
  876.             }

  877.             // Se viene lanciata una eccezione, riguarda la richiesta, altrimenti è gestita dopo nel finally.
  878.             Throwable tParsing = null;
  879.             ParseException parseException = null;
  880.             if(pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION)){
  881.                 parseException = (ParseException) pddContext.removeObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  882.                 if(parseException!=null) {
  883.                     tParsing = parseException.getParseException();
  884.                 }
  885.             }
  886.             if(tParsing==null && (requestMessage==null || requestMessage.getParseException() == null)){
  887.                 tParsing = ParseExceptionUtils.getParseException(e);
  888.             }
  889.            
  890.             // Genero risposta con errore
  891.             String msgErrore = e.getMessage();
  892.             if(msgErrore==null){
  893.                 msgErrore = e.toString();
  894.             }
  895.                
  896.             // Ricerca org.xml.sax.SAXParseException || com.ctc.wstx.exc.WstxParsingException ||  com.ctc.wstx.exc.WstxUnexpectedCharException
  897.             if( ServiceBinding.SOAP.equals(protocolServiceBinding) &&
  898.                     messageTypeReq!=null &&
  899.                     (
  900.                    
  901.                         // Messaggio lanciato dallo streaming engine
  902.                         msgErrore.equals("Transport level information does not match with SOAP Message namespace URI") ||
  903.                         // ?
  904.                         msgErrore.equals("I dati ricevuti non rappresentano un messaggio SOAP 1.1 valido: ") ||
  905.                         // 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
  906.                         // Proprio nel caso il namespace non corrisponde al tipo atteso.
  907.                         msgErrore.equals("InputStream does not represent a valid SOAP 1.1 Message") ||
  908.                         msgErrore.equals("InputStream does not represent a valid SOAP 1.2 Message")
  909.                     )
  910.                 ){
  911.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  912.                 msgDiag.addKeyword(CostantiPdD.KEY_SOAP_ENVELOPE_NAMESPACE, "Impossibile recuperare il valore del namespace");
  913.                 msgDiag.logPersonalizzato("soapEnvelopeNamespace.versionMismatch");
  914.                 responseMessage = this.generatoreErrore.buildErroreProcessamento(pddContext, IntegrationFunctionError.SOAP_VERSION_MISMATCH,
  915.                         ErroriIntegrazione.ERRORE_430_SOAP_ENVELOPE_NAMESPACE_ERROR.
  916.                             getErrore430_SoapNamespaceNonSupportato(messageTypeReq,  "Impossibile recuperare il valore del namespace"));
  917.             }
  918.             else if(tParsing!=null){
  919.                 pddContext.addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  920.                 msgErrore = tParsing.getMessage();
  921.                 if(msgErrore==null){
  922.                     msgErrore = tParsing.toString();
  923.                 }
  924.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  925.                 logCore.error("parsingExceptionRichiesta",e);
  926.                 msgDiag.logPersonalizzato("parsingExceptionRichiesta");
  927.                
  928.                 IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_REQUEST_CONTENT;
  929.                 if( parseException!=null && parseException.getSourceException()!=null &&
  930.                         TimeoutIOException.isTimeoutIOException(parseException.getSourceException())) {
  931.                     integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  932.                 }
  933.                 else if( parseException!=null && parseException.getSourceException()!=null &&
  934.                         LimitExceededIOException.isLimitExceededIOException(parseException.getSourceException())) {
  935.                     integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  936.                 }
  937.                
  938.                 // Richiesto da certificazione DigitPA
  939.                 responseMessage = this.generatoreErrore.buildErroreIntestazione(pddContext, integrationFunctionError,
  940.                         ErroriIntegrazione.ERRORE_432_PARSING_EXCEPTION_RICHIESTA.getErrore432_MessaggioRichiestaMalformato(tParsing));
  941.             }
  942.             else if (e instanceof HandlerException) {
  943.                 logCore.error("ErroreGenerale (HandlerException)",e);
  944.                 HandlerException he = (HandlerException) e;
  945.                 if(he.isEmettiDiagnostico()) {
  946.                     msgDiag.logErroreGenerico(e, "Generale(richiesta-handler)");
  947.                 }
  948.                 ErroreIntegrazione errore = he.convertToErroreIntegrazione();
  949.                 if(errore==null) {
  950.                     errore = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.get5XX_ErroreProcessamento("Generale(richiesta)");
  951.                 }
  952.                 IntegrationFunctionError integrationError = he.getIntegrationFunctionError();
  953.                 if(integrationError==null) {
  954.                     integrationError = IntegrationFunctionError.BAD_REQUEST;
  955.                 }
  956.                 responseMessage = this.generatoreErrore.buildErroreProcessamento(pddContext, integrationError,errore,e);
  957.                 he.customized(responseMessage);
  958.             }
  959.             else{
  960.                 logCore.error("ErroreGenerale",e);
  961.                 msgDiag.logErroreGenerico(e, "Generale(richiesta)");
  962.                 responseMessage = this.generatoreErrore.buildErroreProcessamento(pddContext, IntegrationFunctionError.BAD_REQUEST,
  963.                         ErroriIntegrazione.ERRORE_426_SERVLET_ERROR.getErrore426_ServletError(true, e), e);
  964.             }

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

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


  1153.        
  1154.         // Imposto risposta

  1155.         Date dataPrimaSpedizioneRisposta = DateManager.getDate();
  1156.         Date dataRispostaSpedita = null;
  1157.         Transazione transazioneDaAggiornare = null;

  1158.         if(context.getMsgDiagnostico()!=null){
  1159.             msgDiag = context.getMsgDiagnostico();
  1160.         }
  1161.         if(context.getResponseHeaders()==null) {
  1162.             context.setResponseHeaders(new HashMap<>());
  1163.         }
  1164.         ServicesUtils.setGovWayHeaderResponse(requestMessage!=null ? requestMessage.getServiceBinding() : requestInfo.getProtocolServiceBinding(),
  1165.                 responseMessage, openSPCoopProperties,
  1166.                 context.getResponseHeaders(), logCore, false, context.getPddContext(), requestInfo);
  1167.         if(context.getResponseHeaders()!=null){
  1168.             Iterator<String> keys = context.getResponseHeaders().keySet().iterator();
  1169.             while (keys.hasNext()) {
  1170.                 String key = (String) keys.next();
  1171.                 List<String> values = context.getResponseHeaders().get(key);
  1172.                 if(values!=null && !values.isEmpty()) {
  1173.                     for (int i = 0; i < values.size(); i++) {
  1174.                         String value = values.get(i);
  1175.                         String verbo = "";
  1176.                         try{
  1177.                             if(i==0) {
  1178.                                 verbo = "set";
  1179.                                 res.setHeader(key,value);
  1180.                             }
  1181.                             else {
  1182.                                 verbo = "add";
  1183.                                 res.addHeader(key,value);
  1184.                             }
  1185.                         }catch(Exception e){
  1186.                             logCore.error("Response."+verbo+"Header("+key+","+value+") error: "+e.getMessage(),e);
  1187.                         }  
  1188.                     }
  1189.                 }
  1190.             }  
  1191.         }
  1192.         if(context!=null && context.getProtocol()!=null){
  1193.            
  1194.             this.generatoreErrore.updateDominio(context.getIdentitaPdD());

  1195.             IDServizio idServizio = null;
  1196.             try{
  1197.                 idServizio = IDServizioFactory.getInstance().getIDServizioFromValues(context.getProtocol().getTipoServizio(),
  1198.                         context.getProtocol().getServizio(),
  1199.                         context.getProtocol().getErogatore(),
  1200.                         context.getProtocol().getVersioneServizio());
  1201.             }catch(Exception e){
  1202.                 // non dovrebbe succedere eccezione}
  1203.             }
  1204.             if(idServizio!=null){
  1205.                 idServizio.setAzione(context.getProtocol().getAzione());
  1206.                 this.generatoreErrore.updateInformazioniCooperazione(context.getProtocol().getFruitore(), idServizio);
  1207.             }
  1208.            
  1209.             String servizioApplicativo = null;
  1210.             if(context.getIntegrazione()!=null){
  1211.                 servizioApplicativo = context.getIntegrazione().getServizioApplicativoFruitore();
  1212.             }
  1213.             this.generatoreErrore.updateInformazioniCooperazione(servizioApplicativo);
  1214.            
  1215.         }
  1216.         DirectVMConnectorOutMessage vm = null;
  1217.         if(res instanceof DirectVMConnectorOutMessage){
  1218.             vm = (DirectVMConnectorOutMessage) res;
  1219.         }
  1220.         else if(req instanceof DumpRawConnectorOutMessage){
  1221.             if( ((DumpRawConnectorOutMessage)res).getWrappedConnectorOutMessage() instanceof DirectVMConnectorOutMessage ){
  1222.                 vm = (DirectVMConnectorOutMessage) ((DumpRawConnectorOutMessage)res).getWrappedConnectorOutMessage();
  1223.             }
  1224.         }
  1225.         if(vm!=null){
  1226.             if(context!=null && context.getPddContext()!=null){
  1227.                 DirectVMProtocolInfo pInfo = new DirectVMProtocolInfo();
  1228.                 Object oIdTransazione = context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  1229.                 if(oIdTransazione!=null){
  1230.                     pInfo.setIdTransazione((String)oIdTransazione);
  1231.                 }
  1232.                 if(context.getProtocol()!=null){
  1233.                     if(context.getProtocol().getIdRichiesta()!=null){
  1234.                         pInfo.setIdMessaggioRichiesta(context.getProtocol().getIdRichiesta());
  1235.                     }
  1236.                     if(context.getProtocol().getIdRisposta()!=null){
  1237.                         pInfo.setIdMessaggioRisposta(context.getProtocol().getIdRisposta());
  1238.                     }
  1239.                 }
  1240.                 vm.setDirectVMProtocolInfo(pInfo);
  1241.             }
  1242.         }
  1243.        
  1244.         InformazioniErroriInfrastrutturali informazioniErrori = ServicesUtils.readInformazioniErroriInfrastrutturali(pddContext);
  1245.        
  1246.         OpenSPCoop2Message responseMessageError = null;
  1247.         EsitoTransazione esito = null;
  1248.         String descrizioneSoapFault = "";
  1249.         int statoServletResponse = 200;
  1250.         Throwable erroreConsegnaRisposta = null;    
  1251.         boolean httpEmptyResponse = false;
  1252.         boolean erroreConnessioneClient = false;
  1253.         boolean erroreResponseTimeout = false;
  1254.         boolean erroreResponsePayloadTooLarge = false;
  1255.         boolean sendInvoked = false;
  1256.         boolean registraTracciaOutResponse = false;
  1257.         try{

  1258.             // Invio la risposta
  1259.             if(responseMessage!=null && !responseMessage.isForcedEmptyResponse() && (responseMessage.getForcedResponse()==null)){
  1260.                    
  1261.                 // force response code
  1262.                 if(responseMessage.getForcedResponseCode()!=null){
  1263.                     try{
  1264.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1265.                     }catch(Exception e){
  1266.                         // ignore
  1267.                     }
  1268.                 }
  1269.                
  1270.                 // Puo' capitare che il messaggio abbia avuto un errore di parsing,
  1271.                 // ma in alcuni test della testsuite capita che non venga sollevata
  1272.                 // nuovamente nei successivi accessi e venga serializzato un messaggio malformato.
  1273.                 // Faccio un check esplicito. In altre servlet non e' stato necessario.
  1274.                                
  1275.                 if(responseMessage.getParseException() != null)
  1276.                     throw responseMessage.getParseException().getSourceException(); // viene gestito a modo dopo nel catch
  1277.                
  1278.                 // transfer length
  1279.                 ServicesUtils.setTransferLength(openSPCoopProperties.getTransferLengthModes_ricezioneBuste(),
  1280.                         req, res, responseMessage);
  1281.                
  1282.                 //NOTA: Faccio la save per refreshare il ContentType. Necessario nel caso di attachment
  1283.                 // (implementazione SAAJ della SUN)
  1284.                 responseMessage.updateContentType();
  1285.                
  1286.                 // content type
  1287.                 ServicesUtils.setContentType(responseMessage, res);

  1288.                 // http status
  1289.                 boolean consume = true;
  1290.                 if(ServiceBinding.SOAP.equals(responseMessage.getServiceBinding()) ){
  1291.                     //SOAPBody body = responseMessage.castAsSoap().getSOAPBody();
  1292.                     OpenSPCoop2SoapMessage soapMessage = responseMessage.castAsSoap();
  1293.                     if(soapMessage.hasSOAPFault()){
  1294.                         consume = false; // può essere usato nel post out response handler
  1295.                         statoServletResponse = 500;
  1296.                         descrizioneSoapFault = " ("+SoapUtils.safe_toString(responseMessage.getFactory(), soapMessage.getSOAPBody().getFault(), false, logCore)+")";
  1297.                     }
  1298.                     else if(statoServletResponse==500) {
  1299.                         // in SOAP 500 deve essere associato con un fault
  1300.                         if(!soapMessage.isSOAPBodyEmpty()) {
  1301.                             statoServletResponse = 200;
  1302.                         }
  1303.                         else {
  1304.                             statoServletResponse = protocolFactory.createProtocolManager().getHttpReturnCodeEmptyResponseOneWay();
  1305.                         }
  1306.                     }
  1307.                 }
  1308.                 else if(responseMessage.castAsRest().isProblemDetailsForHttpApis_RFC7807() ||
  1309.                         (MessageRole.FAULT.equals(responseMessage.getMessageRole()) &&
  1310.                             (
  1311.                             MessageType.XML.equals(responseMessage.getMessageType())
  1312.                                     ||
  1313.                             MessageType.JSON.equals(responseMessage.getMessageType())
  1314.                             )
  1315.                         )
  1316.                     ) {
  1317.                     consume = false; // può essere usato nel post out response handler
  1318.                     String contentAsString = null;
  1319.                     try {
  1320.                         contentAsString = responseMessage.castAsRest().getContentAsString();
  1321.                     }catch(Throwable t) {
  1322.                         logCore.error("Parsing errore non riuscito: "+t.getMessage(),t);
  1323.                     }
  1324.                     if(contentAsString!=null && StringUtils.isNotEmpty(contentAsString)) {
  1325.                         descrizioneSoapFault = " ("+contentAsString+")";
  1326.                     }
  1327.                 }
  1328.                 res.setStatus(statoServletResponse);
  1329.                
  1330.                 // esito calcolato prima del sendResponse, per non consumare il messaggio
  1331.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1332.                         statoServletResponse, requestInfo.getProtocolServiceBinding(),
  1333.                         responseMessage, proprietaErroreAppl,informazioniErrori,
  1334.                         pddContext);
  1335.                
  1336.                 // se il tracciamento lo prevedo emetto un log
  1337.                 registraTracciaOutResponse = true;
  1338.                 transazioneDaAggiornare = registraTracciaOutResponse(context, postOutResponseContext,
  1339.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1340.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1341.                         esito, statoServletResponse,
  1342.                         idModulo, req, requestMessage,
  1343.                         responseMessage, erroreConsegnaRisposta, responseMessageError,
  1344.                         msgDiag);
  1345.                
  1346.                 // Il contentLenght, nel caso di TransferLengthModes.CONTENT_LENGTH e' gia' stato calcolato
  1347.                 // con una writeTo senza consume. Riuso il solito metodo per evitare differenze di serializzazione
  1348.                 // e cambiare quindi il content length effettivo.
  1349.                 sendInvoked = true;
  1350.                 if(TransferLengthModes.CONTENT_LENGTH.equals(openSPCoopProperties.getTransferLengthModes_ricezioneBuste())){
  1351.                     res.sendResponse(responseMessage, false);
  1352.                 } else {
  1353.                     res.sendResponse(responseMessage, consume);
  1354.                 }
  1355.                
  1356.             }
  1357.             else if(responseMessage!=null && responseMessage.getForcedResponse()!=null) {
  1358.                 byte[]response = responseMessage.getForcedResponse().getContent();
  1359. //              if(response==null) {
  1360. //                  throw new Exception("Trovata configurazione 'forcedResponse' senza una vera risposta");
  1361. //              }
  1362.            
  1363.                 if(response!=null && response.length<1024) {
  1364.                     // Se il messaggio non è troppo grande lo aggiungo al diagnostico
  1365.                     try {
  1366.                         descrizioneSoapFault = "("+new String(response)+")";
  1367.                     }catch(Throwable t) {
  1368.                         descrizioneSoapFault = "";
  1369.                     }
  1370.                 }
  1371.                
  1372.                 if(responseMessage.getForcedResponse().getHeadersValues()!=null &&
  1373.                         responseMessage.getForcedResponse().getHeadersValues().size()>0) {
  1374.                     Iterator<String> keys = responseMessage.getForcedResponse().getHeadersValues().keySet().iterator();
  1375.                     while (keys.hasNext()) {
  1376.                         String key = (String) keys.next();
  1377.                         List<String> values = responseMessage.getForcedResponse().getHeadersValues().get(key);
  1378.                         if(values!=null && !values.isEmpty()) {
  1379.                             for (int i = 0; i < values.size(); i++) {
  1380.                                 String value = values.get(i);
  1381.                                 String verbo = "";
  1382.                                 try{
  1383.                                     if(i==0) {
  1384.                                         verbo = "set";
  1385.                                         res.setHeader(key,value);
  1386.                                     }
  1387.                                     else {
  1388.                                         verbo = "add";
  1389.                                         res.addHeader(key,value);
  1390.                                     }
  1391.                                 }catch(Exception e){
  1392.                                     logCore.error("Response(Forced)."+verbo+"Header("+key+","+value+") error: "+e.getMessage(),e);
  1393.                                 }  
  1394.                             }
  1395.                         }
  1396.                     }  
  1397.                 }
  1398.                
  1399.                 if(responseMessage.getForcedResponse().getContentType()!=null) {
  1400.                     res.setContentType(responseMessage.getForcedResponse().getContentType());
  1401.                 }
  1402.                
  1403.                 if(responseMessage.getForcedResponse().getResponseCode()!=null) {
  1404.                     try{
  1405.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponse().getResponseCode());
  1406.                     }catch(Exception e){
  1407.                         // ignore
  1408.                     }
  1409.                 }
  1410.                 else if(responseMessage!=null && responseMessage.getForcedResponseCode()!=null) {
  1411.                     try{
  1412.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1413.                     }catch(Exception e){
  1414.                         // ignore
  1415.                     }
  1416.                 }
  1417.                 res.setStatus(statoServletResponse);
  1418.                
  1419.                 // esito calcolato prima del sendResponse, per non consumare il messaggio
  1420.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1421.                         statoServletResponse, requestInfo.getProtocolServiceBinding(),
  1422.                         responseMessage, proprietaErroreAppl,informazioniErrori,
  1423.                         pddContext);
  1424.                
  1425.                 // se il tracciamento lo prevedo emetto un log
  1426.                 registraTracciaOutResponse = true;
  1427.                 transazioneDaAggiornare = registraTracciaOutResponse(context, postOutResponseContext,
  1428.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1429.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1430.                         esito, statoServletResponse,
  1431.                         idModulo, req, requestMessage,
  1432.                         responseMessage, erroreConsegnaRisposta, responseMessageError,
  1433.                         msgDiag);
  1434.                
  1435.                 if(response!=null) {
  1436.                     sendInvoked = true;
  1437.                     res.sendResponse(DumpByteArrayOutputStream.newInstance(response));
  1438.                 }
  1439.                
  1440.             }
  1441.             else{
  1442.                 if(responseMessage!=null && responseMessage.getForcedResponseCode()!=null) {
  1443.                     try{
  1444.                         statoServletResponse = Integer.parseInt(responseMessage.getForcedResponseCode());
  1445.                     }catch(Exception e){
  1446.                         // ignore
  1447.                     }
  1448.                 }
  1449.                 else {
  1450.                     statoServletResponse = protocolFactory.createProtocolManager().getHttpReturnCodeEmptyResponseOneWay();
  1451.                 }
  1452.                 res.setStatus(statoServletResponse);
  1453.                 httpEmptyResponse = true;
  1454.                 // carico-vuoto
  1455.                 esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1456.                         statoServletResponse, requestInfo.getProtocolServiceBinding(),
  1457.                         responseMessage, proprietaErroreAppl,informazioniErrori,
  1458.                         pddContext);
  1459.                
  1460.                 // se il tracciamento lo prevedo emetto un log
  1461.                 registraTracciaOutResponse = true;
  1462.                 transazioneDaAggiornare = registraTracciaOutResponse(context, postOutResponseContext,
  1463.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1464.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1465.                         esito, statoServletResponse,
  1466.                         idModulo, req, requestMessage,
  1467.                         responseMessage, erroreConsegnaRisposta, responseMessageError,
  1468.                         msgDiag);
  1469.             }
  1470.            
  1471.         }catch(Throwable e){
  1472.             // Errore nell'invio della risposta
  1473.             logCore.error("ErroreGenerale",e);
  1474.             erroreConsegnaRisposta = e;
  1475.            
  1476.             erroreConnessioneClient = ServicesUtils.isConnessioneClientNonDisponibile(e);
  1477.             if(!erroreConnessioneClient && ServicesUtils.isConnessioneServerReadTimeout(e)) {
  1478.                 erroreResponseTimeout = true; // non e' stato possibile consegnare tutta la risposta. Il client ha ricevuto 200 ma non ha ricevuto la risposta per intero
  1479.                 erroreConsegnaRisposta = new CoreException("Connessione con il backend dell'API non più disponibile: "+e.getMessage(),e);
  1480.             }
  1481.             if(!erroreConnessioneClient && !erroreResponseTimeout && ServicesUtils.isResponsePayloadTooLarge(e)) {
  1482.                 erroreResponsePayloadTooLarge = true;  // non e' stato possibile consegnare tutta la risposta. Il client ha ricevuto 200 ma non ha ricevuto la risposta per intero
  1483.                 erroreConsegnaRisposta = new CoreException("Risposta ricevuta dal backend dell'API non gestibile: "+e.getMessage(),e);
  1484.             }
  1485.            
  1486.             // Genero risposta con errore
  1487.             try{
  1488.                 if(sendInvoked==false) {
  1489.                     // nel caso sia già stato inoltrata una risposta non e' più possibile modificarlo cosi come tutti gli header etc...
  1490.                
  1491.                     InformazioniErroriInfrastrutturali informazioniErrori_error = new InformazioniErroriInfrastrutturali();
  1492.                     if( (responseMessage!=null && responseMessage.getParseException() != null) ||
  1493.                             (pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION))){
  1494.                         informazioniErrori_error.setContenutoRispostaNonRiconosciuto(true);
  1495.                         ParseException parseException = null;
  1496.                         if( responseMessage!=null && responseMessage.getParseException() != null ){
  1497.                             parseException = responseMessage.getParseException();
  1498.                         }
  1499.                         else{
  1500.                             parseException = (ParseException) pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  1501.                         }
  1502.                         String msgErrore = parseException.getParseException().getMessage();
  1503.                         if(msgErrore==null){
  1504.                             msgErrore = parseException.getParseException().toString();
  1505.                         }
  1506.                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  1507.                         logCore.error("parsingExceptionRisposta",parseException.getSourceException());
  1508.                         msgDiag.logPersonalizzato("parsingExceptionRisposta");
  1509.                         responseMessageError = this.generatoreErrore.buildErroreProcessamento(pddContext, IntegrationFunctionError.UNPROCESSABLE_RESPONSE_CONTENT,
  1510.                                 ErroriIntegrazione.ERRORE_440_PARSING_EXCEPTION_RISPOSTA.
  1511.                                 getErrore440_MessaggioRispostaMalformato(parseException.getParseException()));
  1512.                     }
  1513.                     else {
  1514.                         IntegrationFunctionError ife = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  1515.                         if(e instanceof HandlerException) {
  1516.                             HandlerException he = (HandlerException) e;
  1517.                             if(he.getIntegrationFunctionError()!=null) {
  1518.                                 ife = he.getIntegrationFunctionError();
  1519.                             }
  1520.                         }
  1521.                         responseMessageError = this.generatoreErrore.buildErroreProcessamento(pddContext, ife,
  1522.                                 ErroriIntegrazione.ERRORE_426_SERVLET_ERROR.getErrore426_ServletError(false, e));
  1523.                     }
  1524.                     // transfer length
  1525.                     ServicesUtils.setTransferLength(openSPCoopProperties.getTransferLengthModes_ricezioneBuste(),
  1526.                             req, res, responseMessageError);
  1527.                                    
  1528.                     // content type
  1529.                     ServicesUtils.setContentType(responseMessageError, res);
  1530.                    
  1531.                     // http status
  1532.                     if(responseMessageError!=null && responseMessageError.getForcedResponseCode()!=null) {
  1533.                         try{
  1534.                             statoServletResponse = Integer.parseInt(responseMessageError.getForcedResponseCode());
  1535.                             res.setStatus(statoServletResponse);
  1536.                         }catch(Exception eStatus){
  1537.                             // ignore
  1538.                         }
  1539.                     }
  1540.                     if(responseMessageError!=null && ServiceBinding.SOAP.equals(responseMessageError.getServiceBinding()) ){
  1541.                         SOAPBody body = responseMessageError.castAsSoap().getSOAPBody();
  1542.                         if(body!=null && body.hasFault()){
  1543.                             statoServletResponse = 500;
  1544.                             res.setStatus(statoServletResponse);
  1545.                             descrizioneSoapFault = " ("+SoapUtils.safe_toString(responseMessageError.getFactory(), body.getFault(), false, logCore)+")";
  1546.                         }
  1547.                     }
  1548.                    
  1549.                     // esito calcolato prima del sendResponse, per non consumare il messaggio
  1550.                     esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),
  1551.                             statoServletResponse, requestInfo.getProtocolServiceBinding(),
  1552.                             responseMessageError, proprietaErroreAppl, informazioniErrori_error,
  1553.                             pddContext);
  1554.                    
  1555.                     // se il tracciamento lo prevedo emetto un log
  1556.                     // se ho già provato prima a tracciare non lo faccio un'altra volta
  1557.                     if(!registraTracciaOutResponse) {
  1558.                         transazioneDaAggiornare = registraTracciaOutResponse(context, postOutResponseContext,
  1559.                             dataAccettazioneRichiesta, dataIngressoRichiesta,
  1560.                             dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1561.                             esito, statoServletResponse,
  1562.                             idModulo, req, requestMessage,
  1563.                             responseMessage, erroreConsegnaRisposta, responseMessageError,
  1564.                             msgDiag);
  1565.                     }
  1566.                    
  1567.                     // Il contentLenght, nel caso di TransferLengthModes.CONTENT_LENGTH e' gia' stato calcolato
  1568.                     // con una writeTo senza consume. Riuso il solito metodo per evitare differenze di serializzazione
  1569.                     // e cambiare quindi il content length effettivo.
  1570.                     //if(TransferLengthModes.CONTENT_LENGTH.equals(openSPCoopProperties.getTransferLengthModes_ricezioneBuste())){
  1571.                     //  res.sendResponse(responseMessageError, false);
  1572.                     //} else {
  1573.                         //res.sendResponse(responseMessageError, true);
  1574.                         res.sendResponse(responseMessageError, false); // può essere usato nel post out response handler
  1575.                     //}
  1576.                 }
  1577.                            
  1578.             }catch(Throwable error){
  1579.                
  1580.                 if(!erroreConnessioneClient){
  1581.                     erroreConnessioneClient = ServicesUtils.isConnessioneClientNonDisponibile(error);
  1582.                 }
  1583.                
  1584.                 logCore.error("Generazione di un risposta errore non riuscita",error);
  1585.                 statoServletResponse = 500;
  1586.                 try{
  1587.                     IntegrationFunctionError ife = null;
  1588.                     if(error instanceof HandlerException) {
  1589.                         HandlerException he = (HandlerException) error;
  1590.                         if(he.getIntegrationFunctionError()!=null) {
  1591.                             ife = he.getIntegrationFunctionError();
  1592.                         }
  1593.                     }
  1594.                     if(ife!=null) {
  1595.                         responseMessageError = this.generatoreErrore.buildFault(error, pddContext, ife);
  1596.                     }
  1597.                     else {
  1598.                         responseMessageError = this.generatoreErrore.buildFault(error, pddContext);
  1599.                     }
  1600.                     if(responseMessageError!=null && responseMessageError.getForcedResponseCode()!=null) {
  1601.                         try{
  1602.                             statoServletResponse = Integer.parseInt(responseMessageError.getForcedResponseCode());
  1603.                         }catch(Exception eStatus){
  1604.                             // ignore
  1605.                         }
  1606.                     }
  1607.                    
  1608.                     try{
  1609.                         res.setStatus(statoServletResponse);
  1610.                     }catch(Exception eStatus){
  1611.                         logCore.error("Response.setStatus("+statoServletResponse+") error: "+eStatus.getMessage(),eStatus);
  1612.                     }
  1613.                    
  1614.                     res.sendResponse(responseMessageError, false); // può essere usato nel post out response handler
  1615.                 }catch(Throwable  eError){
  1616.                     if(!erroreConnessioneClient){
  1617.                         erroreConnessioneClient = ServicesUtils.isConnessioneClientNonDisponibile(eError);
  1618.                     }
  1619.                     try {
  1620.                         res.setStatus(statoServletResponse);
  1621.                     }catch(Throwable t) {
  1622.                         // ignore
  1623.                     }
  1624.                     try{
  1625.                         res.sendResponse(DumpByteArrayOutputStream.newInstance(error.toString().getBytes()));
  1626.                     }catch(Exception erroreStreamChiuso){
  1627.                         erroreConnessioneClient = true;
  1628.                         //se lo stream non e' piu' disponibile non si potra' consegnare alcuna risposta
  1629.                     }
  1630.                 }
  1631.                 try{
  1632.                     esito = protocolFactory.createEsitoBuilder().getEsito(req.getURLProtocolContext(),EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX);
  1633.                 }catch(Exception eBuildError){
  1634.                     esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1635.                 }
  1636.             }
  1637.            
  1638.         }
  1639.         finally{
  1640.            
  1641.             if(sendInvoked==false) {
  1642.                 // nel caso sia già stato inoltrata una risposta non e' più possibile modificarlo cosi come tutti gli header etc...
  1643.                 statoServletResponse = res.getResponseStatus(); // puo' essere "trasformato" da api engine
  1644.             }
  1645.             msgDiag.addKeyword(CostantiPdD.KEY_CODICE_CONSEGNA, ""+statoServletResponse);
  1646.             msgDiag.addKeyword(CostantiPdD.KEY_SOAP_FAULT, descrizioneSoapFault);
  1647.            
  1648.             try{

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

  1775.        
  1776.        
  1777.        
  1778.        
  1779.        
  1780.        
  1781.        
  1782.         /* ------------  PostOutResponseHandler ------------- */
  1783.        
  1784.         if(postOutResponseContext!=null){
  1785.             try{
  1786.                 updateContext(context, postOutResponseContext,
  1787.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1788.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1789.                         esito, statoServletResponse,
  1790.                         idModulo, req, requestMessage,
  1791.                         responseMessage, erroreConsegnaRisposta, responseMessageError);
  1792.                 postOutResponseContext.setTransazioneDaAggiornare(transazioneDaAggiornare);
  1793.                
  1794.             }catch(Exception e){
  1795.                 msgDiag.logErroreGenerico(e,"postOutResponse, preparazione contesto");
  1796.             }
  1797.            
  1798.             GestoreHandlers.postOutResponse(postOutResponseContext, msgDiag, logCore);
  1799.         }
  1800.        
  1801.        
  1802.        
  1803.        
  1804.        
  1805.        
  1806.        
  1807.        
  1808.        
  1809.        
  1810.         // *** Rilascio risorse NotifierInputStream ***
  1811.        
  1812.         // request
  1813.         try{
  1814.             if(requestMessage!=null && requestMessage.getNotifierInputStream()!=null){
  1815.                 requestMessage.getNotifierInputStream().close();
  1816.             }
  1817.         }catch(Exception e){
  1818.             msgDiag.logErroreGenerico(e,"Rilascio risorse NotifierInputStream richiesta");
  1819.         }
  1820.        
  1821.         // response
  1822.         try{
  1823.             if(responseMessage!=null && responseMessage.getNotifierInputStream()!=null){
  1824.                 responseMessage.getNotifierInputStream().close();
  1825.             }
  1826.         }catch(Exception e){
  1827.             msgDiag.logErroreGenerico(e,"Rilascio risorse NotifierInputStream risposta");
  1828.         }
  1829.        
  1830.        
  1831.        
  1832.        
  1833.        
  1834.        
  1835.        
  1836.        
  1837.        
  1838.        
  1839.         // *** GB ***
  1840.         requestMessage = null;
  1841.         responseMessage = null;
  1842.         responseMessageError = null;
  1843.         // *** GB ***
  1844.        
  1845.         return;
  1846.     }


  1847.     private void updateContext(RicezioneBusteContext context, PostOutResponseContext postOutResponseContext,
  1848.             Date dataAccettazioneRichiesta, Date dataIngressoRichiesta,
  1849.             Date dataPrimaSpedizioneRisposta, Date dataRispostaSpedita,
  1850.             EsitoTransazione esito, int statoServletResponse,
  1851.             String idModulo, ConnectorInMessage req, OpenSPCoop2Message requestMessage,
  1852.             OpenSPCoop2Message responseMessage, Throwable erroreConsegnaRisposta, OpenSPCoop2Message responseMessageError) throws ConnectorException {
  1853.         if(postOutResponseContext!=null){
  1854.             postOutResponseContext.getPddContext().addObject(CostantiPdD.DATA_ACCETTAZIONE_RICHIESTA, dataAccettazioneRichiesta);
  1855.             if(dataIngressoRichiesta!=null){
  1856.                 postOutResponseContext.getPddContext().addObject(CostantiPdD.DATA_INGRESSO_RICHIESTA, dataIngressoRichiesta);
  1857.             }
  1858.             postOutResponseContext.setDataElaborazioneMessaggio(DateManager.getDate());
  1859.             postOutResponseContext.setDataPrimaSpedizioneRisposta(dataPrimaSpedizioneRisposta);
  1860.             postOutResponseContext.setDataRispostaSpedita(dataRispostaSpedita);
  1861.             postOutResponseContext.setEsito(esito);
  1862.             postOutResponseContext.setReturnCode(statoServletResponse);
  1863.             postOutResponseContext.setResponseHeaders(context.getResponseHeaders());
  1864.             postOutResponseContext.setProtocollo(context.getProtocol());
  1865.             postOutResponseContext.setIntegrazione(context.getIntegrazione());
  1866.             if(context.getTipoPorta()!=null)
  1867.                 postOutResponseContext.setTipoPorta(context.getTipoPorta());    
  1868.             postOutResponseContext.setIdModulo(idModulo);
  1869.            
  1870.             if(requestMessage!=null){
  1871.                 long incomingRequestMessageContentLength = requestMessage.getIncomingMessageContentLength();
  1872.                 long outgoingRequestMessageContentLenght = requestMessage.getOutgoingMessageContentLength();
  1873.                 if(incomingRequestMessageContentLength<0){
  1874.                     int cl = req.getContentLength();
  1875.                     if(cl>0){
  1876.                         /**System.out.println("HTTP");*/
  1877.                         incomingRequestMessageContentLength = cl + 0l;
  1878.                     }
  1879.                     else{
  1880.                         /**System.out.println("FLUSH");*/
  1881.                         // forzo la lettura del messaggio per impostare la dimensione della richiesta
  1882.                         try{
  1883.                             requestMessage.writeTo(NullOutputStream.INSTANCE, true);
  1884.                         }catch(Exception eFlush){
  1885.                             // ignore
  1886.                         }
  1887.                         incomingRequestMessageContentLength = requestMessage.getIncomingMessageContentLength();
  1888.                     }
  1889.                 }
  1890.                 postOutResponseContext.setInputRequestMessageSize(incomingRequestMessageContentLength);
  1891.                 postOutResponseContext.setOutputRequestMessageSize(outgoingRequestMessageContentLenght);
  1892.             }else{
  1893.                 postOutResponseContext.setInputRequestMessageSize(req.getContentLength()+0l);
  1894.             }
  1895.            
  1896.             if(erroreConsegnaRisposta!=null){
  1897.                 if(responseMessageError!=null){
  1898.                     postOutResponseContext.setInputResponseMessageSize(responseMessageError.getIncomingMessageContentLength());
  1899.                     postOutResponseContext.setOutputResponseMessageSize(responseMessageError.getOutgoingMessageContentLength());
  1900.                     postOutResponseContext.setMessaggio(responseMessageError);
  1901.                 }else{
  1902.                     if(responseMessage!=null && !responseMessage.isForcedEmptyResponse() && responseMessage.getForcedResponse()==null){
  1903.                         postOutResponseContext.setInputResponseMessageSize(responseMessage.getIncomingMessageContentLength());
  1904.                         postOutResponseContext.setOutputResponseMessageSize(responseMessage.getOutgoingMessageContentLength());
  1905.                         postOutResponseContext.setMessaggio(responseMessage);
  1906.                     }
  1907.                 }
  1908.                 postOutResponseContext.setErroreConsegna(erroreConsegnaRisposta.toString()); // NOTA: lasciare e.toString()
  1909.             }
  1910.             else if(responseMessage!=null && !responseMessage.isForcedEmptyResponse() && responseMessage.getForcedResponse()==null){
  1911.                 postOutResponseContext.setInputResponseMessageSize(responseMessage.getIncomingMessageContentLength());
  1912.                 postOutResponseContext.setOutputResponseMessageSize(responseMessage.getOutgoingMessageContentLength());
  1913.                 postOutResponseContext.setMessaggio(responseMessage);
  1914.             }
  1915.             else if(responseMessage!=null && responseMessage.getForcedResponse()!=null &&
  1916.                     responseMessage.getForcedResponse().getContent()!=null) {
  1917.                 postOutResponseContext.setInputResponseMessageSize(responseMessage.getIncomingMessageContentLength());
  1918.                 postOutResponseContext.setOutputResponseMessageSize((long) responseMessage.getForcedResponse().getContent().length);
  1919.             }
  1920.         }
  1921.     }
  1922.    
  1923.    
  1924.     private Transazione registraTracciaOutResponse(RicezioneBusteContext context, PostOutResponseContext postOutResponseContext,
  1925.             Date dataAccettazioneRichiesta, Date dataIngressoRichiesta,
  1926.             Date dataPrimaSpedizioneRisposta, Date dataRispostaSpedita,
  1927.             EsitoTransazione esito, int statoServletResponse,
  1928.             String idModulo, ConnectorInMessage req, OpenSPCoop2Message requestMessage,
  1929.             OpenSPCoop2Message responseMessage, Throwable erroreConsegnaRisposta, OpenSPCoop2Message responseMessageError,
  1930.             MsgDiagnostico msgDiag) throws HandlerException {

  1931.         try {
  1932.        
  1933.             if(postOutResponseContext!=null) {
  1934.                 updateContext(context, postOutResponseContext,
  1935.                         dataAccettazioneRichiesta, dataIngressoRichiesta,
  1936.                         dataPrimaSpedizioneRisposta, dataRispostaSpedita,
  1937.                         esito, statoServletResponse,
  1938.                         idModulo, req, requestMessage,
  1939.                         responseMessage, erroreConsegnaRisposta, responseMessageError);
  1940.                
  1941.                 TracciamentoManager tracciamentoManager = new TracciamentoManager(FaseTracciamento.OUT_RESPONSE);
  1942.                 if(!tracciamentoManager.isTransazioniEnabled()) {
  1943.                     return null;
  1944.                 }
  1945.                
  1946.                 InformazioniTransazione info = new InformazioniTransazione(postOutResponseContext);
  1947.                
  1948.                 tracciamentoManager.invoke(info, postOutResponseContext.getEsito(), context.getResponseHeaders(), msgDiag);
  1949.                
  1950.                 return info.getTransazioneDaAggiornare();
  1951.             }
  1952.            
  1953.         }catch(Exception e) {
  1954.             ServicesUtils.processTrackingException(e, postOutResponseContext.getLogCore(), FaseTracciamento.OUT_RESPONSE, context.getPddContext());
  1955.         }
  1956.        
  1957.         return null;
  1958.     }
  1959.    
  1960.     private void registraTracciaInRequest(RicezioneBusteContext context,
  1961.             IProtocolFactory<?> protocolFactory, Logger log,
  1962.             MsgDiagnostico msgDiag) throws HandlerException {

  1963.         try {
  1964.        
  1965.             TracciamentoManager tracciamentoManager = new TracciamentoManager(FaseTracciamento.IN_REQUEST);
  1966.             if(!tracciamentoManager.isTransazioniEnabled()) {
  1967.                 return;
  1968.             }
  1969.                
  1970.             InformazioniTransazione info = new InformazioniTransazione();
  1971.             info.setContext(context.getPddContext());
  1972.             info.setTipoPorta(context.getTipoPorta());
  1973.             info.setProtocolFactory(protocolFactory);
  1974.             info.setProtocollo(context.getProtocol());
  1975.             info.setIntegrazione(context.getIntegrazione());
  1976.             info.setIdModulo(context.getIdModulo());
  1977.            
  1978.             TransportRequestContext transportRequestContext = null;
  1979.             if(context.getMessageRequest()!=null) {
  1980.                 transportRequestContext = context.getMessageRequest().getTransportRequestContext();
  1981.             }
  1982.             String esitoContext = EsitoBuilder.getTipoContext(transportRequestContext, EsitiProperties.getInstance(log, protocolFactory), log);
  1983.            
  1984.             tracciamentoManager.invoke(info, esitoContext, msgDiag);
  1985.            
  1986.         }catch(Exception e) {
  1987.             ServicesUtils.processTrackingException(e, log, FaseTracciamento.IN_REQUEST, context.getPddContext());
  1988.         }
  1989.        
  1990.     }
  1991. }