RicezioneContenutiApplicativiIntegrationManagerService.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.io.ByteArrayInputStream;
  22. import java.util.ArrayList;
  23. import java.util.Date;
  24. import java.util.Enumeration;
  25. import java.util.HashMap;
  26. import java.util.List;
  27. import java.util.Map;

  28. import javax.servlet.http.HttpServletResponse;
  29. import javax.xml.soap.SOAPFault;

  30. import org.openspcoop2.core.config.DumpConfigurazione;
  31. import org.openspcoop2.core.config.PortaDelegata;
  32. import org.openspcoop2.core.constants.TipoPdD;
  33. import org.openspcoop2.core.id.IDPortaDelegata;
  34. import org.openspcoop2.message.OpenSPCoop2Message;
  35. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  36. import org.openspcoop2.message.OpenSPCoop2MessageParseResult;
  37. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  38. import org.openspcoop2.message.constants.MessageRole;
  39. import org.openspcoop2.message.constants.MessageType;
  40. import org.openspcoop2.message.constants.ServiceBinding;
  41. import org.openspcoop2.message.exception.ParseException;
  42. import org.openspcoop2.message.exception.ParseExceptionUtils;
  43. import org.openspcoop2.message.soap.SoapUtils;
  44. import org.openspcoop2.message.utils.MessageUtilities;
  45. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  46. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  47. import org.openspcoop2.pdd.core.CostantiPdD;
  48. import org.openspcoop2.pdd.core.GestoreMessaggi;
  49. import org.openspcoop2.pdd.core.PdDContext;
  50. import org.openspcoop2.pdd.core.connettori.IConnettore;
  51. import org.openspcoop2.pdd.core.connettori.RepositoryConnettori;
  52. import org.openspcoop2.pdd.core.credenziali.Credenziali;
  53. import org.openspcoop2.pdd.core.handlers.GestoreHandlers;
  54. import org.openspcoop2.pdd.core.handlers.PostOutResponseContext;
  55. import org.openspcoop2.pdd.core.handlers.PreInAcceptRequestContext;
  56. import org.openspcoop2.pdd.core.handlers.PreInRequestContext;
  57. import org.openspcoop2.pdd.core.integrazione.HeaderIntegrazione;
  58. import org.openspcoop2.pdd.core.state.OpenSPCoopStateful;
  59. import org.openspcoop2.pdd.core.transazioni.TransactionContext;
  60. import org.openspcoop2.pdd.logger.Dump;
  61. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  62. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  63. import org.openspcoop2.pdd.logger.transazioni.ConfigurazioneTracciamento;
  64. import org.openspcoop2.pdd.services.DumpRaw;
  65. import org.openspcoop2.pdd.services.ServicesUtils;
  66. import org.openspcoop2.pdd.services.connector.ConnectorDispatcherInfo;
  67. import org.openspcoop2.pdd.services.connector.ConnectorUtils;
  68. import org.openspcoop2.pdd.services.connector.messages.HttpServletConnectorInMessage;
  69. import org.openspcoop2.pdd.services.connector.messages.HttpServletConnectorOutMessage;
  70. import org.openspcoop2.pdd.services.core.RicezioneContenutiApplicativi;
  71. import org.openspcoop2.pdd.services.core.RicezioneContenutiApplicativiContext;
  72. import org.openspcoop2.pdd.services.error.RicezioneContenutiApplicativiInternalErrorGenerator;
  73. import org.openspcoop2.pdd.services.skeleton.IntegrationManager;
  74. import org.openspcoop2.pdd.services.skeleton.IntegrationManagerException;
  75. import org.openspcoop2.pdd.services.skeleton.IntegrationManagerMessage;
  76. import org.openspcoop2.pdd.services.skeleton.IntegrationManagerUtility;
  77. import org.openspcoop2.pdd.services.skeleton.ProtocolHeaderInfo;
  78. import org.openspcoop2.protocol.basic.registry.ServiceIdentificationReader;
  79. import org.openspcoop2.protocol.engine.SecurityTokenUtilities;
  80. import org.openspcoop2.protocol.engine.URLProtocolContextImpl;
  81. import org.openspcoop2.protocol.engine.constants.Costanti;
  82. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  83. import org.openspcoop2.protocol.sdk.builder.EsitoTransazione;
  84. import org.openspcoop2.protocol.sdk.builder.InformazioniErroriInfrastrutturali;
  85. import org.openspcoop2.protocol.sdk.builder.ProprietaErroreApplicativo;
  86. import org.openspcoop2.protocol.sdk.constants.CodiceErroreIntegrazione;
  87. import org.openspcoop2.protocol.sdk.constants.ErroriIntegrazione;
  88. import org.openspcoop2.protocol.sdk.constants.EsitoTransazioneName;
  89. import org.openspcoop2.protocol.sdk.constants.IDService;
  90. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  91. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  92. import org.openspcoop2.protocol.sdk.state.URLProtocolContext;
  93. import org.openspcoop2.protocol.utils.ErroriProperties;
  94. import org.openspcoop2.utils.LimitExceededIOException;
  95. import org.openspcoop2.utils.MapKey;
  96. import org.openspcoop2.utils.TimeoutIOException;
  97. import org.openspcoop2.utils.Utilities;
  98. import org.openspcoop2.utils.date.DateManager;
  99. import org.openspcoop2.utils.io.notifier.NotifierInputStreamParams;
  100. import org.openspcoop2.utils.transport.TransportUtils;
  101. import org.slf4j.Logger;

  102. /**
  103.  * RicezioneContenutiApplicativiIntegrationManagerService
  104.  *
  105.  * @author Poli Andrea (apoli@link.it)
  106.  * @author $Author$
  107.  * @version $Rev$, $Date$
  108.  */
  109. public class RicezioneContenutiApplicativiIntegrationManagerService {

  110.     public IntegrationManagerMessage process(String tipoOperazione, String portaDelegata, IntegrationManagerMessage msg,
  111.             String idInvocazionePerRiferimento,
  112.             Logger logCore, javax.servlet.http.HttpServletRequest req, HttpServletResponse res,
  113.             IProtocolFactory<?> protocolFactory, Date dataAccettazioneRichiesta, Date dataIngressoRichiesta) throws IntegrationManagerException {

  114.         String idModulo = RicezioneContenutiApplicativi.ID_MODULO+IntegrationManager.ID_MODULO;
  115.        
  116.         ErroriProperties erroriProperties = null;
  117.         try {
  118.             erroriProperties = ErroriProperties.getInstance(logCore);
  119.         }catch(Exception Ignoree) {
  120.             // non succede
  121.         }
  122.        
  123.         // Proprieta' OpenSPCoop
  124.         OpenSPCoop2Properties openSPCoopProperties = OpenSPCoop2Properties.getInstance();
  125.         if (openSPCoopProperties == null) {
  126.             String msgError = "Inizializzazione di GovWay non correttamente effettuata: OpenSPCoopProperties";
  127.             logCore.error(msgError);
  128.             try{
  129.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  130.                         get5XX_ErroreProcessamento(msgError,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  131.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, erroriProperties);
  132.             }catch(Throwable eError){
  133.                 logCore.error("Errore generazione SOAPFault",eError);
  134.                 throw new RuntimeException(eError); // errore che non dovrebbe accadare
  135.             }
  136.         }

  137.         RequestInfo requestInfo = null;
  138.         try{
  139.             // Request Info
  140.             URLProtocolContext urlProtocolContext = new URLProtocolContextImpl(req,logCore,true,true,openSPCoopProperties.getCustomContexts());
  141.             urlProtocolContext.setInterfaceName(portaDelegata);
  142.             if(protocolFactory==null) {
  143.                 throw new Exception("ProtocolFactory is null");
  144.             }
  145.             requestInfo = ConnectorUtils.getRequestInfo(protocolFactory, urlProtocolContext);
  146.             if(requestInfo==null) {
  147.                 throw new Exception("RequestInfo is null");
  148.             }
  149.         }catch(Exception e){
  150.             String msgError = "Lettura RequestInfo non riuscita: "+Utilities.readFirstErrorValidMessageFromException(e);
  151.             logCore.error(msgError);
  152.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  153.                     get5XX_ErroreProcessamento(msgError),
  154.                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  155.         }
  156.        
  157.        
  158.        
  159.        
  160.        

  161.         /* ------------  PreInHandler (PreInAcceptRequestContext) ------------- */
  162.        
  163.         // build context
  164.         PreInAcceptRequestContext preInAcceptRequestContext = new PreInAcceptRequestContext();
  165.         preInAcceptRequestContext.setTipoPorta(TipoPdD.DELEGATA);
  166.         preInAcceptRequestContext.setIdModulo(idModulo);
  167.         preInAcceptRequestContext.setRequestInfo(requestInfo);  
  168.         preInAcceptRequestContext.setLogCore(logCore);
  169.         preInAcceptRequestContext.setReq(null);
  170.        
  171.         // invocazione handler
  172.         GestoreHandlers.preInRequest(preInAcceptRequestContext, logCore, logCore);
  173.        
  174.        
  175.        
  176.        
  177.         // Configurazione Reader
  178.         ConfigurazionePdDManager configPdDManager = null;
  179.         try{
  180.             configPdDManager = ConfigurazionePdDManager.getInstance();
  181.             if(configPdDManager==null || configPdDManager.isInitializedConfigurazionePdDReader()==false){
  182.                 throw new Exception("ConfigurazionePdDManager not initialized");
  183.             }
  184.         }catch(Throwable e){
  185.             String msgError = "Inizializzazione di GovWay non correttamente effettuata: ConfigurazionePdDManager";
  186.             logCore.error(msgError,e);
  187.             try{
  188.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  189.                         get5XX_ErroreProcessamento(msgError,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  190.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, erroriProperties);
  191.             }catch(Throwable eError){
  192.                 logCore.error("Errore generazione SOAPFault",eError);
  193.                 throw new RuntimeException(eError); // errore che non dovrebbe accadare
  194.             }
  195.         }
  196.            
  197.        
  198.         // Identifico Servizio per comprendere correttamente il messageType
  199.         ServiceIdentificationReader serviceIdentificationReader = null;
  200.         try{
  201.             serviceIdentificationReader = ServicesUtils.getServiceIdentificationReader(logCore, requestInfo,
  202.                     configPdDManager.getRegistroServiziManager(), configPdDManager);
  203.         }catch(Exception e){
  204.             String msgError = "Inizializzazione RegistryReader fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  205.             logCore.error(msgError,e);
  206.             try{
  207.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  208.                         get5XX_ErroreProcessamento(msgError),
  209.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, erroriProperties);
  210.             }catch(Throwable eError){
  211.                 logCore.error("Errore generazione SOAPFault",eError);
  212.                 throw new RuntimeException(eError); // errore che non dovrebbe accadare
  213.             }
  214.         }
  215.        
  216.         // Provo a creare un context (per l'id di transazione nei diagnostici)
  217.         RicezioneContenutiApplicativiContext context = null;
  218.         try {
  219.             context = new RicezioneContenutiApplicativiContext(IDService.PORTA_DELEGATA_INTEGRATION_MANAGER, dataAccettazioneRichiesta,requestInfo);
  220.             String idTransazione = (String)context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  221.             if(openSPCoopProperties.isTransazioniEnabled()) {
  222.                 TransactionContext.createTransaction(idTransazione, "RicezioneContenutiApplicativiIM.1");
  223.             }
  224.             requestInfo.setIdTransazione(idTransazione);
  225.         }catch(Throwable e) {
  226.             context = null;
  227.             // non loggo l'errore tanto poi provo a ricreare il context subito dopo e li verra' registrato l'errore
  228.         }
  229.        
  230.         // Logger dei messaggi diagnostici
  231.         String nomePorta = portaDelegata;
  232.         MsgDiagnostico msgDiag = MsgDiagnostico.newInstance(TipoPdD.DELEGATA,IntegrationManager.ID_MODULO,nomePorta,requestInfo,configPdDManager);
  233.         msgDiag.setPrefixMsgPersonalizzati(MsgDiagnosticiProperties.MSG_DIAG_INTEGRATION_MANAGER);
  234.         msgDiag.addKeyword(CostantiPdD.KEY_TIPO_OPERAZIONE_IM, tipoOperazione);
  235.         if(context!=null) {
  236.             msgDiag.setPddContext(context.getPddContext(), protocolFactory);
  237.         }
  238.        
  239.         try{
  240.             msgDiag.logPersonalizzato("ricezioneRichiesta.firstLog");
  241.         }catch(Exception e){
  242.             logCore.error("Errore generazione diagnostico di ingresso",e);
  243.         }
  244.        
  245.         // emitDiagnostic preAccept handler
  246.         GestoreHandlers.emitDiagnostic(msgDiag, preInAcceptRequestContext, context!=null ? context.getPddContext() : null,
  247.                 logCore, logCore);
  248.                
  249.         // GeneratoreErrore
  250.         RicezioneContenutiApplicativiInternalErrorGenerator generatoreErrore = null;
  251.         try{
  252.             generatoreErrore =
  253.                         new RicezioneContenutiApplicativiInternalErrorGenerator(logCore, idModulo, requestInfo);
  254.         }catch(Exception e){
  255.             String msgError = "Inizializzazione Generatore Errore fallita: "+Utilities.readFirstErrorValidMessageFromException(e);
  256.             msgDiag.logErroreGenerico(e,"Inizializzazione Generatore Errore");
  257.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  258.                     get5XX_ErroreProcessamento(msgError),
  259.                     IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, erroriProperties);
  260.         }
  261.        
  262.         // Aggiorno RequestInfo
  263.         try{
  264.             msgDiag.mediumDebug("Accesso configurazione della richiesta in corso...");
  265.         }catch(Exception e){
  266.             logCore.error("Errore generazione diagnostico",e);
  267.         }
  268.         ConnectorDispatcherInfo cInfo = null;
  269.         try{
  270.             cInfo = RicezioneContenutiApplicativiServiceUtils.updatePortaDelegataRequestInfo(requestInfo, logCore, null, null,
  271.                     generatoreErrore, serviceIdentificationReader, msgDiag,
  272.                     context!=null ? context.getPddContext(): null);
  273.             if(cInfo!=null){
  274.                 try{
  275.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  276.                             getErroreIntegrazione(),
  277.                             IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  278.                 }catch(Throwable eError){
  279.                     logCore.error("Errore generazione SOAPFault",eError);
  280.                     throw new RuntimeException(eError); // errore che non dovrebbe accadare
  281.                 }
  282.             }
  283.         }catch(Exception e){
  284.             String msgError = "Aggiornamento RequestInfo fallito: "+Utilities.readFirstErrorValidMessageFromException(e);
  285.             logCore.error(msgError,e);
  286.             try{
  287.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  288.                         get5XX_ErroreProcessamento(msgError),
  289.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  290.             }catch(Throwable eError){
  291.                 logCore.error("Errore generazione SOAPFault",eError);
  292.                 throw new RuntimeException(eError); // errore che non dovrebbe accadare
  293.             }
  294.         }finally {
  295.             if(cInfo!=null) {
  296.                 RicezioneContenutiApplicativiServiceUtils.emitTransaction(context,logCore, idModulo, IDService.PORTA_DELEGATA_INTEGRATION_MANAGER, protocolFactory, requestInfo,
  297.                         null, dataAccettazioneRichiesta, cInfo);
  298.             }
  299.         }
  300.        
  301.         // DumpRaw
  302.         DumpRaw dumpRaw = null;
  303.         try{
  304.             try{
  305.                 msgDiag.mediumDebug("Lettura configurazione dump binario ...");
  306.             }catch(Exception e){
  307.                 logCore.error("Errore generazione diagnostico",e);
  308.             }
  309.             boolean dumpBinario = configPdDManager.dumpBinarioPD();
  310.             PortaDelegata pd = null;
  311.             if(requestInfo!=null && requestInfo.getProtocolContext()!=null && requestInfo.getProtocolContext().getInterfaceName()!=null) {
  312.                 IDPortaDelegata idPD = new IDPortaDelegata();
  313.                 idPD.setNome(requestInfo.getProtocolContext().getInterfaceName());
  314.                 pd = configPdDManager.getPortaDelegataSafeMethod(idPD, requestInfo);
  315.             }
  316.             try{
  317.                 msgDiag.mediumDebug("Lettura configurazione dump ...");
  318.             }catch(Exception e){
  319.                 logCore.error("Errore generazione diagnostico",e);
  320.             }
  321.             DumpConfigurazione dumpConfigurazione = configPdDManager.getDumpConfigurazione(pd);
  322.             ConfigurazioneTracciamento configurazioneTracciamento = new ConfigurazioneTracciamento(logCore, configPdDManager, pd);
  323.             boolean fileTraceHeaders = configurazioneTracciamento.isTransazioniFileTraceDumpBinarioHeaderEnabled();
  324.             boolean fileTracePayload = configurazioneTracciamento.isTransazioniFileTraceDumpBinarioPayloadEnabled();
  325.             dumpRaw = new DumpRaw(logCore,requestInfo.getIdentitaPdD(), idModulo, TipoPdD.DELEGATA,
  326.                     dumpBinario,
  327.                     dumpConfigurazione,
  328.                     fileTraceHeaders, fileTracePayload);
  329.         }catch(Throwable e){
  330.             String msgError = "Inizializzazione di GovWay non correttamente effettuata: DumpRaw";
  331.             logCore.error(msgError,e);
  332.             try{
  333.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  334.                         get5XX_ErroreProcessamento(msgError,CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  335.                         IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, erroriProperties);
  336.             }catch(Throwable eError){
  337.                 logCore.error("Errore generazione SOAPFault",eError);
  338.                 throw new RuntimeException(eError); // errore che non dovrebbe accadare
  339.             }
  340.         }


  341.        
  342.        
  343.        
  344.        
  345.         /* ------------  Gestione ------------- */
  346.        
  347.         OpenSPCoopStateful stato = null;
  348.        
  349.         try{
  350.             try{
  351.                 msgDiag.mediumDebug("Creazione contesto ...");
  352.             }catch(Exception e){
  353.                 logCore.error("Errore generazione diagnostico",e);
  354.             }
  355.             // viene generato l'UUID
  356.             if(context==null) {
  357.                 context = new RicezioneContenutiApplicativiContext(IDService.PORTA_DELEGATA_INTEGRATION_MANAGER, dataAccettazioneRichiesta,requestInfo);
  358.             }
  359.             if(preInAcceptRequestContext!=null && preInAcceptRequestContext.getPreContext()!=null && !preInAcceptRequestContext.getPreContext().isEmpty()) {
  360.                 context.getPddContext().addAll(preInAcceptRequestContext.getPreContext(), false);
  361.             }
  362.             context.setDataIngressoRichiesta(dataIngressoRichiesta);
  363.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  364.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO, requestInfo);
  365.             RicezionePropertiesConfig rConfig = RicezioneContenutiApplicativiServiceUtils.readPropertiesConfig(requestInfo, logCore,null);
  366.             if(rConfig!=null) {
  367.                 if (rConfig.getApiImplementation() != null && !rConfig.getApiImplementation().isEmpty()) {
  368.                    context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_CONFIGURAZIONE, rConfig.getApiImplementation());
  369.                 }
  370.                 if (rConfig.getSoggettoFruitore() != null && !rConfig.getSoggettoFruitore().isEmpty()) {
  371.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_FRUITORE, rConfig.getSoggettoFruitore());
  372.                 }
  373.                 if (rConfig.getSoggettoErogatore() != null && !rConfig.getSoggettoErogatore().isEmpty()) {
  374.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROPRIETA_SOGGETTO_EROGATORE, rConfig.getSoggettoErogatore());
  375.                 }
  376.             }
  377.             context.getPddContext().addObject(CostantiPdD.TIPO_OPERAZIONE_IM, tipoOperazione);
  378.             context.setTipoPorta(TipoPdD.DELEGATA);
  379.             msgDiag.setPddContext(context.getPddContext(), protocolFactory);
  380.            
  381.             if(dumpRaw!=null && dumpRaw.isActiveDump()){
  382.                 dumpRaw.setPddContext(msgDiag.getPorta(), context.getPddContext());
  383.             }
  384.         }catch(Exception e){
  385.             msgDiag.logErroreGenerico(e,"invocaPortaDelegata_engine("+tipoOperazione+").newRicezioneContenutiApplicativiContext()");
  386.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),
  387.                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  388.         }
  389.        
  390.         try{
  391.             if(openSPCoopProperties.isTransazioniEnabled()) {
  392.                 // NOTA: se gia' esiste con l'id di transazione, non viene ricreata
  393.                 TransactionContext.createTransaction((String)context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE),"RicezioneContenutiApplicativiIM.2");
  394.             }
  395.         }catch(Exception e){
  396.             logCore.error("Errore durante la creazione della transazione",e);
  397.         }
  398.        
  399.         try{
  400.             msgDiag.logPersonalizzato("ricezioneRichiesta.firstAccessRequestStream");
  401.         }catch(Exception e){
  402.             logCore.error("Errore generazione diagnostico di ingresso (stream access)",e);
  403.         }
  404.        
  405.         if(dumpRaw!=null && dumpRaw.isActiveDump()){
  406.             dumpRaw.serializeContext(context, protocolFactory.getProtocol());
  407.         }
  408.        
  409.         // PddContext
  410.         String idTransazione = PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE,context.getPddContext());
  411.         context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, idTransazione);
  412.         context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.TIPO_OPERAZIONE_IM, tipoOperazione.toString());
  413.         context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.ID_MESSAGGIO, idInvocazionePerRiferimento);
  414.         context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PORTA_DELEGATA, portaDelegata);
  415.         context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  416.        
  417.         EsitoTransazione esito = null;
  418.         String errore = null;
  419.         OpenSPCoop2Message msgRequest = null;
  420.         OpenSPCoop2Message msgResponse = null;
  421.         IntegrationManagerMessage msgReturn = null;
  422.         String descrizioneSoapFault = "";
  423.         URLProtocolContext urlProtocolContext = null;
  424.         try{

  425.            
  426.             /* ------------  PreInHandler ------------- */
  427.            
  428.             // build context
  429.             PreInRequestContext preInRequestContext = new PreInRequestContext(context.getPddContext());
  430.             preInRequestContext.setTipoPorta(TipoPdD.DELEGATA);
  431.             preInRequestContext.setIdModulo(idModulo);
  432.             preInRequestContext.setProtocolFactory(protocolFactory);
  433.             preInRequestContext.setRequestInfo(requestInfo);
  434.             Map<String, Object> transportContext = new HashMap<>();
  435.             HttpServletConnectorInMessage httpIn = null;
  436.             try{
  437.                 httpIn = new HttpServletConnectorInMessage(requestInfo, req, IntegrationManager.ID_SERVICE, IntegrationManager.ID_MODULO);
  438.                 transportContext.put(PreInRequestContext.SERVLET_REQUEST, httpIn);
  439.             }catch(Exception e){
  440.                 ConnectorUtils.getErrorLog().error("HttpServletConnectorInMessage init error: "+e.getMessage(),e);
  441.                 /**throw new ServletException(e.getMessage(),e);*/
  442.             }
  443.             HttpServletConnectorOutMessage httpOut = null;
  444.             try{
  445.                 httpOut = new HttpServletConnectorOutMessage(requestInfo, protocolFactory, res, IntegrationManager.ID_SERVICE, IntegrationManager.ID_MODULO);
  446.                 transportContext.put(PreInRequestContext.SERVLET_RESPONSE, httpOut);
  447.             }catch(Exception e){
  448.                 ConnectorUtils.getErrorLog().error("HttpServletConnectorOutMessage init error: "+e.getMessage(),e);
  449.                 /**throw new ServletException(e.getMessage(),e);*/
  450.             }
  451.             preInRequestContext.setTransportContext(transportContext);  
  452.             preInRequestContext.setLogCore(logCore);
  453.            
  454.             // invocazione handler
  455.             GestoreHandlers.preInRequest(preInRequestContext, msgDiag, logCore);
  456.            
  457.             // aggiungo eventuali info inserite nel preInHandler
  458.             context.getPddContext().addAll(preInRequestContext.getPddContext(), false);
  459.            
  460.             // Lettura risposta parametri NotifierInputStream
  461.             NotifierInputStreamParams notifierInputStreamParams = preInRequestContext.getNotifierInputStreamParams();
  462.             context.setNotifierInputStreamParams(notifierInputStreamParams);
  463.            
  464.             msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.tipologiaMessaggio");
  465.            
  466.            
  467.            
  468.            

  469.             /* ------------  Validazione INPUT in base all'operaizone invocata ------------- */
  470.             if("invocaPortaDelegata".equals(tipoOperazione)){
  471.                 // check presenza body applicativo
  472.                 if(msg==null || msg.getMessage()==null){
  473.                     msgDiag.logPersonalizzato("invocazionePortaDelegata.contenutoApplicativoNonPresente");
  474.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  475.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),
  476.                             IntegrationFunctionError.BAD_REQUEST, erroriProperties);
  477.                 }
  478.             }
  479.             else if("invocaPortaDelegataPerRiferimento".equals(tipoOperazione)){
  480.                 //   check presenza riferimento
  481.                 if(idInvocazionePerRiferimento==null){
  482.                     msgDiag.logPersonalizzato("invocazionePortaDelegataPerRiferimento.riferimentoMessaggioNonPresente");
  483.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  484.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),
  485.                             IntegrationFunctionError.BAD_REQUEST, erroriProperties);
  486.                 }
  487.             }
  488.             else if("sendRispostaAsincronaSimmetrica".equals(tipoOperazione)){
  489.                 // check presenza body applicativo
  490.                 if(msg==null || msg.getMessage()==null){
  491.                     msgDiag.logPersonalizzato("invocazionePortaDelegata.contenutoApplicativoNonPresente");
  492.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  493.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),
  494.                             IntegrationFunctionError.BAD_REQUEST, erroriProperties);
  495.                 }
  496.                 //  check presenza id di correlazione asincrona
  497.                 if(msg.getProtocolHeaderInfo()==null || msg.getProtocolHeaderInfo().getRiferimentoMessaggio()==null){
  498.                     msgDiag.logPersonalizzato("invocazionePortaDelegata.profiloAsincrono.riferimentoMessaggioNonPresente");
  499.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  500.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),
  501.                             IntegrationFunctionError.CORRELATION_INFORMATION_NOT_FOUND, erroriProperties);
  502.                 }
  503.             }
  504.             else if("sendRichiestaStatoAsincronaAsimmetrica".equals(tipoOperazione)){
  505.                 //  check presenza body applicativo
  506.                 if(msg==null || msg.getMessage()==null){
  507.                     msgDiag.logPersonalizzato("invocazionePortaDelegata.contenutoApplicativoNonPresente");
  508.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  509.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),
  510.                             IntegrationFunctionError.BAD_REQUEST, erroriProperties);
  511.                 }
  512.                 //  check presenza id di correlazione asincrona
  513.                 if(msg.getProtocolHeaderInfo()==null || msg.getProtocolHeaderInfo().getRiferimentoMessaggio()==null){
  514.                     msgDiag.logPersonalizzato("invocazionePortaDelegata.profiloAsincrono.riferimentoMessaggioNonPresente");
  515.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  516.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),
  517.                             IntegrationFunctionError.CORRELATION_INFORMATION_NOT_FOUND, erroriProperties);
  518.                 }
  519.             }
  520.             else{
  521.                 throw new Exception("Tipo operazione ["+tipoOperazione+"] non gestita");
  522.             }
  523.            
  524.            
  525.            
  526.             /* ------------  Lettura parametri della richiesta ------------- */
  527.        
  528.             // Credenziali utilizzate nella richiesta
  529.             Credenziali credenziali = new Credenziali(requestInfo.getProtocolContext().getCredential());
  530.             // Credenziali credenziali = (Credenziali) msgContext.get("openspcoop.credenziali");

  531.             String credenzialiFornite = "";
  532.             if(credenziali!=null){
  533.                 credenzialiFornite = credenziali.toString();
  534.                 msgDiag.addKeyword(CostantiPdD.KEY_CREDENZIALI_SA_FRUITORE, credenzialiFornite);
  535.             }

  536.             String invPerRiferimento = "";
  537.             if(idInvocazionePerRiferimento!=null)
  538.                 invPerRiferimento = " idInvocazionePerRiferimento["+idInvocazionePerRiferimento+"]";

  539.             String riferimentoMessaggio = "";
  540.             if(msg.getProtocolHeaderInfo()!=null && msg.getProtocolHeaderInfo().getRiferimentoMessaggio()!=null){
  541.                 riferimentoMessaggio = " riferimentoMessaggio["+msg.getProtocolHeaderInfo().getRiferimentoMessaggio()+"]";
  542.             }

  543.             String param = "PD["+portaDelegata+"]"+credenzialiFornite+invPerRiferimento+riferimentoMessaggio;
  544.             msgDiag.addKeyword(CostantiPdD.KEY_PARAMETRI_OPERAZIONE_IM, param);
  545.             msgDiag.logPersonalizzato("logInvocazioneOperazione");

  546.            
  547.            
  548.             // Properties Trasporto
  549.             Map<String, List<String>> headerTrasporto = null;
  550.             if(openSPCoopProperties.integrationManager_readInformazioniTrasporto()){
  551.                 headerTrasporto = new HashMap<>();
  552.                 java.util.Enumeration<?> enTrasporto = req.getHeaderNames();
  553.                 while(enTrasporto.hasMoreElements()){
  554.                     String nomeHeader = (String)enTrasporto.nextElement();

  555.                     Enumeration<String> enValues = req.getHeaders(nomeHeader);
  556.                     List<String> values = new ArrayList<>();
  557.                     if(enValues!=null) {
  558.                         @SuppressWarnings("unused")
  559.                         int i = 0;
  560.                         while (enValues.hasMoreElements()) {
  561.                             String value = (String) enValues.nextElement();
  562.                             values.add(value);
  563.                             //logCore.info("Header ["+nomeHeader+"] valore-"+i+" ["+value+"]");
  564.                             i++;
  565.                         }
  566.                     }
  567.                     if(values.isEmpty()) {
  568.                         //logCore.info("Header ["+nomeHeader+"] valore ["+req.getHeader(nomeHeader)+"]");
  569.                         values.add(req.getHeader(nomeHeader));
  570.                     }
  571.                    
  572.                     headerTrasporto.put(nomeHeader,values);
  573.                 }
  574.             }
  575.            
  576.            
  577.             // Parametri della porta delegata invocata
  578.             urlProtocolContext = new URLProtocolContextImpl(logCore);
  579.             urlProtocolContext.setInterfaceName(portaDelegata);
  580.             urlProtocolContext.setFunctionParameters(portaDelegata);
  581.             urlProtocolContext.setRequestURI(portaDelegata);
  582.             urlProtocolContext.setFunction(URLProtocolContext.IntegrationManager_FUNCTION);
  583.             urlProtocolContext.setProtocol(protocolFactory.getProtocol(),
  584.                     requestInfo.getProtocolContext().getProtocolWebContext());
  585.             if(openSPCoopProperties.integrationManager_readInformazioniTrasporto()){
  586.                 urlProtocolContext.setHeaders(headerTrasporto);
  587.             }
  588.            

  589.             //  Messaggio di richiesta
  590.             msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.inCorso");
  591.             Utilities.printFreeMemory("IntegrationManager - Pre costruzione richiesta");
  592.             if(idInvocazionePerRiferimento!=null){

  593.                 if(dumpRaw!=null && dumpRaw.isActiveDump()){
  594.                     String contentTypeRichiesta = null; // idInvocazionePerRiferimento
  595.                     Integer contentLengthRichiesta = null;
  596.                     String rawMessage = idInvocazionePerRiferimento;
  597.                     dumpRaw.serializeRequest(contentTypeRichiesta, contentLengthRichiesta, requestInfo.getProtocolContext().getCredential(),
  598.                             urlProtocolContext, rawMessage, null);
  599.                 }
  600.                
  601.                 stato = new OpenSPCoopStateful();
  602.                 stato.initResource(openSPCoopProperties.getIdentitaPortaDefault(protocolFactory.getProtocol(), requestInfo),IntegrationManager.ID_MODULO,idTransazione);
  603.                 configPdDManager = configPdDManager.refreshState(stato.getStatoRichiesta(),stato.getStatoRisposta());
  604.                 msgDiag.updateState(configPdDManager);
  605.                
  606.                 // Leggo Messaggio
  607.                 try{
  608.                     GestoreMessaggi gestoreMessaggio = new GestoreMessaggi(stato, true,idInvocazionePerRiferimento,Costanti.INBOX,msgDiag,context.getPddContext());
  609.                     msgRequest = gestoreMessaggio.getMessage();
  610.                 }catch(Exception e){
  611.                     msgDiag.logErroreGenerico(e,"gestoreMessaggio.getMessagePerRiferimento("+idInvocazionePerRiferimento+")");
  612.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  613.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),
  614.                             IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  615.                 }

  616.                 // Rilascio Connessione DB
  617.                 stato.releaseResource();
  618.                 stato = null;

  619.             }else{

  620.                 if(dumpRaw!=null && dumpRaw.isActiveDump()){
  621.                     String contentTypeRichiesta = "text/xml"; // per ora e' cablato.
  622.                     Integer contentLengthRichiesta = null;
  623.                     String rawMessage = null;
  624.                     if(msg.getMessage()!=null){
  625.                         try{
  626.                             contentLengthRichiesta = msg.getMessage().length;
  627.                             rawMessage = new String(msg.getMessage());
  628.                         }catch(Throwable t){
  629.                             logCore.error("Dump error: "+t.getMessage(),t);
  630.                         }
  631.                     }
  632.                     dumpRaw.serializeRequest(contentTypeRichiesta, contentLengthRichiesta, requestInfo.getProtocolContext().getCredential(),
  633.                             urlProtocolContext, rawMessage, null);
  634.                 }
  635.                
  636.                 // Ricostruzione Messaggio
  637.                 try{
  638.                     MessageType messageType = MessageType.SOAP_11; // todo parametrico
  639.                     String contentType = MessageUtilities.getDefaultContentType(messageType); // todo parametrico
  640.                     String soapAction = "OpenSPCoop"; // todo parametrico
  641.                     ByteArrayInputStream bin = new ByteArrayInputStream(msg.getMessage());
  642.                    
  643.                     OpenSPCoop2MessageParseResult pr = null;
  644.                     OpenSPCoop2MessageFactory factory = org.openspcoop2.pdd.core.Utilities.getOpenspcoop2MessageFactory(logCore,requestInfo, MessageRole.REQUEST);
  645.                     if(msg.getImbustamento()){
  646.                         pr = factory.envelopingMessage(messageType, MessageRole.REQUEST, contentType, soapAction, bin,
  647.                                 notifierInputStreamParams, openSPCoopProperties.getAttachmentsProcessingMode(),
  648.                                 openSPCoopProperties.isDeleteInstructionTargetMachineXml(),
  649.                                 openSPCoopProperties.useSoapMessageReader(), openSPCoopProperties.getSoapMessageReaderBufferThresholdKb());
  650.                     }
  651.                     else{
  652.                         pr = factory.createMessage(messageType, MessageRole.REQUEST, contentType,
  653.                                 bin, notifierInputStreamParams, openSPCoopProperties.getAttachmentsProcessingMode());
  654.                     }
  655.                     if(pr.getParseException()!=null){
  656.                         context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION, pr.getParseException());
  657.                     }
  658.                     msgRequest = pr.getMessage_throwParseException();
  659.                     msgRequest.setTransportRequestContext(urlProtocolContext);
  660.                 }catch(Exception e){
  661.                    
  662.                     Throwable tParsing = null;
  663.                     ParseException parseException = null;
  664.                     if(context.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION)){
  665.                         parseException = (ParseException) context.getPddContext().removeObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  666.                         if(parseException!=null) {
  667.                             tParsing = parseException.getParseException();
  668.                         }
  669.                     }
  670.                     if(tParsing==null){
  671.                         tParsing = ParseExceptionUtils.getParseException(e);
  672.                     }
  673.                     if(tParsing==null){
  674.                         tParsing = e;
  675.                     }
  676.                    
  677.                     String msgErrore = tParsing.getMessage();
  678.                     if(msgErrore==null){
  679.                         msgErrore = tParsing.toString();
  680.                     }
  681.                    
  682.                     context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  683.                    
  684.                     ConfigurazionePdDManager configurazionePdDReader = ConfigurazionePdDManager.getInstance();
  685.                     DumpConfigurazione dumpConfig = null;
  686.                     if(portaDelegata!=null) {                          
  687.                         IDPortaDelegata identificativoPortaDelegata = new IDPortaDelegata();
  688.                         identificativoPortaDelegata.setNome(portaDelegata);
  689.                         PortaDelegata portaDelegataObject = configurazionePdDReader.getPortaDelegataSafeMethod(identificativoPortaDelegata, requestInfo);
  690.                         if(portaDelegataObject!=null) {
  691.                             dumpConfig = configurazionePdDReader.getDumpConfigurazione(portaDelegataObject);
  692.                         }
  693.                     }
  694.                     if(dumpConfig==null) {
  695.                         dumpConfig = ConfigurazionePdDManager.getInstance().getDumpConfigurazionePortaDelegata();
  696.                     }
  697.                    
  698.                     Dump dumpApplicativo = new Dump(openSPCoopProperties.getIdentitaPortaDefault(protocolFactory.getProtocol(), requestInfo),
  699.                             IntegrationManager.ID_MODULO,TipoPdD.DELEGATA,portaDelegata,context.getPddContext(),
  700.                             null,null,
  701.                             dumpConfig);
  702.                     dumpApplicativo.dumpRichiestaIngressoByIntegrationManagerError(msg.getMessage(),urlProtocolContext);
  703.                             //IntegrationManager.buildInfoConnettoreIngresso(req, credenziali, urlProtocolContext));
  704.                    
  705.                     IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_REQUEST_CONTENT;
  706.                     if( parseException!=null && parseException.getSourceException()!=null &&
  707.                             TimeoutIOException.isTimeoutIOException(parseException.getSourceException())) {
  708.                         integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  709.                     }
  710.                     else if( parseException!=null && parseException.getSourceException()!=null &&
  711.                             LimitExceededIOException.isLimitExceededIOException(parseException.getSourceException())) {
  712.                         integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  713.                     }
  714.                    
  715.                     if(msg.getImbustamento()==false){
  716.                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  717.                         msgDiag.logPersonalizzato("buildMsg.nonRiuscito");
  718.                         throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_421_MSG_SOAP_NON_COSTRUIBILE_TRAMITE_RICHIESTA_APPLICATIVA.
  719.                                 getErrore421_MessaggioSOAPNonGenerabile(msgErrore),
  720.                                 integrationFunctionError, erroriProperties);
  721.                     } else {
  722.                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  723.                         msgDiag.logPersonalizzato("buildMsg.imbustamentoSOAP.nonRiuscito");
  724.                         throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_422_IMBUSTAMENTO_SOAP_NON_RIUSCITO_RICHIESTA_APPLICATIVA.
  725.                                 getErrore422_MessaggioSOAPNonGenerabileTramiteImbustamentoSOAP(msgErrore),
  726.                                 integrationFunctionError, erroriProperties);
  727.                     }
  728.                 }
  729.             }
  730.             Utilities.printFreeMemory("IntegrationManager - Post costruzione richiesta");
  731.             if(msgRequest!=null) {
  732.                 msgRequest.setProtocolName(protocolFactory.getProtocol());
  733.                 msgRequest.setTransactionId( idTransazione);
  734.                 Object nomePortaInvocataObject = context.getPddContext().getObject(CostantiPdD.NOME_PORTA_INVOCATA);
  735.                 if(nomePortaInvocataObject!=null && nomePortaInvocataObject instanceof String) {
  736.                     msgRequest.addContextProperty(CostantiPdD.NOME_PORTA_INVOCATA, (String) nomePortaInvocataObject );
  737.                 }
  738.             }

  739.            


  740.             //  Costruisco HeaderIntegrazione IntegrationManager
  741.             HeaderIntegrazione headerIntegrazioneRichiesta = new HeaderIntegrazione(idTransazione);


  742.             // Identificazione Porta Delegata INPUT-BASED
  743.             ProtocolHeaderInfo protocolHeaderInfo = msg.getProtocolHeaderInfo();
  744.             if(protocolHeaderInfo!=null){

  745.                 if(protocolHeaderInfo.getTipoMittente()!=null && (!"".equals(protocolHeaderInfo.getTipoMittente())))
  746.                     headerIntegrazioneRichiesta.getBusta().setTipoMittente(protocolHeaderInfo.getTipoMittente());
  747.                 if(protocolHeaderInfo.getMittente()!=null && (!"".equals(protocolHeaderInfo.getMittente())))
  748.                     headerIntegrazioneRichiesta.getBusta().setMittente(protocolHeaderInfo.getMittente());

  749.                 if(protocolHeaderInfo.getTipoDestinatario()!=null && (!"".equals(protocolHeaderInfo.getTipoDestinatario())))
  750.                     headerIntegrazioneRichiesta.getBusta().setTipoDestinatario(protocolHeaderInfo.getTipoDestinatario());
  751.                 if(protocolHeaderInfo.getDestinatario()!=null && (!"".equals(protocolHeaderInfo.getDestinatario())))
  752.                     headerIntegrazioneRichiesta.getBusta().setDestinatario(protocolHeaderInfo.getDestinatario());

  753.                 if(protocolHeaderInfo.getTipoServizio()!=null && (!"".equals(protocolHeaderInfo.getTipoServizio())))
  754.                     headerIntegrazioneRichiesta.getBusta().setTipoServizio(protocolHeaderInfo.getTipoServizio());
  755.                 if(protocolHeaderInfo.getServizio()!=null && (!"".equals(protocolHeaderInfo.getServizio())))
  756.                     headerIntegrazioneRichiesta.getBusta().setServizio(protocolHeaderInfo.getServizio());

  757.                 if(protocolHeaderInfo.getAzione()!=null && (!"".equals(protocolHeaderInfo.getAzione())))
  758.                     headerIntegrazioneRichiesta.getBusta().setAzione(protocolHeaderInfo.getAzione());

  759.                 if(protocolHeaderInfo.getID()!=null && (!"".equals(protocolHeaderInfo.getID())))
  760.                     headerIntegrazioneRichiesta.getBusta().setID(protocolHeaderInfo.getID());

  761.                 if(protocolHeaderInfo.getIdCollaborazione()!=null && (!"".equals(protocolHeaderInfo.getIdCollaborazione())))
  762.                     headerIntegrazioneRichiesta.getBusta().setIdCollaborazione(protocolHeaderInfo.getIdCollaborazione());

  763.                 if(protocolHeaderInfo.getRiferimentoMessaggio()!=null && (!"".equals(protocolHeaderInfo.getRiferimentoMessaggio())))
  764.                     headerIntegrazioneRichiesta.getBusta().setRiferimentoMessaggio(protocolHeaderInfo.getRiferimentoMessaggio());
  765.             }
  766.             if(msg.getIdApplicativo()!=null && (!"".equals(msg.getIdApplicativo())))
  767.                 headerIntegrazioneRichiesta.setIdApplicativo(msg.getIdApplicativo());
  768.             if(msg.getServizioApplicativo()!=null && (!"".equals(msg.getServizioApplicativo())))
  769.                 headerIntegrazioneRichiesta.setServizioApplicativo(msg.getServizioApplicativo());

  770.             //  Contesto di Richiesta
  771.             context.setTipoPorta(TipoPdD.DELEGATA);
  772.             context.setCredenziali(credenziali);
  773.             context.setIdModulo(idModulo);
  774.             context.setGestioneRisposta(true); // siamo in un webServices, la risposta deve essere aspettata
  775.             context.setInvocazionePDPerRiferimento(idInvocazionePerRiferimento!=null);
  776.             context.setIdInvocazionePDPerRiferimento(idInvocazionePerRiferimento);
  777.             context.setMessageRequest(msgRequest);
  778.             context.setUrlProtocolContext(urlProtocolContext);
  779.             context.setHeaderIntegrazioneRichiesta(headerIntegrazioneRichiesta);
  780.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  781.             context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO, requestInfo);
  782.             context.setProprietaErroreAppl(generatoreErrore.getProprietaErroreAppl());
  783.             if(context.getMsgDiagnostico()==null) {
  784.                 context.setMsgDiagnostico(msgDiag);
  785.             }
  786.            
  787.            
  788.             /* --------------- SecurityToken --------------- */
  789.             try {
  790.                 if(requestInfo!=null && requestInfo.getProtocolContext()!=null && requestInfo.getProtocolContext().getCredential()!=null &&
  791.                         requestInfo.getProtocolContext().getCredential().getCertificate()!=null &&
  792.                         requestInfo.getProtocolContext().getCredential().getCertificate().getCertificate()!=null) {
  793.                     SecurityTokenUtilities.newSecurityToken(context.getPddContext());
  794.                 }
  795.             }catch(Exception e){
  796.                 logCore.error("Costruzione SecurityToken non riuscito: "+e.getMessage(),e);
  797.             }
  798.            
  799.             // Log elaborazione dati completata
  800.             msgDiag.logPersonalizzato("ricezioneRichiesta.elaborazioneDati.completata");
  801.            
  802.             // Invocazione...
  803.             RicezioneContenutiApplicativi gestoreRichiesta = new RicezioneContenutiApplicativi(context,generatoreErrore);
  804.             gestoreRichiesta.process(req);
  805.             msgResponse = context.getMessageResponse();
  806.             if(context.getMsgDiagnostico()!=null){
  807.                 msgDiag = context.getMsgDiagnostico();
  808.                 // Aggiorno informazioni
  809.                 msgDiag.addKeyword(CostantiPdD.KEY_TIPO_OPERAZIONE_IM, tipoOperazione);
  810.             }

  811.             // Check parsing request
  812.             if((msgRequest!=null && msgRequest.getParseException() != null) ||
  813.                     (context.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION))){
  814.            
  815.                 // Senno l'esito viene forzato essere 5XX
  816.                 try{
  817.                     esito = protocolFactory.createEsitoBuilder().getEsito(urlProtocolContext,EsitoTransazioneName.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO);
  818.                 }catch(Exception eBuildError){
  819.                     esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  820.                 }
  821.                
  822.                 context.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO, true);
  823.                 ParseException parseException = null;
  824.                 if( msgRequest!=null && msgRequest.getParseException() != null ){
  825.                     parseException = msgRequest.getParseException();
  826.                 }
  827.                 else{
  828.                     parseException = (ParseException) context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  829.                 }
  830.                 String msgErrore = null;
  831.                 if(parseException!=null && parseException.getParseException()!=null) {
  832.                     msgErrore = parseException.getParseException().getMessage();
  833.                     if(msgErrore==null){
  834.                         msgErrore = parseException.getParseException().toString();
  835.                     }
  836.                 }  
  837.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  838.                 if(parseException!=null) {
  839.                     logCore.error("parsingExceptionRichiesta",parseException.getSourceException());
  840.                 }
  841. //              msgDiag.logPersonalizzato("parsingExceptionRichiesta");
  842. //              throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_432_PARSING_EXCEPTION_RICHIESTA.
  843. //                      getErrore432_MessaggioRichiestaMalformato(parseException.getParseException()));
  844.                 // Per l'IntegrationManager esiste un codice specifico
  845.                
  846.                 IntegrationFunctionError integrationFunctionError = IntegrationFunctionError.UNPROCESSABLE_REQUEST_CONTENT;
  847.                 if( parseException!=null && parseException.getSourceException()!=null &&
  848.                         TimeoutIOException.isTimeoutIOException(parseException.getSourceException())) {
  849.                     integrationFunctionError = IntegrationFunctionError.REQUEST_TIMED_OUT;
  850.                 }
  851.                 else if( parseException!=null && parseException.getSourceException()!=null &&
  852.                         LimitExceededIOException.isLimitExceededIOException(parseException.getSourceException())) {
  853.                     integrationFunctionError = IntegrationFunctionError.REQUEST_SIZE_EXCEEDED;
  854.                 }
  855.                
  856.                 msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INTEGRATION_MANAGER,"buildMsg.nonRiuscito");
  857.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_421_MSG_SOAP_NON_COSTRUIBILE_TRAMITE_RICHIESTA_APPLICATIVA.
  858.                         getErrore421_MessaggioSOAPNonGenerabile(msgErrore),
  859.                         integrationFunctionError, erroriProperties);
  860.             }
  861.            
  862.             // Raccolgo l'eventuale header di integrazione
  863.             Map<String, List<String>> headerIntegrazioneRisposta = context.getResponseHeaders();
  864.             ProtocolHeaderInfo protocolHeaderInfoResponse = null;
  865.             if(headerIntegrazioneRisposta!=null){
  866.                 Map<MapKey<String>,String> keyValue = openSPCoopProperties.getKeyValue_HeaderIntegrazioneTrasporto();
  867.                 protocolHeaderInfoResponse = new ProtocolHeaderInfo();

  868.                 protocolHeaderInfoResponse.setID(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_ID_MESSAGGIO)));
  869.                 protocolHeaderInfoResponse.setRiferimentoMessaggio(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_RIFERIMENTO_MESSAGGIO)));
  870.                 protocolHeaderInfoResponse.setIdCollaborazione(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_COLLABORAZIONE)));

  871.                 protocolHeaderInfoResponse.setMittente(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_MITTENTE)));
  872.                 protocolHeaderInfoResponse.setTipoMittente(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_TIPO_MITTENTE)));

  873.                 protocolHeaderInfoResponse.setDestinatario(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_DESTINATARIO)));
  874.                 protocolHeaderInfoResponse.setTipoDestinatario(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_TIPO_DESTINATARIO)));

  875.                 protocolHeaderInfoResponse.setServizio(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_SERVIZIO)));
  876.                 protocolHeaderInfoResponse.setTipoServizio(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_TIPO_SERVIZIO)));

  877.                 protocolHeaderInfoResponse.setAzione(TransportUtils.getFirstValue(headerIntegrazioneRisposta,keyValue.get(CostantiPdD.HEADER_INTEGRAZIONE_AZIONE)));
  878.             }

  879.             InformazioniErroriInfrastrutturali informazioniErrori = ServicesUtils.readInformazioniErroriInfrastrutturali(context.getPddContext());
  880.            
  881.             //  IntepretazioneRisposta
  882.             if(msgResponse!=null){
  883.                
  884.                 esito = protocolFactory.createEsitoBuilder().getEsito(urlProtocolContext,
  885.                         200, requestInfo.getIntegrationServiceBinding(),
  886.                          msgResponse,
  887.                         context.getProprietaErroreAppl(), informazioniErrori,
  888.                         context.getPddContext()!=null ? context.getPddContext() : null);            
  889.                                                
  890.                 IntegrationManagerException exc = null;
  891.                 try{
  892.                     if(ServiceBinding.SOAP.equals(msgResponse.getServiceBinding())){
  893.                         OpenSPCoop2SoapMessage soapMessage = msgResponse.castAsSoap();
  894.                         if(soapMessage.hasSOAPFault()){
  895.    
  896.                             descrizioneSoapFault = " ("+SoapUtils.safe_toString(soapMessage.getFactory(), soapMessage.getSOAPBody().getFault(), false, logCore)+")";
  897.                            
  898.                             // Potenziale MsgErroreApplicativo
  899.                             SOAPFault fault = soapMessage.getSOAPBody().getFault();
  900.                             ProprietaErroreApplicativo pea = context.getProprietaErroreAppl();
  901.                             if(pea!=null && fault.getFaultActor()!=null && fault.getFaultActor().equals(pea.getFaultActor())){
  902.                                 String prefix = org.openspcoop2.protocol.basic.Costanti.ERRORE_INTEGRAZIONE_PREFIX_CODE;
  903.                                 if(context.getProprietaErroreAppl().getFaultPrefixCode()!=null){
  904.                                     prefix = context.getProprietaErroreAppl().getFaultPrefixCode();
  905.                                 }
  906.                                
  907.                                 String faultCode = null;
  908.                                 if(fault.getFaultCodeAsQName()!=null) {
  909.                                     faultCode = fault.getFaultCodeAsQName().getLocalPart();
  910.                                 }
  911.                                 else {
  912.                                     faultCode = fault.getFaultCode();
  913.                                 }
  914.                                 exc = IntegrationManagerUtility.mapMessageIntoProtocolException(soapMessage, faultCode, fault.getFaultString(),
  915.                                                 requestInfo.getIdentitaPdD(), idModulo);
  916.                                 if(exc==null) {// non si dovrebbe arrivare a questo if
  917.                                     if(openSPCoopProperties.isErroreApplicativoIntoDetails() && fault.getDetail()!=null){
  918.                                         exc = IntegrationManagerUtility.mapXMLIntoProtocolException(protocolFactory,fault.getDetail().getFirstChild(),
  919.                                                 prefix,
  920.                                                 IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  921.                                     }else{
  922.                                         exc = IntegrationManagerUtility.mapXMLIntoProtocolException(protocolFactory,fault.getFaultString(),
  923.                                                 prefix,
  924.                                                 IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  925.                                     }
  926.                                 }
  927.                                 if(exc== null)
  928.                                     throw new Exception("Costruzione Eccezione fallita: null");
  929.                             }
  930.                         }
  931.                     }
  932.                 }catch(Exception e){
  933.                     try{
  934.                         if( (msgResponse!=null && msgResponse.getParseException() != null) ||
  935.                                 (context.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION))){
  936.                             informazioniErrori.setContenutoRispostaNonRiconosciuto(true);
  937.                             ParseException parseException = null;
  938.                             if( msgResponse!=null && msgResponse.getParseException() != null ){
  939.                                 parseException = msgResponse.getParseException();
  940.                             }
  941.                             else{
  942.                                 parseException = (ParseException) context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  943.                             }
  944.                             String msgErrore = parseException.getParseException().getMessage();
  945.                             if(msgErrore==null){
  946.                                 msgErrore = parseException.getParseException().toString();
  947.                             }
  948.                             msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  949.                             logCore.error("parsingExceptionRisposta",parseException.getSourceException());
  950.                             msgDiag.logPersonalizzato("parsingExceptionRisposta");
  951.                             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_440_PARSING_EXCEPTION_RISPOSTA.
  952.                                     getErrore440_MessaggioRispostaMalformato(parseException.getParseException()),
  953.                                     IntegrationFunctionError.UNPROCESSABLE_RESPONSE_CONTENT, erroriProperties);
  954.                         }
  955.                         else{
  956.                             msgDiag.logErroreGenerico(e,"buildProtocolException("+tipoOperazione+")");
  957.                             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  958.                                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_524_CREAZIONE_PROTOCOL_EXCEPTION),
  959.                                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  960.                         }
  961.                     }finally{
  962.                         // ricalcolo esito
  963.                         esito = protocolFactory.createEsitoBuilder().getEsito(urlProtocolContext,
  964.                                 500, requestInfo.getIntegrationServiceBinding(),
  965.                                 msgResponse,
  966.                                 context.getProprietaErroreAppl(), informazioniErrori,
  967.                                 (context.getPddContext()!=null ? context.getPddContext() : null));      
  968.                     }
  969.                 }  
  970.                 if(exc!=null){
  971.                     throw exc;
  972.                 }

  973.                 // Se non ho lanciato l'eccezione, costruisco una risposta
  974.                 try{
  975.                     msgReturn = new IntegrationManagerMessage(msgResponse,false);
  976.                 }catch(Exception e){
  977.                     try{
  978.                         if( (msgResponse!=null && msgResponse.getParseException() != null) ||
  979.                                 (context.getPddContext().containsKey(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION))){
  980.                             informazioniErrori.setContenutoRispostaNonRiconosciuto(true);
  981.                             ParseException parseException = null;
  982.                             if( msgResponse!=null && msgResponse.getParseException() != null ){
  983.                                 parseException = msgResponse.getParseException();
  984.                             }
  985.                             else{
  986.                                 parseException = (ParseException) context.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO_PARSE_EXCEPTION);
  987.                             }
  988.                             String msgErrore = parseException.getParseException().getMessage();
  989.                             if(msgErrore==null){
  990.                                 msgErrore = parseException.getParseException().toString();
  991.                             }
  992.                             msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, msgErrore);
  993.                             logCore.error("parsingExceptionRisposta",parseException.getSourceException());
  994.                             msgDiag.logPersonalizzato("parsingExceptionRisposta");
  995.                             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_440_PARSING_EXCEPTION_RISPOSTA.
  996.                                     getErrore440_MessaggioRispostaMalformato(parseException.getParseException()),
  997.                                     IntegrationFunctionError.UNPROCESSABLE_RESPONSE_CONTENT, erroriProperties);
  998.                         }
  999.                         else{
  1000.                             msgDiag.logErroreGenerico(e,"buildMessage_response("+tipoOperazione+")");
  1001.                             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1002.                                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_523_CREAZIONE_PROTOCOL_MESSAGE),
  1003.                                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  1004.                         }
  1005.                     }finally{
  1006.                         // ricalcolo esito
  1007.                         esito = protocolFactory.createEsitoBuilder().getEsito(urlProtocolContext,
  1008.                                 500, requestInfo.getIntegrationServiceBinding(),
  1009.                                 msgResponse,
  1010.                                 context.getProprietaErroreAppl(), informazioniErrori,
  1011.                                 (context.getPddContext()!=null ?context.getPddContext() : null));      
  1012.                     }
  1013.                 }
  1014.                
  1015.                 msgDiag.addKeyword(CostantiPdD.KEY_SOAP_FAULT, descrizioneSoapFault);
  1016.                 msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_CONTENUTI_APPLICATIVI,"integrationManager.consegnaRispostaApplicativaEffettuata");
  1017.                
  1018.             }else{
  1019.                 /*
  1020.                 // Con la nuova versione di RicezioneContenutiApplicativi, in caso di oneway non viene ritornato un messaggio SOAP empty, ma proprio null
  1021.                 // Una risposta deve esistere per forza.
  1022.                 msgDiag.logErroreGenerico("Risposta non presente","gestioneRisposta("+tipoOperazione+")");
  1023.                 throw new IntegrationManagerException(CostantiPdD.CODICE_511_READ_RESPONSE_MSG,
  1024.                         CostantiPdD.MSG_5XX_SISTEMA_NON_DISPONIBILE);
  1025.                 */
  1026.                 msgReturn = new IntegrationManagerMessage();
  1027.                
  1028.                 esito = protocolFactory.createEsitoBuilder().getEsito(urlProtocolContext,
  1029.                         200, requestInfo.getIntegrationServiceBinding(),
  1030.                         msgResponse,
  1031.                         context.getProprietaErroreAppl(), informazioniErrori,
  1032.                         (context.getPddContext()!=null ? context.getPddContext() : null));  
  1033.                 // ok oneway
  1034.                
  1035.                 msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_CONTENUTI_APPLICATIVI,"integrationManager.consegnaRispostaApplicativaVuota");
  1036.             }      

  1037.             msgReturn.setProtocolHeaderInfo(protocolHeaderInfoResponse);
  1038.            
  1039.             if(dumpRaw!=null && dumpRaw.isActiveDump()){
  1040.                 String contentTypeRisposta = "text/xml"; // per ora e' cablato.
  1041.                 String rawMessage = null;
  1042.                 Integer contentLengthRisposta = null;
  1043.                 if(msgReturn.getMessage()!=null){
  1044.                     try{
  1045.                         contentLengthRisposta = msgReturn.getMessage().length;
  1046.                         rawMessage = new String(msgReturn.getMessage());
  1047.                     }catch(Throwable t){
  1048.                         logCore.error("Dump error: "+t.getMessage(),t);
  1049.                     }
  1050.                 }
  1051.                 dumpRaw.serializeResponse(rawMessage, null, null, contentLengthRisposta, contentTypeRisposta, 200);
  1052.             }
  1053.            
  1054.             return msgReturn;
  1055.            
  1056.         }catch(Exception e){
  1057.            
  1058.             if(dumpRaw!=null && dumpRaw.isActiveDump()){
  1059.                 String contentTypeRisposta = "text/xml"; // per ora e' cablato.
  1060.                 String rawMessage = "[Exception "+e.getClass().getName()+"]: "+ e.getMessage(); // Non riesco ad avere il marshal xml della risposta ritornata
  1061.                 Integer contentLengthRisposta = null;
  1062.                 dumpRaw.serializeResponse(rawMessage, null,null, contentLengthRisposta, contentTypeRisposta, 500);
  1063.             }
  1064.            
  1065.             errore = e.getMessage();
  1066.             msgDiag.addKeyword(CostantiPdD.KEY_SOAP_FAULT, descrizioneSoapFault);
  1067.            
  1068.             // Controllo Eccezioni
  1069.             if(e instanceof IntegrationManagerException){
  1070.                 // Lanciata all'interno del metodo
  1071.                
  1072.                 if(esito==null){
  1073.                     // Altrimenti l'esito era settato
  1074.                     try{
  1075.                         esito = protocolFactory.createEsitoBuilder().getEsito(urlProtocolContext,EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX);
  1076.                     }catch(Exception eBuildError){
  1077.                         esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1078.                     }
  1079.                 }
  1080.                
  1081.                 IntegrationManagerException eSPC = (IntegrationManagerException)e;
  1082.                 //String prefix = eSPC.getProprietaErroreApplicativo().getFaultPrefixCode();
  1083.                 //boolean isFaultAsGenericCode = eSPC.getProprietaErroreApplicativo().isFaultAsGenericCode();
  1084.                 if(descrizioneSoapFault!=null && !"".equals(descrizioneSoapFault)){
  1085.                     // stesse informazioni presenti gia nel fault
  1086.                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_CONSEGNA,"ProtocolException/"+eSPC.getCodiceEccezione());
  1087.                 }else{
  1088.                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_CONSEGNA,"ProtocolException/"+eSPC.getCodiceEccezione() + " " + eSPC.getDescrizioneEccezione());
  1089.                 }
  1090.                 msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_CONTENUTI_APPLICATIVI,"integrationManager.consegnaRispostaApplicativaFallita");
  1091.                
  1092.                 throw eSPC;
  1093.             }else{
  1094.                 msgDiag.logErroreGenerico(e,"invocaPortaDelegata("+tipoOperazione+")");
  1095.                 try{
  1096.                     esito = protocolFactory.createEsitoBuilder().getEsito(urlProtocolContext,EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX);
  1097.                 }catch(Exception eBuildError){
  1098.                     esito = EsitoTransazione.ESITO_TRANSAZIONE_ERROR;
  1099.                 }
  1100.                
  1101.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_CONSEGNA,errore);
  1102.                 msgDiag.logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_CONTENUTI_APPLICATIVI,"integrationManager.consegnaRispostaApplicativaFallita");
  1103.                
  1104.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),
  1105.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, erroriProperties);
  1106.             }
  1107.            
  1108.         }finally{
  1109.            
  1110.             try{
  1111.                 if(stato!=null)
  1112.                     stato.releaseResource();
  1113.             }catch(Exception eClose){}
  1114.            
  1115.            
  1116.            
  1117.            
  1118.             // *** Chiudo connessione verso PdD Destinazione per casi stateless ***
  1119.             String location = "...";
  1120.             try{
  1121.                 IConnettore c = null;
  1122.                 //if(context!=null && context.getIdMessage()!=null){
  1123.                 if(idTransazione!=null) {
  1124.                     c = RepositoryConnettori.removeConnettorePD(
  1125.                             //context.getIdMessage()
  1126.                             idTransazione);
  1127.                 }
  1128.                 if(c!=null){
  1129.                     location = c.getLocation();
  1130.                     c.disconnect();
  1131.                 }
  1132.             }catch(Exception e){
  1133.                 msgDiag.logDisconnectError(e, location);
  1134.             }
  1135.            
  1136.            
  1137.            
  1138.            
  1139.             /* ------------  PostOutResponseHandler ------------- */
  1140.             PostOutResponseContext postOutResponseContext = new PostOutResponseContext(logCore, protocolFactory);
  1141.             try{
  1142.                 context.getPddContext().addObject(CostantiPdD.DATA_ACCETTAZIONE_RICHIESTA, dataAccettazioneRichiesta);
  1143.                 if(dataIngressoRichiesta!=null){
  1144.                     context.getPddContext().addObject(CostantiPdD.DATA_INGRESSO_RICHIESTA, dataIngressoRichiesta);
  1145.                 }
  1146.                 postOutResponseContext.setPddContext(context.getPddContext());
  1147.                 postOutResponseContext.setDataElaborazioneMessaggio(DateManager.getDate());
  1148.                 postOutResponseContext.setDataPrimaSpedizioneRisposta(DateManager.getDate());
  1149.                 postOutResponseContext.setDataRispostaSpedita(DateManager.getDate());
  1150.                 postOutResponseContext.setEsito(esito);
  1151.                 postOutResponseContext.setMessaggio(msgResponse);
  1152.                
  1153.                 if(msgRequest!=null){
  1154.                     postOutResponseContext.setInputRequestMessageSize(msgRequest.getIncomingMessageContentLength());
  1155.                     postOutResponseContext.setOutputRequestMessageSize(msgRequest.getOutgoingMessageContentLength());
  1156.                 }else{
  1157.                     if(msg!=null && msg.getMessage()!=null)
  1158.                         postOutResponseContext.setInputRequestMessageSize(Long.valueOf(msg.getMessage().length));
  1159.                 }
  1160.                 if(msgResponse!=null){
  1161.                     postOutResponseContext.setInputResponseMessageSize(msgResponse.getIncomingMessageContentLength());
  1162.                     if(msgReturn!=null && msgReturn.getMessage()!=null)
  1163.                         postOutResponseContext.setOutputResponseMessageSize(Long.valueOf(msgReturn.getMessage().length));
  1164.                 }
  1165.                
  1166.                 if(errore!=null){
  1167.                     postOutResponseContext.setReturnCode(500);
  1168.                 }else{
  1169.                     postOutResponseContext.setReturnCode(200);
  1170.                 }
  1171. //              if(context!=null){
  1172.                 if(context.getTipoPorta()!=null)
  1173.                     postOutResponseContext.setTipoPorta(context.getTipoPorta());
  1174.                 else
  1175.                     postOutResponseContext.setTipoPorta(TipoPdD.DELEGATA);
  1176.                 postOutResponseContext.setProtocollo(context.getProtocol());
  1177.                 postOutResponseContext.setIntegrazione(context.getIntegrazione());
  1178. //              }else{
  1179. //                  postOutResponseContext.setTipoPorta(TipoPdD.DELEGATA);
  1180. //              }
  1181.                 postOutResponseContext.setIdModulo(idModulo);
  1182.                                
  1183.             }catch(Exception e){
  1184.                 msgDiag.logErroreGenerico(e,"postOutResponse, preparazione contesto");
  1185.             }
  1186.            
  1187.             GestoreHandlers.postOutResponse(postOutResponseContext, msgDiag, logCore);
  1188.         }
  1189.     }
  1190.    
  1191. }