LocalForwardEngine.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.pdd.core;

  21. import java.util.ArrayList;
  22. import java.util.Iterator;
  23. import java.util.List;

  24. import javax.xml.transform.dom.DOMSource;

  25. import org.openspcoop2.core.config.PortaApplicativa;
  26. import org.openspcoop2.core.config.PortaDelegata;
  27. import org.openspcoop2.core.config.ServizioApplicativo;
  28. import org.openspcoop2.core.config.driver.DriverConfigurazioneNotFound;
  29. import org.openspcoop2.core.constants.TipoPdD;
  30. import org.openspcoop2.core.id.IDPortaApplicativa;
  31. import org.openspcoop2.core.id.IDServizio;
  32. import org.openspcoop2.core.id.IDServizioApplicativo;
  33. import org.openspcoop2.core.id.IDSoggetto;
  34. import org.openspcoop2.message.OpenSPCoop2Message;
  35. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  36. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  37. import org.openspcoop2.message.constants.MessageRole;
  38. import org.openspcoop2.message.exception.ParseException;
  39. import org.openspcoop2.message.utils.MessageUtilities;
  40. import org.openspcoop2.message.xml.MessageXMLUtils;
  41. import org.openspcoop2.pdd.config.MTOMProcessorConfig;
  42. import org.openspcoop2.pdd.config.MessageSecurityConfig;
  43. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  44. import org.openspcoop2.pdd.config.RichiestaApplicativa;
  45. import org.openspcoop2.pdd.config.RichiestaDelegata;
  46. import org.openspcoop2.pdd.core.behaviour.Behaviour;
  47. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  48. import org.openspcoop2.pdd.core.handlers.HandlerException;
  49. import org.openspcoop2.pdd.core.state.OpenSPCoopState;
  50. import org.openspcoop2.pdd.core.transazioni.Transaction;
  51. import org.openspcoop2.pdd.core.transazioni.TransactionContext;
  52. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  53. import org.openspcoop2.pdd.mdb.Imbustamento;
  54. import org.openspcoop2.pdd.mdb.SbustamentoRisposte;
  55. import org.openspcoop2.pdd.services.ServicesUtils;
  56. import org.openspcoop2.pdd.services.error.AbstractErrorGenerator;
  57. import org.openspcoop2.pdd.services.error.RicezioneBusteExternalErrorGenerator;
  58. import org.openspcoop2.pdd.services.error.RicezioneContenutiApplicativiInternalErrorGenerator;
  59. import org.openspcoop2.protocol.engine.constants.Costanti;
  60. import org.openspcoop2.protocol.sdk.Busta;
  61. import org.openspcoop2.protocol.sdk.Eccezione;
  62. import org.openspcoop2.protocol.sdk.SecurityInfo;
  63. import org.openspcoop2.protocol.sdk.builder.ProprietaErroreApplicativo;
  64. import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
  65. import org.openspcoop2.protocol.sdk.constants.CodiceErroreIntegrazione;
  66. import org.openspcoop2.protocol.sdk.constants.ErroreIntegrazione;
  67. import org.openspcoop2.protocol.sdk.constants.ErroriCooperazione;
  68. import org.openspcoop2.protocol.sdk.constants.ErroriIntegrazione;
  69. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  70. import org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione;
  71. import org.openspcoop2.protocol.sdk.constants.RuoloMessaggio;
  72. import org.openspcoop2.protocol.sdk.state.IState;
  73. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  74. import org.openspcoop2.protocol.sdk.validator.IValidazioneSemantica;
  75. import org.openspcoop2.security.message.MessageSecurityContext;
  76. import org.openspcoop2.security.message.MessageSecurityContextParameters;
  77. import org.openspcoop2.security.message.SubErrorCodeSecurity;
  78. import org.openspcoop2.security.message.constants.SecurityConstants;
  79. import org.openspcoop2.security.message.engine.MessageSecurityFactory;
  80. import org.openspcoop2.utils.Utilities;
  81. import org.openspcoop2.utils.date.DateManager;
  82. import org.openspcoop2.utils.date.DateUtils;
  83. import org.openspcoop2.utils.digest.IDigestReader;
  84. import org.openspcoop2.utils.transport.http.HttpConstants;
  85. import org.w3c.dom.Node;

  86. /**
  87.  * LocalForwardEngine
  88.  *
  89.  * @author Poli Andrea (apoli@link.it)
  90.  * @author $Author$
  91.  * @version $Rev$, $Date$
  92.  */
  93. public class LocalForwardEngine {

  94.     private LocalForwardParameter localForwardParameter;
  95.     private EJBUtils ejbUtils = null;
  96.     private RicezioneContenutiApplicativiInternalErrorGenerator generatoreErrorePortaDelegata = null;
  97.     private RicezioneBusteExternalErrorGenerator generatoreErrorePortaApplicativa = null;
  98.     private Busta busta = null;
  99.     private IDPortaApplicativa idPA = null;
  100.     private PortaApplicativa pa = null;
  101.     private RichiestaApplicativa richiestaApplicativa = null;
  102.     private RichiestaDelegata richiestaDelegata = null;
  103.     private PortaDelegata pd =null;
  104.     private ServizioApplicativo sa = null;
  105.     private OpenSPCoop2Properties propertiesReader = null;
  106.     private RequestInfo requestInfo = null;
  107.     private IntegrationFunctionError _integrationFunctionError;
  108.     private IntegrationFunctionError getIntegrationFunctionError(PdDContext pddContext) {
  109.         if(this._integrationFunctionError!=null) {
  110.             return this._integrationFunctionError;
  111.         }
  112.         else {
  113.             return AbstractErrorGenerator.getIntegrationInternalError(pddContext); // default
  114.         }
  115.     }
  116.    
  117.    
  118.     /* ***** COSTRUTTORE ******** */
  119.    
  120.     public LocalForwardEngine(LocalForwardParameter localForwardParameter) throws LocalForwardException{
  121.         this.localForwardParameter = localForwardParameter;
  122.         try{
  123.            
  124.             this.propertiesReader = OpenSPCoop2Properties.getInstance();
  125.            
  126.             this.richiestaDelegata = this.localForwardParameter.getRichiestaDelegata();
  127.             this.richiestaApplicativa = this.localForwardParameter.getRichiestaApplicativa();
  128.            
  129.             ((OpenSPCoopState)this.localForwardParameter.getOpenspcoopstate()).setIDMessaggioSessione(this.localForwardParameter.getIdRequest());
  130.             IState state = ((OpenSPCoopState)this.localForwardParameter.getOpenspcoopstate()).getStatoRichiesta();
  131.            
  132.             String profiloGestione = null;
  133.             IDSoggetto soggettoFruitore = null;
  134.             IDServizio idServizio = null;
  135.             ProprietaErroreApplicativo fault = null;
  136.             String servizioApplicativo = null;
  137.             String scenarioCooperazione = null;
  138.             if(this.richiestaApplicativa!=null){
  139.                 profiloGestione = this.richiestaApplicativa.getProfiloGestione();
  140.                 soggettoFruitore = this.richiestaApplicativa.getSoggettoFruitore();
  141.                 idServizio = this.richiestaApplicativa.getIDServizio();
  142.                 fault = null;
  143.                 servizioApplicativo = this.richiestaApplicativa.getServizioApplicativo();
  144.                 scenarioCooperazione = this.richiestaApplicativa.getScenario();
  145.                
  146.                 this.idPA = this.richiestaApplicativa.getIdPortaApplicativa();
  147.                
  148.                 this.busta = this.localForwardParameter.getBusta();
  149.                                
  150.             }else{
  151.                 profiloGestione = this.richiestaDelegata.getProfiloGestione();
  152.                 soggettoFruitore = this.richiestaDelegata.getIdSoggettoFruitore();
  153.                 idServizio = this.richiestaDelegata.getIdServizio();
  154.                 fault = this.richiestaDelegata.getFault();
  155.                 servizioApplicativo = this.richiestaDelegata.getServizioApplicativo();
  156.                 if(ProfiloDiCollaborazione.ONEWAY.equals(this.localForwardParameter.getInfoServizio().getProfiloDiCollaborazione())){
  157.                     scenarioCooperazione = Costanti.SCENARIO_ONEWAY_INVOCAZIONE_SERVIZIO;
  158.                 }
  159.                 else if(ProfiloDiCollaborazione.SINCRONO.equals(this.localForwardParameter.getInfoServizio().getProfiloDiCollaborazione())){
  160.                     scenarioCooperazione = Costanti.SCENARIO_SINCRONO_INVOCAZIONE_SERVIZIO;
  161.                 }
  162.                
  163.                 this.idPA = this.localForwardParameter.getIdPortaApplicativaIndirizzata();
  164.                
  165.                 this.richiestaApplicativa =
  166.                         new RichiestaApplicativa(soggettoFruitore,  
  167.                                 this.localForwardParameter.getIdModulo(), this.localForwardParameter.getIdentitaPdD(),this.idPA);
  168.                 this.richiestaApplicativa.setIdCorrelazioneApplicativa(this.localForwardParameter.getIdCorrelazioneApplicativa());
  169.                 this.richiestaApplicativa.setProfiloGestione(profiloGestione);
  170.                 this.richiestaApplicativa.setRicevutaAsincrona(false);
  171.                 this.richiestaApplicativa.setLocalForward(true);
  172.                 this.richiestaApplicativa.setScenario(scenarioCooperazione);
  173.                 if(!CostantiPdD.SERVIZIO_APPLICATIVO_ANONIMO.equals(servizioApplicativo)){
  174.                     this.richiestaApplicativa.setIdentitaServizioApplicativoFruitore(servizioApplicativo);
  175.                 }
  176.                                
  177.                 this.busta = new Busta(this.localForwardParameter.getProtocolFactory(),
  178.                         this.localForwardParameter.getInfoServizio(),
  179.                         soggettoFruitore,idServizio.getSoggettoErogatore(),
  180.                         this.localForwardParameter.getIdRequest(), false);
  181.                 this.busta.setID(this.localForwardParameter.getIdRequest());
  182.             }
  183.            
  184.             this.pd = this.localForwardParameter.getConfigurazionePdDReader().getPortaDelegata(this.richiestaDelegata.getIdPortaDelegata(), this.requestInfo);  
  185.             try{
  186.                 IDServizioApplicativo idSA = new IDServizioApplicativo();
  187.                 idSA.setNome(this.richiestaDelegata.getServizioApplicativo());
  188.                 idSA.setIdSoggettoProprietario(this.richiestaDelegata.getIdSoggettoFruitore());
  189.                 this.sa = this.localForwardParameter.getConfigurazionePdDReader().getServizioApplicativo(idSA, this.requestInfo);
  190.             }catch(DriverConfigurazioneNotFound e){
  191.                 if(CostantiPdD.SERVIZIO_APPLICATIVO_ANONIMO.equals(this.richiestaDelegata.getServizioApplicativo())==false)
  192.                     throw e;
  193.             }
  194.            
  195.             this.requestInfo = (RequestInfo) this.localForwardParameter.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO);
  196.            
  197.             if(fault==null){
  198.                 fault = this.propertiesReader.getProprietaGestioneErrorePD(this.localForwardParameter.getProtocolFactory().createProtocolManager());
  199.                 fault.setDominio(this.localForwardParameter.getIdentitaPdD().getCodicePorta());
  200.                 fault.setIdModulo(this.localForwardParameter.getIdModulo());
  201.                 this.localForwardParameter.getConfigurazionePdDReader().aggiornaProprietaGestioneErrorePD(fault, this.sa);
  202.             }
  203.            
  204.             this.ejbUtils = new EJBUtils(this.localForwardParameter.getIdentitaPdD(), TipoPdD.DELEGATA,
  205.                     this.localForwardParameter.getIdModulo(), this.localForwardParameter.getIdRequest(), this.localForwardParameter.getIdRequest(), Costanti.OUTBOX,
  206.                     this.localForwardParameter.getOpenspcoopstate(), this.localForwardParameter.getMsgDiag(), false,
  207.                     this.localForwardParameter.getImplementazionePdDMittente(), this.localForwardParameter.getImplementazionePdDDestinatario(),
  208.                     profiloGestione, this.localForwardParameter.getPddContext());
  209.             this.ejbUtils.setOneWayVersione11(this.localForwardParameter.isOneWayVersione11());
  210.             this.ejbUtils.setPortaDiTipoStateless_esclusoOneWay11(this.localForwardParameter.isStateless() && !this.localForwardParameter.isOneWayVersione11());
  211.            
  212.             this.generatoreErrorePortaDelegata = new RicezioneContenutiApplicativiInternalErrorGenerator(this.localForwardParameter.getLog(),
  213.                     this.localForwardParameter.getIdModulo(), this.requestInfo);
  214.             this.generatoreErrorePortaDelegata.updateInformazioniCooperazione(soggettoFruitore, idServizio);
  215.             this.generatoreErrorePortaDelegata.updateInformazioniCooperazione(servizioApplicativo);
  216.             this.generatoreErrorePortaDelegata.updateProprietaErroreApplicativo(fault);
  217.                
  218.             this.generatoreErrorePortaApplicativa = new RicezioneBusteExternalErrorGenerator(this.localForwardParameter.getLog(),
  219.                     this.localForwardParameter.getIdModulo(), this.requestInfo, state);
  220.             this.generatoreErrorePortaApplicativa.updateInformazioniCooperazione(soggettoFruitore, idServizio);
  221.             this.generatoreErrorePortaApplicativa.updateInformazioniCooperazione(servizioApplicativo);
  222.            
  223.             this.ejbUtils.setGeneratoreErrorePortaApplicativa(this.generatoreErrorePortaApplicativa);
  224.            
  225.             this.pa = this.localForwardParameter.getConfigurazionePdDReader().getPortaApplicativa(this.idPA, this.requestInfo);
  226.            
  227.            
  228.            
  229.         }catch(Exception e){
  230.             throw new LocalForwardException(e.getMessage(),e);
  231.         }
  232.     }
  233.    
  234.     public void updateLocalForwardParameter(LocalForwardParameter localForwardParameter) throws LocalForwardException{
  235.         this.localForwardParameter = localForwardParameter;
  236.     }
  237.    
  238.     public void setIntegrationFunctionError(IntegrationFunctionError integrationError) {
  239.         this._integrationFunctionError = integrationError;
  240.     }
  241.    
  242.     private Transaction getTransactionNullable() {
  243.         String idTransazione = (String) this.localForwardParameter.getPddContext().getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  244.         Transaction transactionNullable = null;
  245.         try{
  246.             transactionNullable = TransactionContext.getTransaction(idTransazione);
  247.         }catch(Exception e){
  248.             // puo' non essere presente in comunicazioni stateful
  249.         }
  250.         return transactionNullable;
  251.     }
  252.    
  253.    
  254.    
  255.    
  256.    
  257.    
  258.     /* ***** PROCESS REQUEST ******** */
  259.    
  260.     private SecurityInfo securityInfoRequest = null;
  261.     public SecurityInfo getSecurityInfoRequest() {
  262.         return this.securityInfoRequest;
  263.     }
  264.     private OpenSPCoop2Message responseMessageError = null;
  265.     public OpenSPCoop2Message getResponseMessageError() {
  266.         return this.responseMessageError;
  267.     }
  268.     private OpenSPCoop2Message requestMessageAfterProcess = null;
  269.     public OpenSPCoop2Message getRequestMessageAfterProcess() {
  270.         return this.requestMessageAfterProcess;
  271.     }

  272.     private MessageSecurityConfig securityConfigPDRequest = null;
  273.     private MessageSecurityConfig securityConfigPARequest = null;
  274.    
  275.     public boolean processRequest(OpenSPCoop2Message requestMessage) throws LocalForwardException{
  276.        
  277.         try{

  278.             ErroreIntegrazione erroreIntegrazione = null;
  279.             CodiceErroreCooperazione codiceErroreCooperazione = null;
  280.             Exception configException = null;
  281.             MessageSecurityFactory messageSecurityFactory = new MessageSecurityFactory();
  282.        
  283.             IState state = ((OpenSPCoopState)this.localForwardParameter.getOpenspcoopstate()).getStatoRichiesta();
  284.            
  285.             PdDContext pddContext = this.localForwardParameter.getPddContext();
  286.            
  287.            
  288.             /* ****************** PORTA DELEGATA **************************** */
  289.            
  290.            
  291.             /* *** Init MTOM Processor / SecurityContext *** */
  292.             boolean messageSecurityApply = false;
  293.             this.localForwardParameter.getMsgDiag().mediumDebug("init MTOM Processor / SecurityContext (PD) ...");
  294.             MTOMProcessorConfig mtomConfig = null;
  295.             String msgErrore = null;
  296.             String posizione = null;
  297.             MTOMProcessor mtomProcessor = null;
  298.             boolean logDiagnosticError = true;
  299.             IntegrationFunctionError integrationFunctionError = null;
  300.             try{
  301.                 this.securityConfigPDRequest=this.localForwardParameter.getConfigurazionePdDReader().getMessageSecurityForSender(this.pd, this.localForwardParameter.getLog(), requestMessage, this.busta, this.requestInfo, this.localForwardParameter.getPddContext());
  302.             }catch(Exception e){
  303.                 posizione = "LetturaParametriSicurezzaMessaggioPDRequest";
  304.                 erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  305.                         get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  306.                 configException = e;
  307.                 integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  308.             }
  309.             if(erroreIntegrazione==null){
  310.                 try{
  311.                     mtomConfig=this.localForwardParameter.getConfigurazionePdDReader().getMTOMProcessorForSender(this.pd);
  312.                 }catch(Exception e){
  313.                     posizione = "LetturaParametriMTOMProcessorPDRequest";
  314.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  315.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  316.                     configException = e;
  317.                     integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  318.                 }
  319.             }      
  320.             if(erroreIntegrazione==null){
  321.                 mtomProcessor = new MTOMProcessor(mtomConfig, this.securityConfigPDRequest, TipoPdD.DELEGATA,
  322.                         this.localForwardParameter.getMsgDiag(), this.localForwardParameter.getLog(),
  323.                         this.localForwardParameter.getPddContext());
  324.             }
  325.                    
  326.             /* *** MTOM Processor BeforeSecurity  *** */
  327.             if(mtomProcessor!=null && erroreIntegrazione==null){
  328.                 try{
  329.                     mtomProcessor.mtomBeforeSecurity(requestMessage, RuoloMessaggio.RICHIESTA);
  330.                 }catch(Exception e){
  331.                     logDiagnosticError = false; // L'errore viene registrato dentro il metodo mtomProcessor.mtomBeforeSecurity
  332.                    
  333.                     posizione = "MTOMProcessor(BeforeSec-"+mtomProcessor.getMTOMProcessorType()+")PDRequest";
  334.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  335.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_557_MTOM_PROCESSOR_ERROR);
  336.                     configException = e;
  337.                     integrationFunctionError = IntegrationFunctionError.ATTACHMENTS_PROCESSING_REQUEST_FAILED;
  338.                 }
  339.             }
  340.            
  341.             /* *** MessageSecurity *** */
  342.             MessageSecurityContext messageSecurityContext = null;
  343.             if(erroreIntegrazione==null){
  344.                 if(this.securityConfigPDRequest!=null && this.securityConfigPDRequest.getFlowParameters()!=null &&
  345.                         this.securityConfigPDRequest.getFlowParameters().size() > 0){
  346.                     try{
  347.                         this.localForwardParameter.getMsgDiag().mediumDebug("Inizializzazione contesto di Message Security (PD) della richiesta ...");
  348.                         messageSecurityApply = true;
  349.                         MessageSecurityContextParameters contextParameters = new MessageSecurityContextParameters();
  350.                         contextParameters.setUseActorDefaultIfNotDefined(this.propertiesReader.isGenerazioneActorDefault(this.localForwardParameter.getImplementazionePdDDestinatario()));
  351.                         contextParameters.setActorDefault(this.propertiesReader.getActorDefault(this.localForwardParameter.getImplementazionePdDDestinatario()));
  352.                         contextParameters.setLog(this.localForwardParameter.getLog());
  353.                         contextParameters.setFunctionAsClient(SecurityConstants.SECURITY_CLIENT);
  354.                         contextParameters.setPrefixWsuId(this.propertiesReader.getPrefixWsuId());
  355.                         contextParameters.setRemoveAllWsuIdRef(this.propertiesReader.isRemoveAllWsuIdRef());
  356.                         contextParameters.setIdFruitore(this.richiestaDelegata.getIdSoggettoFruitore());
  357.                         contextParameters.setIdServizio(this.richiestaDelegata.getIdServizio());
  358.                         contextParameters.setPddFruitore(this.localForwardParameter.getIdPdDMittente());
  359.                         contextParameters.setPddErogatore(this.localForwardParameter.getIdPdDDestinatario());
  360.                         messageSecurityContext = messageSecurityFactory.getMessageSecurityContext(contextParameters);
  361.                         messageSecurityContext.setOutgoingProperties(this.securityConfigPDRequest.getFlowParameters());
  362.                        
  363.                         this.localForwardParameter.getMsgDiag().mediumDebug("Inizializzazione contesto di Message Security (PD) della richiesta completata con successo");
  364.                        
  365.                         if(org.openspcoop2.security.message.engine.WSSUtilities.isNormalizeToSaajImpl(messageSecurityContext)){
  366.                             this.localForwardParameter.getMsgDiag().mediumDebug("Normalize to saajImpl");
  367.                             //System.out.println("InoltroBusteEgov.request.normalize");
  368.                             requestMessage = requestMessage.normalizeToSaajImpl();
  369.                             this.requestMessageAfterProcess = requestMessage; // per aggiornare il messaggio fuori dall'engine
  370.                         }
  371.                        
  372.                         String tipoSicurezza = SecurityConstants.convertActionToString(messageSecurityContext.getOutgoingProperties());
  373.                         this.localForwardParameter.getMsgDiag().addKeyword(CostantiPdD.KEY_TIPO_SICUREZZA_MESSAGGIO_RICHIESTA, tipoSicurezza);
  374.                         this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRichiestaInCorso");                
  375.                         DynamicMapBuilderUtils.injectDynamicMap(this.busta, this.requestInfo, pddContext, this.localForwardParameter.getLog());
  376.                         if(messageSecurityContext.processOutgoing(requestMessage,this.localForwardParameter.getPddContext(),
  377.                                 getTransactionNullable()!=null ? getTransactionNullable().getTempiElaborazione() : null) == false){
  378.                             msgErrore = messageSecurityContext.getMsgErrore();
  379.                             codiceErroreCooperazione = messageSecurityContext.getCodiceErrore();
  380.                            
  381.                             this.localForwardParameter.getMsgDiag().addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO , "["+codiceErroreCooperazione+"] "+msgErrore );
  382.                             this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRichiestaInErrore");
  383.                         }
  384.                         else{
  385.                             this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRichiestaEffettuato");
  386.                         }
  387.                     }catch(Exception e){
  388.                        
  389.                         this.localForwardParameter.getMsgDiag().addKeywordErroreProcessamento(e);
  390.                         this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRichiestaInErrore");
  391.                         this.localForwardParameter.getLog().error("[MessageSecurityRequest]" + e.getMessage(),e);
  392.                        
  393.                         posizione = "MessageSecurityPortaDelegataRequestFlow";
  394.                         erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  395.                                 get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  396.                         configException = e;
  397.                         integrationFunctionError = IntegrationFunctionError.MESSAGE_SECURITY_REQUEST_FAILED;
  398.                     }
  399.                 }
  400.                 else{
  401.                     this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRichiestaDisabilitato");
  402.                 }
  403.             }
  404.            
  405.             /* *** ReadSecurityInformation *** */
  406.             if(erroreIntegrazione==null && codiceErroreCooperazione==null){
  407.                 IDigestReader digestReader = null;
  408.                 if(messageSecurityContext != null) {
  409.                     digestReader = messageSecurityContext.getDigestReader(requestMessage!=null ? requestMessage.getFactory() : OpenSPCoop2MessageFactory.getDefaultMessageFactory());
  410.                 }
  411.                 if(digestReader!=null){
  412.                     try{
  413.                         this.localForwardParameter.getMsgDiag().mediumDebug("ReadSecurityInformation (PD) ...");
  414.                         IValidazioneSemantica validazioneSemantica = this.localForwardParameter.getProtocolFactory().createValidazioneSemantica(state);
  415.                         this.securityInfoRequest = validazioneSemantica.readSecurityInformation(digestReader,requestMessage);
  416.                     }catch(Exception e){
  417.                         posizione = "LetturaInformazioniSicurezzaPDRequest";
  418.                         erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  419.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_549_SECURITY_INFO_READER_ERROR);
  420.                         configException = e;
  421.                         integrationFunctionError = IntegrationFunctionError.MESSAGE_SECURITY_REQUEST_FAILED;
  422.                     }
  423.                 }
  424.             }
  425.            
  426.             /* *** MTOM Processor AfterSecurity  *** */
  427.             if(mtomProcessor!=null && erroreIntegrazione==null){
  428.                 try{
  429.                     mtomProcessor.mtomAfterSecurity(requestMessage, RuoloMessaggio.RICHIESTA);
  430.                 }catch(Exception e){
  431.                     logDiagnosticError = false; // L'errore viene registrato dentro il metodo mtomProcessor.mtomAfterSecurity
  432.                    
  433.                     posizione = "MTOMProcessor(AfterSec-"+mtomProcessor.getMTOMProcessorType()+")PDRequest";
  434.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  435.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_557_MTOM_PROCESSOR_ERROR);
  436.                     configException = e;
  437.                     integrationFunctionError = IntegrationFunctionError.ATTACHMENTS_PROCESSING_REQUEST_FAILED;
  438.                 }
  439.             }
  440.            
  441.             /* *** Gestione eventuale errore  *** */
  442.             if(erroreIntegrazione!=null || codiceErroreCooperazione!= null){
  443.                 if(integrationFunctionError==null) {
  444.                     integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  445.                 }
  446.                 if(erroreIntegrazione!=null){
  447.                     if(logDiagnosticError){
  448.                         this.localForwardParameter.getMsgDiag().logErroreGenerico(erroreIntegrazione.getDescrizione(this.localForwardParameter.getProtocolFactory()),
  449.                                 posizione);
  450.                     }
  451.                     this.responseMessageError = this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,
  452.                             erroreIntegrazione,configException,null);
  453.                 }else{
  454.                     Eccezione ecc = Eccezione.getEccezioneValidazione(ErroriCooperazione.MESSAGE_SECURITY.getErroreMessageSecurity(msgErrore, codiceErroreCooperazione),
  455.                             this.localForwardParameter.getProtocolFactory());
  456.                     if(logDiagnosticError){
  457.                         this.localForwardParameter.getMsgDiag().logErroreGenerico(ecc.getDescrizione(this.localForwardParameter.getProtocolFactory()),
  458.                                 posizione);
  459.                     }
  460.                     this.responseMessageError = this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,
  461.                             ecc,this.richiestaDelegata.getIdSoggettoFruitore(),null);
  462.                 }
  463.                 if(logDiagnosticError==false){
  464.                     // comunque effettuo log nel core. Puo' darsi in alcuni casi che non venga registrato (es. NullPointer)
  465.                     this.localForwardParameter.getLog().error("("+posizione+") "+Utilities.readFirstErrorValidMessageFromException(configException),configException);
  466.                 }

  467.             }
  468.             if(this.responseMessageError!=null){
  469.                 return false;
  470.             }

  471.            
  472.            
  473.            
  474.            
  475.            
  476.            
  477.            
  478.            
  479.             /* ****************** PORTA APPLICATIVA **************************** */
  480.            
  481.             /* *** Init MTOM Processor / SecurityContext *** */
  482.             this.localForwardParameter.getMsgDiag().mediumDebug("init MTOM Processor / SecurityContext (PA) ...");
  483.             erroreIntegrazione = null;
  484.             codiceErroreCooperazione = null;
  485.             configException = null;
  486.             mtomConfig = null;
  487.             mtomProcessor = null;
  488.             msgErrore = null;
  489.             posizione = null;
  490.             messageSecurityContext = null;
  491.             logDiagnosticError = true;
  492.             integrationFunctionError = null;
  493.             try{
  494.                 this.securityConfigPARequest=this.localForwardParameter.getConfigurazionePdDReader().getMessageSecurityForReceiver(this.pa, this.localForwardParameter.getLog(), requestMessage, this.busta, this.requestInfo, this.localForwardParameter.getPddContext());
  495.             }catch(Exception e){
  496.                 posizione = "LetturaParametriSicurezzaMessaggioPARequest";
  497.                 erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  498.                         get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  499.                 configException = e;
  500.                 integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  501.             }
  502.             if(erroreIntegrazione==null){
  503.                 try{
  504.                     mtomConfig=this.localForwardParameter.getConfigurazionePdDReader().getMTOMProcessorForReceiver(this.pa);
  505.                 }catch(Exception e){
  506.                     posizione = "LetturaParametriMTOMProcessorPARequest";
  507.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  508.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  509.                     configException = e;
  510.                     integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  511.                 }
  512.             }      
  513.             if(erroreIntegrazione==null){
  514.                 mtomProcessor = new MTOMProcessor(mtomConfig, this.securityConfigPARequest, TipoPdD.APPLICATIVA,
  515.                         this.localForwardParameter.getMsgDiag(), this.localForwardParameter.getLog(),
  516.                         this.localForwardParameter.getPddContext());
  517.             }
  518.            
  519.             /* *** MTOM Processor BeforeSecurity  *** */
  520.             if(mtomProcessor!=null && erroreIntegrazione==null){
  521.                 try{
  522.                     mtomProcessor.mtomBeforeSecurity(requestMessage, RuoloMessaggio.RICHIESTA);
  523.                 }catch(Exception e){
  524.                     logDiagnosticError = false; // L'errore viene registrato dentro il metodo mtomProcessor.mtomBeforeSecurity
  525.                    
  526.                     posizione = "MTOMProcessor(BeforeSec-"+mtomProcessor.getMTOMProcessorType()+")PARequest";
  527.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  528.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_557_MTOM_PROCESSOR_ERROR);
  529.                     configException = e;
  530.                     integrationFunctionError = IntegrationFunctionError.ATTACHMENTS_PROCESSING_REQUEST_FAILED;
  531.                 }
  532.             }
  533.            
  534.             /* *** MessageSecurity (InitContext) *** */
  535.             if(erroreIntegrazione==null && this.securityConfigPARequest!=null && this.securityConfigPARequest.getFlowParameters()!=null){
  536.                 if(this.securityConfigPARequest.getFlowParameters().size() > 0){
  537.                     try{
  538.                         this.localForwardParameter.getMsgDiag().mediumDebug("Inizializzazione contesto di Message Security (PA) della richiesta ...");
  539.                        
  540.                         if(messageSecurityApply){
  541.                            
  542.                             OpenSPCoop2SoapMessage soapMessage = requestMessage.castAsSoap();
  543.                            
  544.                             // Per poter applicare anche questa config devo rigenerare tutto il messaggio
  545. //                          requestMessage.writeTo(System.out, false);
  546.                             DOMSource s = (DOMSource) soapMessage.getSOAPPart().getContent();
  547.                             Node n = s.getNode();
  548.                             MessageXMLUtils xmlUtils = MessageXMLUtils.getInstance(requestMessage.getFactory());
  549.                             byte[] bytes = xmlUtils.toByteArray(n);
  550. //                          System.out.println("A:"+new String(bytes));
  551.                             soapMessage.getSOAPPart().setContent(new DOMSource(xmlUtils.newElement(bytes)));
  552. //                          System.out.println("B");
  553. //                          requestMessage.writeTo(System.out, false);
  554.                         }
  555.    
  556.                         MessageSecurityContextParameters contextParameters = new MessageSecurityContextParameters();
  557.                         contextParameters.setUseActorDefaultIfNotDefined(this.propertiesReader.isGenerazioneActorDefault(this.localForwardParameter.getImplementazionePdDMittente()));
  558.                         contextParameters.setActorDefault(this.propertiesReader.getActorDefault(this.localForwardParameter.getImplementazionePdDMittente()));
  559.                         contextParameters.setLog(this.localForwardParameter.getLog());
  560.                         contextParameters.setFunctionAsClient(SecurityConstants.SECURITY_SERVER);
  561.                         contextParameters.setPrefixWsuId(this.propertiesReader.getPrefixWsuId());
  562.                         contextParameters.setRemoveAllWsuIdRef(this.propertiesReader.isRemoveAllWsuIdRef());
  563.                         contextParameters.setIdFruitore(this.richiestaDelegata.getIdSoggettoFruitore());
  564.                         contextParameters.setIdServizio(this.richiestaDelegata.getIdServizio());
  565.                         contextParameters.setPddFruitore(this.localForwardParameter.getIdPdDMittente());
  566.                         contextParameters.setPddErogatore(this.localForwardParameter.getIdPdDDestinatario());
  567.                         messageSecurityContext = messageSecurityFactory.getMessageSecurityContext(contextParameters);
  568.                         messageSecurityContext.setIncomingProperties(this.securityConfigPARequest.getFlowParameters());
  569.                        
  570.                         this.localForwardParameter.getMsgDiag().mediumDebug("Inizializzazione contesto di Message Security (PA) della richiesta completata con successo");
  571.                        
  572.                     }catch(Exception e){
  573.                         posizione = "MessageSecurityPortaApplicativaRequestFlowInitContext";
  574.                         erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  575.                                 get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  576.                         configException = e;
  577.                         integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  578.                     }
  579.                 }
  580.             }
  581.            
  582.             /* *** ReadSecurityInformation *** */
  583.             if(erroreIntegrazione==null && messageSecurityContext!=null){
  584.                 IDigestReader digestReader = null;
  585.                 if(messageSecurityContext != null) {
  586.                     digestReader = messageSecurityContext.getDigestReader(requestMessage!=null ? requestMessage.getFactory() : OpenSPCoop2MessageFactory.getDefaultMessageFactory());
  587.                 }
  588.                 if(digestReader!=null) {
  589.                     try{
  590.                         this.localForwardParameter.getMsgDiag().mediumDebug("ReadSecurityInformation (PA) ...");
  591.                         IValidazioneSemantica validazioneSemantica = this.localForwardParameter.getProtocolFactory().createValidazioneSemantica(state);
  592.                         this.securityInfoRequest = validazioneSemantica.readSecurityInformation(digestReader,requestMessage);
  593.                     }catch(Exception e){
  594.                         posizione = "LetturaInformazioniSicurezzaPARequest";
  595.                         erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  596.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_549_SECURITY_INFO_READER_ERROR);
  597.                         configException = e;
  598.                         integrationFunctionError = IntegrationFunctionError.MESSAGE_SECURITY_REQUEST_FAILED;
  599.                     }
  600.                 }
  601.             }
  602.            
  603.             /* *** MessageSecurity *** */
  604.             List<Eccezione> eccezioniSicurezza = new ArrayList<>();
  605.             if(erroreIntegrazione==null && messageSecurityContext!=null){
  606.                 try{
  607.                     if(org.openspcoop2.security.message.engine.WSSUtilities.isNormalizeToSaajImpl(messageSecurityContext)){
  608.                         this.localForwardParameter.getMsgDiag().mediumDebug("Normalize to saajImpl");
  609.                         //System.out.println("RicezioneBuste.request.normalize");
  610.                         requestMessage = requestMessage.normalizeToSaajImpl();
  611.                         this.requestMessageAfterProcess = requestMessage; // per aggiornare il messaggio fuori dall'engine
  612.                     }
  613.                    
  614.                     String tipoSicurezza = SecurityConstants.convertActionToString(messageSecurityContext.getIncomingProperties());
  615.                     this.localForwardParameter.getMsgDiag().addKeyword(CostantiPdD.KEY_TIPO_SICUREZZA_MESSAGGIO_RICHIESTA, tipoSicurezza);
  616.                     this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRichiestaInCorso");                  
  617.                     DynamicMapBuilderUtils.injectDynamicMap(this.busta, this.requestInfo, this.localForwardParameter.getPddContext(), this.localForwardParameter.getLog());
  618.                     if(messageSecurityContext.processIncoming(requestMessage,this.busta,this.localForwardParameter.getPddContext(),
  619.                             getTransactionNullable()!=null ? getTransactionNullable().getTempiElaborazione() : null) == false){  
  620.                         if(messageSecurityContext.getListaSubCodiceErrore()!=null && messageSecurityContext.getListaSubCodiceErrore().size()>0){
  621.                             List<SubErrorCodeSecurity> subCodiciErrore = messageSecurityContext.getListaSubCodiceErrore();
  622.                             for (Iterator<?> iterator = subCodiciErrore.iterator(); iterator.hasNext();) {
  623.                                 SubErrorCodeSecurity subCodiceErrore = (SubErrorCodeSecurity) iterator.next();
  624.                                 Eccezione ecc = new Eccezione(ErroriCooperazione.MESSAGE_SECURITY.getErroreMessageSecurity(subCodiceErrore.getMsgErrore(), messageSecurityContext.getCodiceErrore()),true,null,
  625.                                         this.localForwardParameter.getProtocolFactory());
  626.                                 ecc.setSubCodiceEccezione(subCodiceErrore);
  627.                                 eccezioniSicurezza.add(ecc);
  628.                             }
  629.                         }else{
  630.                             Eccezione ecc = new Eccezione(ErroriCooperazione.MESSAGE_SECURITY.getErroreMessageSecurity(messageSecurityContext.getMsgErrore(),messageSecurityContext.getCodiceErrore()), true, null,
  631.                                     this.localForwardParameter.getProtocolFactory());
  632.                             eccezioniSicurezza.add(ecc);
  633.                         }
  634.                         Eccezione ecc = eccezioniSicurezza.get(0); // prendo la prima disponibile.
  635.                         this.localForwardParameter.getMsgDiag().addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO , "["+ecc.getCodiceEccezione()+"] "+ecc.getDescrizione(this.localForwardParameter.getProtocolFactory() ));
  636.                         this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRichiestaInErrore");
  637.                     }
  638.                     else{
  639.                         this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRichiestaEffettuato");
  640.                     }                                      
  641.                 }catch(Exception e){
  642.                    
  643.                     this.localForwardParameter.getMsgDiag().addKeywordErroreProcessamento(e);
  644.    
  645.                     this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRichiestaInErrore");
  646.                    
  647.                     posizione = "MessageSecurityPortaApplicativaRequestFlow";
  648.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  649.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  650.                     configException = e;
  651.                     integrationFunctionError = IntegrationFunctionError.MESSAGE_SECURITY_REQUEST_FAILED;
  652.                 }
  653.             }
  654.             else{
  655.                 if(erroreIntegrazione==null){
  656.                     this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRichiestaDisabilitato");
  657.                 }
  658.             }
  659.            
  660.             /* *** MTOM Processor AfterSecurity  *** */
  661.             if(mtomProcessor!=null && erroreIntegrazione==null){
  662.                 try{
  663.                     mtomProcessor.mtomAfterSecurity(requestMessage, RuoloMessaggio.RICHIESTA);
  664.                 }catch(Exception e){
  665.                     logDiagnosticError = false; // L'errore viene registrato dentro il metodo mtomProcessor.mtomAfterSecurity
  666.                    
  667.                     posizione = "MTOMProcessor(AfterSec-"+mtomProcessor.getMTOMProcessorType()+")PARequest";
  668.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  669.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_557_MTOM_PROCESSOR_ERROR);
  670.                     configException = e;
  671.                     integrationFunctionError = IntegrationFunctionError.ATTACHMENTS_PROCESSING_REQUEST_FAILED;
  672.                 }
  673.             }
  674.            
  675.             /* *** Gestione eventuale errore  *** */
  676.             if(erroreIntegrazione!=null || eccezioniSicurezza.size()>0){
  677.                 if(integrationFunctionError==null) {
  678.                     integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  679.                 }
  680.                 if(erroreIntegrazione!=null){
  681.                     if(logDiagnosticError){
  682.                         this.localForwardParameter.getMsgDiag().logErroreGenerico(erroreIntegrazione.getDescrizione(this.localForwardParameter.getProtocolFactory()),
  683.                                 posizione);
  684.                     }
  685.                     this.responseMessageError = this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,
  686.                             erroreIntegrazione,configException,null);
  687.                 }else{
  688.                     Eccezione ecc = eccezioniSicurezza.get(0); // prendo la prima disponibile.
  689.                     if(logDiagnosticError){
  690.                         this.localForwardParameter.getMsgDiag().logErroreGenerico(ecc.getDescrizione(this.localForwardParameter.getProtocolFactory()),
  691.                                 posizione);
  692.                     }
  693.                     this.responseMessageError = this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,
  694.                             ecc,this.richiestaDelegata.getIdSoggettoFruitore(),null);
  695.                 }
  696.                 if(logDiagnosticError==false){
  697.                     // comunque effettuo log nel core. Puo' darsi in alcuni casi che non venga registrato (es. NullPointer)
  698.                     this.localForwardParameter.getLog().error("("+posizione+") "+Utilities.readFirstErrorValidMessageFromException(configException),configException);
  699.                 }
  700.             }
  701.             if(this.responseMessageError!=null){
  702.                 return false;
  703.             }

  704.            
  705.            
  706.            
  707.            
  708.             return true;
  709.            
  710.         }catch(Exception e){
  711.             throw new LocalForwardException(e.getMessage(),e);
  712.         }
  713.     }
  714.    
  715.    
  716.    
  717.    
  718.    
  719.     /* ***** SEND REQUEST ******** */
  720.     public void sendRequest(GestoreMessaggi gestoreMessaggiRequest) throws LocalForwardException{
  721.        
  722.         try{

  723.             Behaviour behaviour = this.ejbUtils.sendToConsegnaContenutiApplicativi(this.requestInfo, this.richiestaApplicativa, this.busta, gestoreMessaggiRequest, this.pa,
  724.                     this.localForwardParameter.getRepositoryBuste(), this.richiestaDelegata);
  725.             boolean behaviourResponseTo = behaviour!=null && behaviour.isResponseTo();
  726.            
  727.             GestoreMessaggi msgOK = null;
  728.            
  729.             if(behaviourResponseTo){
  730.            
  731.                 this.localForwardParameter.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.DATA_PRESA_IN_CARICO,
  732.                         DateUtils.getSimpleDateFormatMs().format(DateManager.getDate()));
  733.                
  734.                 this.localForwardParameter.getMsgDiag().mediumDebug("Invio messaggio 'OK' al modulo di RicezioneContenutiApplicativi (Behaviour)...");  
  735.                
  736.                 OpenSPCoop2Message responseToMessage = null;
  737.                 if(behaviour.getResponseTo()!=null){
  738.                     responseToMessage = behaviour.getResponseTo().getMessage();
  739.                 }
  740.                 if(responseToMessage==null){
  741.                     if(this.localForwardParameter.getProtocolFactory().createProtocolManager().isHttpEmptyResponseOneWay()){
  742.                         responseToMessage =  MessageUtilities.buildEmptyMessage(OpenSPCoop2MessageFactory.getDefaultMessageFactory(), this.requestInfo.getIntegrationRequestMessageType(),MessageRole.RESPONSE);
  743.                     }
  744.                     else{
  745.                         responseToMessage = this.ejbUtils.buildOpenSPCoopOK(this.requestInfo.getIntegrationRequestMessageType(), this.localForwardParameter.getIdRequest());
  746.                     }
  747.                 }
  748.                 msgOK = this.ejbUtils.sendRispostaApplicativaOK(responseToMessage,
  749.                         this.richiestaDelegata,this.pd,this.sa);            
  750.                
  751.             }else if(this.localForwardParameter.isStateless()==false || this.localForwardParameter.isOneWayVersione11() || this.ejbUtils.isGestioneSolamenteConIntegrationManager()){
  752.                
  753.                 this.localForwardParameter.getPddContext().addObject(org.openspcoop2.core.constants.Costanti.DATA_PRESA_IN_CARICO,
  754.                         DateUtils.getSimpleDateFormatMs().format(DateManager.getDate()));
  755.                
  756.                 this.localForwardParameter.getMsgDiag().mediumDebug("Invio messaggio 'OK' al modulo di RicezioneContenutiApplicativi...");  
  757.                
  758.                 if(this.localForwardParameter.getProtocolFactory().createProtocolManager().isHttpEmptyResponseOneWay())
  759.                     msgOK = this.ejbUtils.sendRispostaApplicativaOK(MessageUtilities.buildEmptyMessage(OpenSPCoop2MessageFactory.getDefaultMessageFactory(), this.requestInfo.getIntegrationRequestMessageType(),MessageRole.RESPONSE),this.richiestaDelegata,this.pd,this.sa);
  760.                 else
  761.                     msgOK = this.ejbUtils.sendRispostaApplicativaOK(this.ejbUtils.buildOpenSPCoopOK(this.requestInfo.getIntegrationRequestMessageType(), this.localForwardParameter.getIdRequest()),
  762.                             this.richiestaDelegata,this.pd,this.sa);
  763.             }
  764.            
  765.            
  766.             if(msgOK!=null)
  767.                 msgOK.addMessaggiIntoCache_readFromTable(Imbustamento.ID_MODULO, "messaggio OK");
  768.            
  769.             if(msgOK!=null)
  770.                 msgOK.addProprietariIntoCache_readFromTable(Imbustamento.ID_MODULO, "messaggio OK",this.localForwardParameter.getIdRequest(),false);
  771.            
  772.            
  773.         }catch(Exception e){
  774.             throw new LocalForwardException(e.getMessage(),e);
  775.         }
  776.        
  777.     }
  778.    
  779.    
  780.    
  781.    
  782.    
  783.     /* ***** PROCESS RESPONSE ******** */
  784.     private SecurityInfo securityInfoResponse = null;
  785.     public SecurityInfo getSecurityInfoResponse() {
  786.         return this.securityInfoResponse;
  787.     }
  788.     private OpenSPCoop2Message responseMessageAfterProcess = null;
  789.     public OpenSPCoop2Message getResponseMessageAfterProcess() {
  790.         return this.responseMessageAfterProcess;
  791.     }
  792.     public boolean processResponse(OpenSPCoop2Message responseMessage) throws LocalForwardException{
  793.        
  794.         try{
  795.            
  796.             ErroreIntegrazione erroreIntegrazione = null;
  797.             CodiceErroreCooperazione codiceErroreCooperazione = null;
  798.             Exception configException = null;
  799.             MessageSecurityFactory messageSecurityFactory = new MessageSecurityFactory();

  800.             IState state = ((OpenSPCoopState)this.localForwardParameter.getOpenspcoopstate()).getStatoRisposta();
  801.            
  802.             PdDContext pddContext = this.localForwardParameter.getPddContext();
  803.            
  804.            
  805.            
  806.            
  807.             /* ****************** PORTA APPLICATIVA **************************** */
  808.            
  809.             /* *** Init MTOM Processor / SecurityContext *** */
  810.             boolean messageSecurityApply = false;
  811.             this.localForwardParameter.getMsgDiag().mediumDebug("init MTOM Processor / SecurityContext (PA-Response) ...");
  812.             MessageSecurityConfig securityConfig = null;
  813.             MTOMProcessorConfig mtomConfig = null;
  814.             String msgErrore = null;
  815.             String posizione = null;
  816.             MTOMProcessor mtomProcessor = null;
  817.             boolean logDiagnosticError = true;
  818.             IntegrationFunctionError integrationFunctionError = null;
  819.             try{
  820.                 securityConfig=this.localForwardParameter.getConfigurazionePdDReader().getMessageSecurityForSender(this.pa, this.localForwardParameter.getLog(), responseMessage, this.busta, this.requestInfo, this.localForwardParameter.getPddContext(),
  821.                         this.securityConfigPARequest);
  822.             }catch(Exception e){
  823.                 posizione = "LetturaParametriSicurezzaMessaggioPAResponse";
  824.                 erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  825.                         get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  826.                 configException = e;
  827.                 integrationFunctionError = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  828.             }
  829.             if(erroreIntegrazione==null){
  830.                 try{
  831.                     mtomConfig=this.localForwardParameter.getConfigurazionePdDReader().getMTOMProcessorForSender(this.pa);
  832.                 }catch(Exception e){
  833.                     posizione = "LetturaParametriMTOMProcessorPAResponse";
  834.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  835.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  836.                     configException = e;
  837.                     integrationFunctionError = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  838.                 }
  839.             }      
  840.             if(erroreIntegrazione==null){
  841.                 mtomProcessor = new MTOMProcessor(mtomConfig, securityConfig, TipoPdD.APPLICATIVA,
  842.                         this.localForwardParameter.getMsgDiag(), this.localForwardParameter.getLog(),
  843.                         this.localForwardParameter.getPddContext());
  844.             }
  845.            
  846.             /* *** MTOM Processor BeforeSecurity  *** */
  847.             if(mtomProcessor!=null && erroreIntegrazione==null){
  848.                 try{
  849.                     mtomProcessor.mtomBeforeSecurity(responseMessage, RuoloMessaggio.RISPOSTA);
  850.                 }catch(Exception e){
  851.                     logDiagnosticError = false; // L'errore viene registrato dentro il metodo mtomProcessor.mtomBeforeSecurity
  852.                    
  853.                     posizione = "MTOMProcessor(BeforeSec-"+mtomProcessor.getMTOMProcessorType()+")PAResponse";
  854.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  855.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_557_MTOM_PROCESSOR_ERROR);
  856.                     configException = e;
  857.                     integrationFunctionError = IntegrationFunctionError.ATTACHMENTS_PROCESSING_RESPONSE_FAILED;
  858.                 }
  859.             }
  860.            
  861.             /* *** MessageSecurity (InitContext) *** */
  862.             MessageSecurityContext messageSecurityContext = null;
  863.             if(erroreIntegrazione==null && securityConfig!=null && securityConfig.getFlowParameters()!=null){
  864.                 if(securityConfig.getFlowParameters().size() > 0){
  865.                     try{
  866.                         this.localForwardParameter.getMsgDiag().mediumDebug("Inizializzazione contesto di Message Security (PA) della risposta ...");
  867.                         MessageSecurityContextParameters contextParameters = new MessageSecurityContextParameters();
  868.                         contextParameters.setUseActorDefaultIfNotDefined(this.propertiesReader.isGenerazioneActorDefault(this.localForwardParameter.getImplementazionePdDMittente()));
  869.                         contextParameters.setActorDefault(this.propertiesReader.getActorDefault(this.localForwardParameter.getImplementazionePdDMittente()));
  870.                         contextParameters.setLog(this.localForwardParameter.getLog());
  871.                         contextParameters.setFunctionAsClient(SecurityConstants.SECURITY_CLIENT);
  872.                         contextParameters.setPrefixWsuId(this.propertiesReader.getPrefixWsuId());
  873.                         contextParameters.setIdFruitore(this.richiestaDelegata.getIdSoggettoFruitore());
  874.                         contextParameters.setIdServizio(this.richiestaDelegata.getIdServizio());
  875.                         contextParameters.setPddFruitore(this.localForwardParameter.getIdPdDMittente());
  876.                         contextParameters.setPddErogatore(this.localForwardParameter.getIdPdDDestinatario());
  877.                         messageSecurityContext = messageSecurityFactory.getMessageSecurityContext(contextParameters);
  878.                         messageSecurityContext.setOutgoingProperties(securityConfig.getFlowParameters());
  879.                         this.localForwardParameter.getMsgDiag().mediumDebug("Inizializzazione contesto di Message Security (PA) della risposta completata con successo");
  880.                        
  881.                     }catch(Exception e){
  882.                         posizione = "MessageSecurityPortaApplicativaResponseFlowInitContext";
  883.                         erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  884.                                 get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  885.                         configException = e;
  886.                         integrationFunctionError = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  887.                     }
  888.                 }
  889.             }
  890.            
  891.             /* *** ReadSecurityInformation *** */
  892.             if(erroreIntegrazione==null && messageSecurityContext!=null){
  893.                 IDigestReader digestReader = null;
  894.                 if(messageSecurityContext != null) {
  895.                     digestReader = messageSecurityContext.getDigestReader(responseMessage!=null ? responseMessage.getFactory() : OpenSPCoop2MessageFactory.getDefaultMessageFactory());
  896.                 }
  897.                 if(digestReader!=null) {
  898.                     try{
  899.                         this.localForwardParameter.getMsgDiag().mediumDebug("ReadSecurityInformation (PA-Response) ...");
  900.                         IValidazioneSemantica validazioneSemantica = this.localForwardParameter.getProtocolFactory().createValidazioneSemantica(state);
  901.                         this.securityInfoResponse = validazioneSemantica.readSecurityInformation(digestReader,responseMessage);
  902.                     }catch(Exception e){
  903.                         posizione = "LetturaInformazioniSicurezzaPAResponse";
  904.                         erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  905.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_549_SECURITY_INFO_READER_ERROR);
  906.                         configException = e;
  907.                         integrationFunctionError = IntegrationFunctionError.MESSAGE_SECURITY_RESPONSE_FAILED;
  908.                     }
  909.                 }
  910.             }
  911.            
  912.             /* *** MessageSecurity *** */
  913.             if(erroreIntegrazione==null && messageSecurityContext!=null){
  914.                 try{
  915.                     if(org.openspcoop2.security.message.engine.WSSUtilities.isNormalizeToSaajImpl(messageSecurityContext)){
  916.                         this.localForwardParameter.getMsgDiag().mediumDebug("Normalize to saajImpl");
  917.                         //System.out.println("InoltroBusteEgov.request.normalize");
  918.                         responseMessage = responseMessage.normalizeToSaajImpl();
  919.                         this.responseMessageAfterProcess = responseMessage; // per aggiornare il messaggio fuori dall'engine
  920.                     }
  921.                     String tipoSicurezza = SecurityConstants.convertActionToString(messageSecurityContext.getOutgoingProperties());
  922.                     this.localForwardParameter.getMsgDiag().addKeyword(CostantiPdD.KEY_TIPO_SICUREZZA_MESSAGGIO_RISPOSTA, tipoSicurezza);
  923.                     this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRispostaInCorso");                    
  924.                     messageSecurityApply = true;
  925.                     DynamicMapBuilderUtils.injectDynamicMap(this.busta, this.requestInfo, pddContext, this.localForwardParameter.getLog());
  926.                     if(messageSecurityContext.processOutgoing(responseMessage,this.localForwardParameter.getPddContext(),
  927.                             getTransactionNullable()!=null ? getTransactionNullable().getTempiElaborazione() : null) == false){
  928.                         msgErrore = messageSecurityContext.getMsgErrore();
  929.                         codiceErroreCooperazione = messageSecurityContext.getCodiceErrore();
  930.                         this.localForwardParameter.getMsgDiag().addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO , "["+codiceErroreCooperazione+"] "+msgErrore );
  931.                         this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRispostaInErrore");
  932.                     }
  933.                     else{
  934.                         this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRispostaEffettuato");
  935.                     }
  936.                 }catch(Exception e){
  937.                     this.localForwardParameter.getMsgDiag().addKeywordErroreProcessamento(e);
  938.                     this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRispostaInErrore");
  939.                     posizione = "MessageSecurityPortaApplicativaResponseFlow";
  940.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  941.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  942.                     configException = e;
  943.                     integrationFunctionError = IntegrationFunctionError.MESSAGE_SECURITY_RESPONSE_FAILED;
  944.                 }
  945.             }
  946.             else{
  947.                 if(erroreIntegrazione==null){
  948.                     this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE,"messageSecurity.processamentoRispostaDisabilitato");
  949.                 }
  950.             }
  951.            
  952.             /* *** MTOM Processor AfterSecurity  *** */
  953.             if(mtomProcessor!=null && erroreIntegrazione==null){
  954.                 try{
  955.                     mtomProcessor.mtomAfterSecurity(responseMessage, RuoloMessaggio.RISPOSTA);
  956.                 }catch(Exception e){
  957.                     logDiagnosticError = false; // L'errore viene registrato dentro il metodo mtomProcessor.mtomAfterSecurity
  958.                    
  959.                     posizione = "MTOMProcessor(AfterSec-"+mtomProcessor.getMTOMProcessorType()+")PAResponse";
  960.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  961.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_557_MTOM_PROCESSOR_ERROR);
  962.                     configException = e;
  963.                     integrationFunctionError = IntegrationFunctionError.ATTACHMENTS_PROCESSING_RESPONSE_FAILED;
  964.                 }
  965.             }
  966.            
  967.             /* *** Gestione eventuale errore  *** */
  968.             if(erroreIntegrazione!=null || codiceErroreCooperazione!= null){
  969.                 if(integrationFunctionError==null) {
  970.                     integrationFunctionError = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  971.                 }
  972.                 if(erroreIntegrazione!=null){
  973.                     if(logDiagnosticError){
  974.                         this.localForwardParameter.getMsgDiag().logErroreGenerico(erroreIntegrazione.getDescrizione(this.localForwardParameter.getProtocolFactory()),
  975.                                 posizione);
  976.                     }
  977.                     this.responseMessageError = this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,
  978.                             erroreIntegrazione,configException,
  979.                             (responseMessage!=null ? responseMessage.getParseException() : null));
  980.                 }else{
  981.                     Eccezione ecc = Eccezione.getEccezioneValidazione(ErroriCooperazione.MESSAGE_SECURITY.getErroreMessageSecurity(msgErrore, codiceErroreCooperazione),
  982.                             this.localForwardParameter.getProtocolFactory());
  983.                     if(logDiagnosticError){
  984.                         this.localForwardParameter.getMsgDiag().logErroreGenerico(ecc.getDescrizione(this.localForwardParameter.getProtocolFactory()),
  985.                                 posizione);
  986.                     }
  987.                     this.responseMessageError = this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,
  988.                             ecc,this.richiestaDelegata.getIdSoggettoFruitore(),null);
  989.                 }
  990.                 if(logDiagnosticError==false){
  991.                     // comunque effettuo log nel core. Puo' darsi in alcuni casi che non venga registrato (es. NullPointer)
  992.                     this.localForwardParameter.getLog().error("("+posizione+") "+Utilities.readFirstErrorValidMessageFromException(configException),configException);
  993.                 }
  994.             }
  995.             if(this.responseMessageError!=null){
  996.                 return false;
  997.             }

  998.            
  999.            
  1000.            
  1001.            
  1002.            
  1003.            
  1004.             /* ****************** PORTA DELEGATA **************************** */
  1005.            
  1006.             /* *** Init MTOM Processor / SecurityContext *** */
  1007.             this.localForwardParameter.getMsgDiag().mediumDebug("init MTOM Processor / SecurityContext (PD-Response) ...");
  1008.             erroreIntegrazione = null;
  1009.             codiceErroreCooperazione = null;
  1010.             configException = null;
  1011.             securityConfig = null;
  1012.             mtomConfig = null;
  1013.             mtomProcessor = null;
  1014.             msgErrore = null;
  1015.             posizione = null;
  1016.             messageSecurityContext = null;
  1017.             logDiagnosticError = true;
  1018.             integrationFunctionError = null;
  1019.             try{
  1020.                 securityConfig=this.localForwardParameter.getConfigurazionePdDReader().getMessageSecurityForReceiver(this.pd, this.localForwardParameter.getLog(), responseMessage, this.busta, this.requestInfo, this.localForwardParameter.getPddContext(),
  1021.                         this.securityConfigPDRequest);
  1022.             }catch(Exception e){
  1023.                 posizione = "LetturaParametriSicurezzaMessaggioPDResponse";
  1024.                 erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1025.                         get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  1026.                 configException = e;
  1027.                 integrationFunctionError = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  1028.             }
  1029.             if(erroreIntegrazione==null){
  1030.                 try{
  1031.                     mtomConfig=this.localForwardParameter.getConfigurazionePdDReader().getMTOMProcessorForReceiver(this.pd);
  1032.                 }catch(Exception e){
  1033.                     posizione = "LetturaParametriMTOMProcessorPDResponse";
  1034.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1035.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  1036.                     configException = e;
  1037.                     integrationFunctionError = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  1038.                 }
  1039.             }      
  1040.             if(erroreIntegrazione==null){
  1041.                 mtomProcessor = new MTOMProcessor(mtomConfig, securityConfig, TipoPdD.DELEGATA,
  1042.                         this.localForwardParameter.getMsgDiag(), this.localForwardParameter.getLog(),
  1043.                         this.localForwardParameter.getPddContext());
  1044.             }
  1045.            
  1046.             /* *** MTOM Processor BeforeSecurity  *** */
  1047.             if(mtomProcessor!=null && erroreIntegrazione==null){
  1048.                 try{
  1049.                     mtomProcessor.mtomBeforeSecurity(responseMessage, RuoloMessaggio.RISPOSTA);
  1050.                 }catch(Exception e){
  1051.                     logDiagnosticError = false; // L'errore viene registrato dentro il metodo mtomProcessor.mtomBeforeSecurity
  1052.                    
  1053.                     posizione = "MTOMProcessor(BeforeSec-"+mtomProcessor.getMTOMProcessorType()+")PDResponse";
  1054.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1055.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_557_MTOM_PROCESSOR_ERROR);
  1056.                     configException = e;
  1057.                     integrationFunctionError = IntegrationFunctionError.ATTACHMENTS_PROCESSING_RESPONSE_FAILED;
  1058.                 }
  1059.             }
  1060.            
  1061.             /* *** MessageSecurity *** */
  1062.             if(erroreIntegrazione==null){
  1063.                 if(securityConfig!=null && securityConfig.getFlowParameters()!=null &&
  1064.                         securityConfig.getFlowParameters().size() > 0){
  1065.                     try{
  1066.                         this.localForwardParameter.getMsgDiag().mediumDebug("Inizializzazione contesto di Message Security (PD) della risposta ...");
  1067.                        
  1068.                         if(messageSecurityApply){
  1069.                            
  1070.                             OpenSPCoop2SoapMessage soapMessage = responseMessage.castAsSoap();
  1071.                            
  1072.                             // Per poter applicare anche questa config devo rigenerare tutto il messaggio
  1073. //                          requestMessage.writeTo(System.out, false);
  1074.                             DOMSource s = (DOMSource) soapMessage.getSOAPPart().getContent();
  1075.                             Node n = s.getNode();
  1076.                             MessageXMLUtils xmlUtils = MessageXMLUtils.getInstance(responseMessage.getFactory());
  1077.                             byte[] bytes = xmlUtils.toByteArray(n);
  1078. //                          System.out.println("A:"+new String(bytes));
  1079.                             soapMessage.getSOAPPart().setContent(new DOMSource(xmlUtils.newElement(bytes)));
  1080. //                          System.out.println("B");
  1081. //                          requestMessage.writeTo(System.out, false);
  1082.                         }
  1083.    
  1084.                         MessageSecurityContextParameters contextParameters = new MessageSecurityContextParameters();
  1085.                         contextParameters.setUseActorDefaultIfNotDefined(this.propertiesReader.isGenerazioneActorDefault(this.localForwardParameter.getImplementazionePdDDestinatario()));
  1086.                         contextParameters.setActorDefault(this.propertiesReader.getActorDefault(this.localForwardParameter.getImplementazionePdDDestinatario()));
  1087.                         contextParameters.setLog(this.localForwardParameter.getLog());
  1088.                         contextParameters.setFunctionAsClient(SecurityConstants.SECURITY_SERVER);
  1089.                         contextParameters.setPrefixWsuId(this.propertiesReader.getPrefixWsuId());
  1090.                         contextParameters.setIdFruitore(this.richiestaDelegata.getIdSoggettoFruitore());
  1091.                         contextParameters.setIdServizio(this.richiestaDelegata.getIdServizio());
  1092.                         contextParameters.setPddFruitore(this.localForwardParameter.getIdPdDMittente());
  1093.                         contextParameters.setPddErogatore(this.localForwardParameter.getIdPdDDestinatario());
  1094.                         messageSecurityContext = messageSecurityFactory.getMessageSecurityContext(contextParameters);
  1095.                         messageSecurityContext.setIncomingProperties(securityConfig.getFlowParameters());
  1096.                         this.localForwardParameter.getMsgDiag().mediumDebug("Inizializzazione contesto di Message Security (PD) della risposta completata con successo");
  1097.                        
  1098.                         if(org.openspcoop2.security.message.engine.WSSUtilities.isNormalizeToSaajImpl(messageSecurityContext)){
  1099.                             this.localForwardParameter.getMsgDiag().mediumDebug("Normalize to saajImpl");
  1100.                             //System.out.println("InoltroBusteEgov.request.normalize");
  1101.                             responseMessage = responseMessage.normalizeToSaajImpl();
  1102.                             this.responseMessageAfterProcess = responseMessage; // per aggiornare il messaggio fuori dall'engine
  1103.                         }
  1104.                         String tipoSicurezza = SecurityConstants.convertActionToString(messageSecurityContext.getIncomingProperties());
  1105.                         this.localForwardParameter.getMsgDiag().addKeyword(CostantiPdD.KEY_TIPO_SICUREZZA_MESSAGGIO_RISPOSTA, tipoSicurezza);
  1106.                         this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRispostaInCorso");                  
  1107.                         DynamicMapBuilderUtils.injectDynamicMap(this.busta, this.requestInfo, this.localForwardParameter.getPddContext(), this.localForwardParameter.getLog());
  1108.                         if(messageSecurityContext.processIncoming(responseMessage,this.busta,this.localForwardParameter.getPddContext(),
  1109.                                 getTransactionNullable()!=null ? getTransactionNullable().getTempiElaborazione() : null) == false){
  1110.                             msgErrore = messageSecurityContext.getMsgErrore();
  1111.                             codiceErroreCooperazione = messageSecurityContext.getCodiceErrore();
  1112.                             this.localForwardParameter.getMsgDiag().addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO , "["+codiceErroreCooperazione+"] "+msgErrore );
  1113.                             this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRispostaInErrore");
  1114.                         }
  1115.                         else{
  1116.                             this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRispostaEffettuato");
  1117.                         }
  1118.                     }catch(Exception e){
  1119.                         this.localForwardParameter.getMsgDiag().addKeywordErroreProcessamento(e);
  1120.                         this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRispostaInErrore");
  1121.                         posizione = "MessageSecurityPortaDelegataResponseFlow";
  1122.                         erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1123.                                 get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE);
  1124.                         configException = e;
  1125.                         integrationFunctionError = IntegrationFunctionError.MESSAGE_SECURITY_RESPONSE_FAILED;
  1126.                     }
  1127.                 }
  1128.                 else{
  1129.                     this.localForwardParameter.getMsgDiag().logPersonalizzato(MsgDiagnosticiProperties.MSG_DIAG_INOLTRO_BUSTE,"messageSecurity.processamentoRispostaDisabilitato");                
  1130.                 }
  1131.             }
  1132.            
  1133.             /* *** ReadSecurityInformation *** */
  1134.             if(erroreIntegrazione==null && codiceErroreCooperazione==null){
  1135.                 IDigestReader digestReader = null;
  1136.                 if(messageSecurityContext != null) {
  1137.                     digestReader = messageSecurityContext.getDigestReader(responseMessage!=null ? responseMessage.getFactory() : OpenSPCoop2MessageFactory.getDefaultMessageFactory());
  1138.                 }
  1139.                 if(digestReader!=null){
  1140.                     try{
  1141.                         this.localForwardParameter.getMsgDiag().mediumDebug("ReadSecurityInformation (PD-Response) ...");
  1142.                         IValidazioneSemantica validazioneSemantica = this.localForwardParameter.getProtocolFactory().createValidazioneSemantica(state);
  1143.                         this.securityInfoResponse = validazioneSemantica.readSecurityInformation(digestReader,responseMessage);
  1144.                     }catch(Exception e){
  1145.                         posizione = "LetturaInformazioniSicurezzaPDResponse";
  1146.                         erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1147.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_549_SECURITY_INFO_READER_ERROR);
  1148.                         configException = e;
  1149.                         integrationFunctionError = IntegrationFunctionError.MESSAGE_SECURITY_RESPONSE_FAILED;
  1150.                     }
  1151.                 }
  1152.             }
  1153.            
  1154.             /* *** MTOM Processor AfterSecurity  *** */
  1155.             if(mtomProcessor!=null && erroreIntegrazione==null){
  1156.                 try{
  1157.                     mtomProcessor.mtomAfterSecurity(responseMessage, RuoloMessaggio.RISPOSTA);
  1158.                 }catch(Exception e){
  1159.                     logDiagnosticError = false; // L'errore viene registrato dentro il metodo mtomProcessor.mtomAfterSecurity
  1160.                    
  1161.                     posizione = "MTOMProcessor(AfterSec-"+mtomProcessor.getMTOMProcessorType()+")PDResponse";
  1162.                     erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1163.                             get5XX_ErroreProcessamento(e,CodiceErroreIntegrazione.CODICE_557_MTOM_PROCESSOR_ERROR);
  1164.                     configException = e;
  1165.                     integrationFunctionError = IntegrationFunctionError.ATTACHMENTS_PROCESSING_RESPONSE_FAILED;
  1166.                 }
  1167.             }
  1168.            
  1169.             /* *** Gestione eventuale errore  *** */
  1170.             if(erroreIntegrazione!=null || codiceErroreCooperazione!= null){
  1171.                 if(integrationFunctionError==null) {
  1172.                     integrationFunctionError = IntegrationFunctionError.INTERNAL_RESPONSE_ERROR;
  1173.                 }
  1174.                 if(erroreIntegrazione!=null){
  1175.                     if(logDiagnosticError){
  1176.                         this.localForwardParameter.getMsgDiag().logErroreGenerico(erroreIntegrazione.getDescrizione(this.localForwardParameter.getProtocolFactory()),
  1177.                                 posizione);
  1178.                     }
  1179.                     this.responseMessageError = this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,
  1180.                             erroreIntegrazione,configException,
  1181.                             (responseMessage!=null ? responseMessage.getParseException() : null));
  1182.                 }else{
  1183.                     Eccezione ecc = Eccezione.getEccezioneValidazione(ErroriCooperazione.MESSAGE_SECURITY.getErroreMessageSecurity(msgErrore, codiceErroreCooperazione),
  1184.                             this.localForwardParameter.getProtocolFactory());
  1185.                     if(logDiagnosticError){
  1186.                         this.localForwardParameter.getMsgDiag().logErroreGenerico(ecc.getDescrizione(this.localForwardParameter.getProtocolFactory()),
  1187.                                 posizione);
  1188.                     }
  1189.                     this.responseMessageError = this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,
  1190.                             ecc,this.richiestaDelegata.getIdSoggettoFruitore(),null);
  1191.                 }
  1192.                 if(logDiagnosticError==false){
  1193.                     // comunque effettuo log nel core. Puo' darsi in alcuni casi che non venga registrato (es. NullPointer)
  1194.                     this.localForwardParameter.getLog().error("("+posizione+") "+Utilities.readFirstErrorValidMessageFromException(configException),configException);
  1195.                 }
  1196.             }
  1197.             if(this.responseMessageError!=null){
  1198.                 return false;
  1199.             }

  1200.            
  1201.            
  1202.            
  1203.            
  1204.            
  1205.             return true;
  1206.            
  1207.            
  1208.         }catch(Exception e){
  1209.             throw new LocalForwardException(e.getMessage(),e);
  1210.         }
  1211.        
  1212.     }
  1213.    
  1214.    
  1215.    
  1216.    
  1217.    
  1218.    
  1219.    
  1220.    
  1221.    
  1222.     /* ***** SEND RESPONSE ******** */
  1223.    
  1224.     public void sendErrore(PdDContext pddContext, ErroreIntegrazione errore,Throwable eErrore,ParseException parseException) throws LocalForwardException{
  1225.    
  1226.         try{
  1227.        
  1228.             IntegrationFunctionError integrationFunctionError = getIntegrationFunctionError(pddContext);
  1229.            
  1230.             OpenSPCoop2Message responseMessageError =
  1231.                     this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,errore,eErrore,parseException);
  1232.            
  1233.             // Retry-After
  1234.             if(integrationFunctionError!=null &&
  1235.                     (
  1236.                             IntegrationFunctionError.SERVICE_UNAVAILABLE.equals(integrationFunctionError)
  1237.                             ||
  1238.                             IntegrationFunctionError.ENDPOINT_REQUEST_TIMED_OUT.equals(integrationFunctionError)
  1239.                     )
  1240.                     ) {
  1241.                 boolean isEnabled = this.propertiesReader.isEnabledServiceUnavailableRetryAfterPAConnectionFailed();
  1242.                 Integer retryAfterSeconds = this.propertiesReader.getServiceUnavailableRetryAfterSecondsPAConnectionFailed();
  1243.                 Integer retryAfterBackOffSeconds = this.propertiesReader.getServiceUnavailableRetryAfterSecondsRandomBackoffPAConnectionFailed();
  1244.                 if( isEnabled &&
  1245.                     retryAfterSeconds!=null && retryAfterSeconds>0) {
  1246.                     int seconds = retryAfterSeconds;
  1247.                     if(retryAfterBackOffSeconds!=null && retryAfterBackOffSeconds>0) {
  1248.                         seconds = seconds + ServicesUtils.getRandom().nextInt(retryAfterBackOffSeconds);
  1249.                     }
  1250.                     responseMessageError.forceTransportHeader(HttpConstants.RETRY_AFTER, seconds+"");
  1251.                 }
  1252.             }
  1253.            
  1254.             if(eErrore instanceof HandlerException){
  1255.                 HandlerException he = (HandlerException) eErrore;
  1256.                 he.customized(responseMessageError);
  1257.             }
  1258.             this.sendErrore(responseMessageError);
  1259.            
  1260.         }catch(Exception e){
  1261.             throw new LocalForwardException(e.getMessage(),e);
  1262.         }  
  1263.     }
  1264.    
  1265.     public void sendErrore(PdDContext pddContext, Eccezione errore,IDSoggetto dominio,ParseException parseException) throws LocalForwardException{
  1266.        
  1267.         try{
  1268.        
  1269.             IntegrationFunctionError integrationFunctionError = getIntegrationFunctionError(pddContext);
  1270.            
  1271.             OpenSPCoop2Message responseMessageError =
  1272.                     this.generatoreErrorePortaDelegata.build(pddContext, integrationFunctionError,errore,dominio,parseException);
  1273.             this.sendErrore(responseMessageError);
  1274.            
  1275.         }catch(Exception e){
  1276.             throw new LocalForwardException(e.getMessage(),e);
  1277.         }  
  1278.     }
  1279.    
  1280.     public void sendErrore(OpenSPCoop2Message responseMessageError) throws LocalForwardException{
  1281.        
  1282.         try{
  1283.        
  1284.             this.ejbUtils.sendRispostaApplicativaErrore(responseMessageError,this.richiestaDelegata,true,this.pd,this.sa);
  1285.            
  1286.         }catch(Exception e){
  1287.             throw new LocalForwardException(e.getMessage(),e);
  1288.         }  
  1289.     }
  1290.    
  1291.     public void sendResponse(String idRisposta) throws LocalForwardException{
  1292.        
  1293.         try{
  1294.        
  1295.             GestoreMessaggi msgResponse = null;
  1296.            
  1297.             this.localForwardParameter.getMsgDiag().mediumDebug("Send risposta applicativa...");
  1298.             this.ejbUtils.setIdMessage(idRisposta);
  1299.             msgResponse = this.ejbUtils.sendRispostaApplicativa(this.richiestaDelegata,this.pd,this.sa);
  1300.                        
  1301.             // Aggiornamento cache messaggio
  1302.             if(msgResponse!=null)
  1303.                 msgResponse.addMessaggiIntoCache_readFromTable(SbustamentoRisposte.ID_MODULO, "risposte");

  1304.             // Aggiornamento cache proprietario messaggio
  1305.             if(msgResponse!=null)
  1306.                 msgResponse.addProprietariIntoCache_readFromTable(SbustamentoRisposte.ID_MODULO, "risposte",this.localForwardParameter.getIdRequest(),false);
  1307.            
  1308.         }catch(Exception e){
  1309.             throw new LocalForwardException(e.getMessage(),e);
  1310.         }  
  1311.     }
  1312. }