IntegrationManager.java

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



  20. package org.openspcoop2.pdd.services.skeleton;

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

  24. import javax.servlet.http.HttpServletRequest;
  25. import javax.servlet.http.HttpServletResponse;

  26. import org.openspcoop2.core.commons.CoreException;
  27. import org.openspcoop2.core.config.constants.CostantiConfigurazione;
  28. import org.openspcoop2.core.constants.TipoPdD;
  29. import org.openspcoop2.core.id.IDPortaApplicativa;
  30. import org.openspcoop2.core.id.IDServizio;
  31. import org.openspcoop2.core.id.IDServizioApplicativo;
  32. import org.openspcoop2.core.id.IDSoggetto;
  33. import org.openspcoop2.core.registry.driver.IDServizioFactory;
  34. import org.openspcoop2.core.transazioni.TransazioneApplicativoServer;
  35. import org.openspcoop2.message.OpenSPCoop2Message;
  36. import org.openspcoop2.message.soap.TunnelSoapUtils;
  37. import org.openspcoop2.pdd.config.ClassNameProperties;
  38. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  39. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  40. import org.openspcoop2.pdd.core.AbstractCore;
  41. import org.openspcoop2.pdd.core.CostantiPdD;
  42. import org.openspcoop2.pdd.core.GestoreMessaggi;
  43. import org.openspcoop2.pdd.core.MessaggioServizioApplicativo;
  44. import org.openspcoop2.pdd.core.PdDContext;
  45. import org.openspcoop2.pdd.core.StatoServiziPdD;
  46. import org.openspcoop2.pdd.core.autenticazione.GestoreAutenticazione;
  47. import org.openspcoop2.pdd.core.autenticazione.pd.EsitoAutenticazionePortaDelegata;
  48. import org.openspcoop2.pdd.core.connettori.InfoConnettoreIngresso;
  49. import org.openspcoop2.pdd.core.credenziali.Credenziali;
  50. import org.openspcoop2.pdd.core.credenziali.GestoreCredenzialiConfigurationException;
  51. import org.openspcoop2.pdd.core.credenziali.IGestoreCredenzialiIM;
  52. import org.openspcoop2.pdd.core.handlers.GestoreHandlers;
  53. import org.openspcoop2.pdd.core.handlers.HandlerException;
  54. import org.openspcoop2.pdd.core.handlers.IntegrationManagerRequestContext;
  55. import org.openspcoop2.pdd.core.handlers.IntegrationManagerResponseContext;
  56. import org.openspcoop2.pdd.core.state.OpenSPCoopStateDBManager;
  57. import org.openspcoop2.pdd.core.state.OpenSPCoopStateful;
  58. import org.openspcoop2.pdd.core.transazioni.GestoreConsegnaMultipla;
  59. import org.openspcoop2.pdd.logger.Dump;
  60. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  61. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  62. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  63. import org.openspcoop2.pdd.logger.Tracciamento;
  64. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  65. import org.openspcoop2.pdd.services.service.RicezioneContenutiApplicativiIntegrationManagerService;
  66. import org.openspcoop2.pdd.timers.TimerMonitoraggioRisorseThread;
  67. import org.openspcoop2.pdd.timers.TimerThresholdThread;
  68. import org.openspcoop2.protocol.engine.LetturaParametriBusta;
  69. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  70. import org.openspcoop2.protocol.engine.URLProtocolContextImpl;
  71. import org.openspcoop2.protocol.engine.constants.Costanti;
  72. import org.openspcoop2.protocol.engine.driver.RepositoryBuste;
  73. import org.openspcoop2.protocol.sdk.Busta;
  74. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  75. import org.openspcoop2.protocol.sdk.ProtocolException;
  76. import org.openspcoop2.protocol.sdk.ProtocolMessage;
  77. import org.openspcoop2.protocol.sdk.builder.EsitoTransazione;
  78. import org.openspcoop2.protocol.sdk.builder.IBustaBuilder;
  79. import org.openspcoop2.protocol.sdk.builder.ProprietaManifestAttachments;
  80. import org.openspcoop2.protocol.sdk.constants.CodiceErroreIntegrazione;
  81. import org.openspcoop2.protocol.sdk.constants.ErroreIntegrazione;
  82. import org.openspcoop2.protocol.sdk.constants.ErroriIntegrazione;
  83. import org.openspcoop2.protocol.sdk.constants.EsitoTransazioneName;
  84. import org.openspcoop2.protocol.sdk.constants.FaseSbustamento;
  85. import org.openspcoop2.protocol.sdk.constants.IDService;
  86. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  87. import org.openspcoop2.protocol.sdk.constants.RuoloMessaggio;
  88. import org.openspcoop2.protocol.sdk.state.URLProtocolContext;
  89. import org.openspcoop2.protocol.utils.ErroriProperties;
  90. import org.openspcoop2.utils.LoggerWrapperFactory;
  91. import org.openspcoop2.utils.Semaphore;
  92. import org.openspcoop2.utils.SemaphoreLock;
  93. import org.openspcoop2.utils.UtilsException;
  94. import org.openspcoop2.utils.date.DateManager;
  95. import org.openspcoop2.utils.id.IUniqueIdentifier;
  96. import org.openspcoop2.utils.id.UniqueIdentifierManager;
  97. import org.openspcoop2.utils.resources.Loader;
  98. import org.openspcoop2.utils.transport.TransportRequestContext;
  99. import org.slf4j.Logger;

  100.        
  101. /**
  102.  * IntegrationManager service
  103.  *
  104.  *
  105.  * @author Lo Votrico Fabio (fabio@link.it)
  106.  * @author Poli Andrea (apoli@link.it)
  107.  * @author Tronci Fabio (tronci@link.it)
  108.  * @author Nardi Lorenzo (nardi@link.it)
  109.  * @author $Author$
  110.  * @version $Rev$, $Date$
  111.  */
  112.        
  113. public abstract class IntegrationManager implements IntegrationManagerMessageBoxInterface,IntegrationManagerPDInterface {

  114.     public static final IDService ID_SERVICE = IDService.INTEGRATION_MANAGER_SOAP;
  115.     public static final String ID_MODULO = ID_SERVICE.getValue();
  116.    
  117.     private static void logError(Logger logCore, String msg) {
  118.         logCore.error(msg);
  119.     }
  120.     private static void logError(Logger logCore, String msg, Throwable e) {
  121.         logCore.error(msg,e);
  122.     }
  123.    
  124.     private OpenSPCoop2Properties propertiesReader;
  125.     private ClassNameProperties className;

  126.     private static final boolean useNewMethod = true; // compatta diverse query e usa le date

  127.     private boolean inizializzato = false;

  128.     /** Indicazione se il servizio PD risulta attivo */
  129.     private static Semaphore semaphore = new Semaphore(ID_MODULO);
  130.     private static Boolean staticInitialized = false;
  131.    
  132.     private void init(){
  133.         if(!this.inizializzato){
  134.             this.propertiesReader = OpenSPCoop2Properties.getInstance();
  135.             this.className = ClassNameProperties.getInstance();
  136.             this.inizializzato = true;
  137.             SemaphoreLock lock = semaphore.acquireThrowRuntime("init");
  138.             try {
  139.                 if(!IntegrationManager.staticInitialized){
  140.                     IntegrationManager.staticInitialized = true;
  141.                 }
  142.             }finally {
  143.                 semaphore.release(lock, "init");
  144.             }
  145.         }
  146.     }


  147.     protected abstract HttpServletRequest getHttpServletRequest() throws IntegrationManagerException;
  148.     protected abstract HttpServletResponse getHttpServletResponse() throws IntegrationManagerException;

  149.     private ErroriProperties getErroriProperties(Logger log) {
  150.         ErroriProperties erroriProperties = null;
  151.         try {
  152.             erroriProperties = ErroriProperties.getInstance(log);
  153.         }catch(Exception ignore) {
  154.             // non succede
  155.         }
  156.         return erroriProperties;
  157.     }
  158.    
  159.     private IProtocolFactory<?> getProtocolFactory(Logger log) throws IntegrationManagerException{
  160.         try {
  161.             String protocolName = (String) getHttpServletRequest().getAttribute(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME.getValue());
  162.             return ProtocolFactoryManager.getInstance().getProtocolFactoryByName(protocolName);
  163.         } catch (Exception e) {
  164.             log.error("Errore durante il recupero della ProtocolFactory: "+e.getMessage(),e);
  165.             throw new IntegrationManagerException(null,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),
  166.                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(log));
  167.         }
  168.     }
  169.    
  170.     private void checkIMAuthorization(Logger log) throws IntegrationManagerException{
  171.         try {
  172.             Object o = getHttpServletRequest().getAttribute(org.openspcoop2.core.constants.Costanti.INTEGRATION_MANAGER_ENGINE_AUTHORIZED.getValue());
  173.             if(!(o instanceof Boolean)){
  174.                 throw new CoreException("Invocazione del Servizio non autorizzata");
  175.             }
  176.             Boolean b = (Boolean) o;
  177.             if(!b.booleanValue()){
  178.                 throw new CoreException("Invocazione del Servizio non autorizzata");
  179.             }
  180.         } catch (Exception e) {
  181.             log.error(e.getMessage(),e);
  182.             throw new IntegrationManagerException(null,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),
  183.                     IntegrationFunctionError.AUTHORIZATION, this.getErroriProperties(log));
  184.         }
  185.     }
  186.     private void setNomePortaDelegata(Logger log,String nomePorta) throws IntegrationManagerException{
  187.         try {
  188.             getHttpServletRequest().setAttribute(org.openspcoop2.core.constants.Costanti.PORTA_DELEGATA.getValue(), nomePorta);
  189.         } catch (Exception e) {
  190.             log.error(e.getMessage(),e);
  191.             throw new IntegrationManagerException(null,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),
  192.                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(log));
  193.         }
  194.     }
  195.    
  196.    
  197.     public static InfoConnettoreIngresso buildInfoConnettoreIngresso(javax.servlet.http.HttpServletRequest req,Credenziali credenziali,URLProtocolContext urlProtocolContext){
  198.         // Informazioni connettore ingresso
  199.         InfoConnettoreIngresso connettoreIngresso = new InfoConnettoreIngresso();
  200.         connettoreIngresso.setCredenziali(credenziali);
  201.         connettoreIngresso.setFromLocation(urlProtocolContext.getSource());
  202.         connettoreIngresso.setUrlProtocolContext(urlProtocolContext);
  203.         return connettoreIngresso;
  204.     }
  205.    
  206.     private IntegrationManagerRequestContext buildIMRequestContext(Date dataRichiestaOperazione,
  207.             Operazione tipoOperazione, PdDContext pddContext, Logger logCore,IProtocolFactory<?> protocolFactory) throws IntegrationManagerException, ProtocolException, UtilsException{
  208.        
  209.         IntegrationManagerRequestContext imRequestContext =
  210.             new IntegrationManagerRequestContext(dataRichiestaOperazione, tipoOperazione, pddContext, logCore,protocolFactory);
  211.        
  212.         // Raccolta oggetti da contesto
  213.         Credenziali credenziali = null;
  214.         javax.servlet.http.HttpServletRequest req = getHttpServletRequest();
  215.         URLProtocolContext urlProtocolContext = new URLProtocolContextImpl(req,logCore,true,true,this.propertiesReader.getCustomContexts());
  216.         try {
  217.             credenziali = new Credenziali(urlProtocolContext.getCredential());
  218.         }catch(Exception e){
  219.             credenziali = new Credenziali();
  220.         }
  221.         imRequestContext.setConnettore(buildInfoConnettoreIngresso(req, credenziali, urlProtocolContext));
  222.        
  223.         return imRequestContext;
  224.     }

  225.     /** IGestoreCredenziali: lista di gestori delle credenziali */
  226.     // E' stato aggiunto lo stato dentro l'oggetto.
  227.     private String [] tipiGestoriCredenziali = null;
  228.     private synchronized void initializeGestoreCredenziali(Logger logCore,IProtocolFactory<?> protocolFactory,MsgDiagnostico msgDiag) throws IntegrationManagerException{
  229.         if(this.tipiGestoriCredenziali==null){
  230.            
  231.             Loader loader = Loader.getInstance();
  232.            
  233.             this.tipiGestoriCredenziali = this.propertiesReader.getTipoGestoreCredenzialiIM();
  234.             if(this.tipiGestoriCredenziali!=null){
  235.                 for (int i = 0; i < this.tipiGestoriCredenziali.length; i++) {
  236.                     String classType = this.className.getGestoreCredenzialiIM(this.tipiGestoriCredenziali[i]);
  237.                     try {
  238.                         IGestoreCredenzialiIM gestore = (IGestoreCredenzialiIM)loader.newInstance(classType);
  239.                         gestore.toString();
  240.                     } catch (Exception e) {
  241.                         msgDiag.logErroreGenerico(e, "InizializzazioneGestoreCredenziali("+this.tipiGestoriCredenziali[i]+")");
  242.                         throw new IntegrationManagerException(protocolFactory,
  243.                                 ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  244.                                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_548_GESTORE_CREDENZIALI_NON_FUNZIONANTE),
  245.                                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  246.                     }
  247.                 }
  248.             }
  249.         }
  250.     }
  251.     private void gestioneCredenziali(Logger logCore,IProtocolFactory<?> protocolFactory,MsgDiagnostico msgDiag,
  252.             InfoConnettoreIngresso infoConnettoreIngresso,PdDContext pddContext) throws IntegrationManagerException {
  253.         if(this.tipiGestoriCredenziali==null){
  254.             initializeGestoreCredenziali(logCore,protocolFactory,msgDiag);
  255.         }
  256.         if(this.tipiGestoriCredenziali!=null){
  257.             msgDiag.mediumDebug("Gestione personalizzata delle credenziali...");
  258.            
  259.             Loader loader = Loader.getInstance();
  260.            
  261.             for (int i = 0; i < this.tipiGestoriCredenziali.length; i++) {
  262.                 try {
  263.                                    
  264.                     String classType = null;
  265.                     IGestoreCredenzialiIM gestore = null;
  266.                     try {
  267.                         classType = this.className.getGestoreCredenzialiIM(this.tipiGestoriCredenziali[i]);
  268.                         gestore = (IGestoreCredenzialiIM)loader.newInstance(classType);
  269.                         AbstractCore.init(gestore, pddContext, protocolFactory);
  270.                     } catch (Exception e) {
  271.                         msgDiag.logErroreGenerico(e, "InizializzazioneGestoreCredenziali("+this.tipiGestoriCredenziali[i]+")");
  272.                         throw new IntegrationManagerException(protocolFactory,
  273.                                 ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  274.                                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_548_GESTORE_CREDENZIALI_NON_FUNZIONANTE),
  275.                                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  276.                     }
  277.                    
  278.                     if (gestore != null) {
  279.                         Credenziali credenzialiRitornate = gestore.elaborazioneCredenziali(infoConnettoreIngresso);
  280.                         if(credenzialiRitornate==null){
  281.                             throw new CoreException("Credenziali non ritornate");
  282.                         }
  283.                         if(infoConnettoreIngresso.getCredenziali().equals(credenzialiRitornate) == false){
  284.                             String nuoveCredenziali = credenzialiRitornate.toString();
  285.                             nuoveCredenziali = nuoveCredenziali.substring(0,(nuoveCredenziali.length()-1));
  286.                             msgDiag.addKeyword(CostantiPdD.KEY_NUOVE_CREDENZIALI,nuoveCredenziali);
  287.                             String identita = gestore.getIdentitaGestoreCredenziali();
  288.                             if(identita==null){
  289.                                 identita = "Gestore delle credenziali di tipo "+this.tipiGestoriCredenziali[i];
  290.                             }
  291.                             msgDiag.addKeyword(CostantiPdD.KEY_IDENTITA_GESTORE_CREDENZIALI, identita);
  292.                             pddContext.addObject(org.openspcoop2.core.constants.Costanti.IDENTITA_GESTORE_CREDENZIALI, identita);
  293.                             msgDiag.logPersonalizzato("gestoreCredenziali.nuoveCredenziali");
  294.                             // update credenziali
  295.                             infoConnettoreIngresso.setCredenziali(credenzialiRitornate);    
  296.                         }
  297.                     } else {
  298.                         throw new CoreException("non inizializzato");
  299.                     }
  300.                 }
  301.                 catch (Exception e) {
  302.                     OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("Errore durante l'identificazione delle credenziali ["+ this.tipiGestoriCredenziali[i]
  303.                              + "]: "+ e.getMessage(),e);
  304.                     msgDiag.addKeyword(CostantiPdD.KEY_TIPO_GESTORE_CREDENZIALI,this.tipiGestoriCredenziali[i]);
  305.                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, e.getMessage());
  306.                     msgDiag.logPersonalizzato("gestoreCredenziali.errore");
  307.                     ErroreIntegrazione errore = null;
  308.                     IntegrationFunctionError integrationFunctionError = null;
  309.                     if(e instanceof GestoreCredenzialiConfigurationException){
  310.                         GestoreCredenzialiConfigurationException ge = (GestoreCredenzialiConfigurationException) e;
  311.                         integrationFunctionError = ge.getIntegrationFunctionError();
  312.                         errore = ErroriIntegrazione.ERRORE_431_GESTORE_CREDENZIALI_ERROR.
  313.                                 getErrore431_ErroreGestoreCredenziali(this.tipiGestoriCredenziali[i], e);
  314.                     }else{
  315.                         errore = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  316.                                 get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_548_GESTORE_CREDENZIALI_NON_FUNZIONANTE);
  317.                     }
  318.                     if(integrationFunctionError==null) {
  319.                         integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  320.                     }
  321.                    
  322.                     throw new IntegrationManagerException(protocolFactory,errore,
  323.                             integrationFunctionError, this.getErroriProperties(logCore));
  324.                    
  325.                 }
  326.             }
  327.         }
  328.     }

  329.     /**
  330.      * Effettua il processo di autenticazione
  331.      *
  332.      * @return il nome del Servizio Applicativo invocante
  333.      *
  334.      */
  335.     private IDServizioApplicativo autenticazione(Logger logCore, IProtocolFactory<?> protocolFactory,MsgDiagnostico msgDiag,InfoConnettoreIngresso infoConnettoreIngresso,
  336.             ConfigurazionePdDManager configPdDManager,PdDContext pddContext) throws IntegrationManagerException {
  337.        
  338.         Credenziali credenziali = infoConnettoreIngresso.getCredenziali();
  339.        
  340.         // Autenticazione
  341.         String credenzialiFornite = "";
  342.         if(credenziali!=null){
  343.             credenzialiFornite = credenziali.toString();
  344.         }      
  345.         msgDiag.addKeyword(CostantiPdD.KEY_CREDENZIALI_SA_FRUITORE, credenzialiFornite);

  346.         IDServizioApplicativo servizioApplicativo = null;      
  347.         String [] tipoAutenticazione = configPdDManager.getIntegrationManagerAuthentication();
  348.         if(tipoAutenticazione==null || tipoAutenticazione.length<1){
  349.             msgDiag.logPersonalizzato("autenticazioneNonImpostata");
  350.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  351.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_519_INTEGRATION_MANAGER_CONFIGURATION_ERROR),
  352.                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  353.         }
  354.         for(int i=0; i<tipoAutenticazione.length; i++){
  355.             if(CostantiConfigurazione.INVOCAZIONE_SERVIZIO_AUTENTICAZIONE_NONE.toString().equalsIgnoreCase(tipoAutenticazione[i]) == true){
  356.                 msgDiag.logPersonalizzato("autenticazioneNonImpostata");
  357.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  358.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_519_INTEGRATION_MANAGER_CONFIGURATION_ERROR),
  359.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  360.             }
  361.         }
  362.        
  363.         StringBuilder errori = new StringBuilder();
  364.         for(int i=0; i<tipoAutenticazione.length; i++){
  365.            
  366.             org.openspcoop2.pdd.core.autenticazione.pd.DatiInvocazionePortaDelegata datiInvocazione = new org.openspcoop2.pdd.core.autenticazione.pd.DatiInvocazionePortaDelegata();
  367.             datiInvocazione.setInfoConnettoreIngresso(infoConnettoreIngresso);
  368.            
  369.             EsitoAutenticazionePortaDelegata esito = null;
  370.             try{
  371.                 esito = GestoreAutenticazione.verificaAutenticazioneMessageBox(tipoAutenticazione[i],
  372.                         datiInvocazione, null,
  373.                         pddContext, protocolFactory);
  374.             }catch(Exception e){
  375.                 msgDiag.logErroreGenerico(e,"Autenticazione("+tipoAutenticazione[i]+")");
  376.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  377.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_503_AUTENTICAZIONE),
  378.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  379.             }  
  380.             if(esito.getDetails()==null){
  381.                 msgDiag.addKeyword(CostantiPdD.KEY_DETAILS, "");
  382.             }else{
  383.                 msgDiag.addKeyword(CostantiPdD.KEY_DETAILS, " ("+esito.getDetails()+")");
  384.             }
  385.             if (esito.isClientAuthenticated()==false || esito.isClientIdentified() == false) {
  386.                 if(errori.length()>0 || tipoAutenticazione.length>1)
  387.                     errori.append("\n");
  388.                 try{
  389.                     if(esito.getErroreIntegrazione()!=null) {
  390.                         errori.append("(Autenticazione " +tipoAutenticazione[i]+") "+ esito.getErroreIntegrazione().getDescrizione(protocolFactory));
  391.                     }
  392.                     else {
  393.                         // l'errore puo' non esserci se l'identificazione non e' obbligatoria nella modalita' scelta.
  394.                         errori.append("(Autenticazione " +tipoAutenticazione[i]+") non ha identificato alcun servizio applicativo");
  395.                     }
  396.                 }catch(Exception e){
  397.                     OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("Errore durante l'identificazione dell'errore: "+e.getMessage(),e);
  398.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  399.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_519_INTEGRATION_MANAGER_CONFIGURATION_ERROR),
  400.                             IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  401.                 }
  402.             }
  403.             else{
  404.                 servizioApplicativo = esito.getIdServizioApplicativo();
  405.                 break; //sa individuato
  406.             }
  407.         }
  408.        
  409.         if(servizioApplicativo == null){
  410.             if(errori.length()>0){
  411.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, errori.toString());
  412.                 msgDiag.logPersonalizzato("servizioApplicativo.identificazioneTramiteCredenziali");
  413.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_402_AUTENTICAZIONE_FALLITA.
  414.                         getErrore402_AutenticazioneFallita(errori.toString()),
  415.                         IntegrationFunctionError.AUTHENTICATION, this.getErroriProperties(logCore));
  416.             }
  417.             else{
  418.                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, "servizio applicativo non autenticato");
  419.                 msgDiag.logPersonalizzato("servizioApplicativo.identificazioneTramiteCredenziali");
  420.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  421.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_503_AUTENTICAZIONE),
  422.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  423.             }
  424.         }
  425.        
  426.         msgDiag.addKeyword(CostantiPdD.KEY_SA_FRUITORE, servizioApplicativo.getNome());
  427.         msgDiag.addKeyword(CostantiPdD.KEY_SA_EROGATORE, servizioApplicativo.getNome());
  428.         msgDiag.setServizioApplicativo(servizioApplicativo.getNome());
  429.         if(servizioApplicativo.getIdSoggettoProprietario()!=null){
  430.             msgDiag.addKeyword(CostantiPdD.KEY_TIPO_MITTENTE_BUSTA_RICHIESTA, servizioApplicativo.getIdSoggettoProprietario().getTipo());
  431.             msgDiag.addKeyword(CostantiPdD.KEY_MITTENTE_BUSTA_RICHIESTA, servizioApplicativo.getIdSoggettoProprietario().getNome());
  432.             msgDiag.setFruitore(servizioApplicativo.getIdSoggettoProprietario());
  433.         }
  434.         return  servizioApplicativo;
  435.     }


  436.     /* ----------- Init -------------- */
  437.     private void verificaRisorseSistema(IProtocolFactory<?> protocolFactory,Logger logCore,String tipoOperazione) throws IntegrationManagerException {
  438.        
  439.         if( !OpenSPCoop2Startup.initialize){
  440.             logError(logCore, "["+IntegrationManager.ID_MODULO+"]["+tipoOperazione+"] Inizializzazione di GovWay non correttamente effettuata");
  441.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  442.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_501_PDD_NON_INIZIALIZZATA),
  443.                     IntegrationFunctionError.GOVWAY_NOT_INITIALIZED, this.getErroriProperties(logCore));
  444.         }
  445.         if( !TimerMonitoraggioRisorseThread.isRisorseDisponibili()){
  446.             logError(logCore, "["+IntegrationManager.ID_MODULO+"]["+tipoOperazione+"] Risorse di sistema non disponibili: "+TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile().getMessage(),TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile());
  447.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  448.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_532_RISORSE_NON_DISPONIBILI),
  449.                     IntegrationFunctionError.GOVWAY_RESOURCES_NOT_AVAILABLE, this.getErroriProperties(logCore));
  450.         }
  451.         if (!TimerThresholdThread.freeSpace) {
  452.             logError(logCore, "["+IntegrationManager.ID_MODULO+"]["+tipoOperazione+"] Non sono disponibili abbastanza risorse per la gestione della richiesta");
  453.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  454.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_533_RISORSE_DISPONIBILI_LIVELLO_CRITICO),
  455.                     IntegrationFunctionError.GOVWAY_RESOURCES_NOT_AVAILABLE, this.getErroriProperties(logCore));
  456.         }
  457.         if( !Tracciamento.tracciamentoDisponibile){
  458.             logError(logCore, "["+IntegrationManager.ID_MODULO+"]["+tipoOperazione+"] Tracciatura non disponibile: "+Tracciamento.motivoMalfunzionamentoTracciamento.getMessage(),Tracciamento.motivoMalfunzionamentoTracciamento);
  459.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  460.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_545_TRACCIATURA_NON_FUNZIONANTE),
  461.                     IntegrationFunctionError.GOVWAY_RESOURCES_NOT_AVAILABLE, this.getErroriProperties(logCore));
  462.         }
  463.         if( !MsgDiagnostico.gestoreDiagnosticaDisponibile){
  464.             logError(logCore, "["+IntegrationManager.ID_MODULO+"]["+tipoOperazione+"] Sistema di diagnostica non disponibile: "+MsgDiagnostico.motivoMalfunzionamentoDiagnostici.getMessage(),MsgDiagnostico.motivoMalfunzionamentoDiagnostici);
  465.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  466.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_546_DIAGNOSTICA_NON_FUNZIONANTE),
  467.                     IntegrationFunctionError.GOVWAY_RESOURCES_NOT_AVAILABLE, this.getErroriProperties(logCore));
  468.         }
  469.         if( !Dump.isSistemaDumpDisponibile()){
  470.             logError(logCore, "["+IntegrationManager.ID_MODULO+"]["+tipoOperazione+"] Sistema di dump dei contenuti applicativi non disponibile: "+Dump.getMotivoMalfunzionamentoDump().getMessage(),Dump.getMotivoMalfunzionamentoDump());
  471.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  472.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_547_DUMP_CONTENUTI_APPLICATIVI_NON_FUNZIONANTE),
  473.                     IntegrationFunctionError.GOVWAY_RESOURCES_NOT_AVAILABLE, this.getErroriProperties(logCore));
  474.         }
  475.         // Check Configurazione (XML)
  476.         try{
  477.             ConfigurazionePdDManager.getInstance().verificaConsistenzaConfigurazione();
  478.         }catch(Exception e){
  479.             logError(logCore, "["+IntegrationManager.ID_MODULO+"]["+tipoOperazione+"] Riscontrato errore durante la verifica della consistenza della configurazione PdD",e);
  480.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  481.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE),
  482.                     IntegrationFunctionError.GOVWAY_RESOURCES_NOT_AVAILABLE, this.getErroriProperties(logCore));
  483.         }
  484.        
  485.         boolean serviceIsEnabled = false;
  486.         Exception serviceIsEnabledExceptionProcessamento = null;
  487.         try{
  488.             serviceIsEnabled = StatoServiziPdD.isEnabledIntegrationManager();
  489.         }catch(Exception e){
  490.             serviceIsEnabledExceptionProcessamento = e;
  491.         }
  492.         if (!serviceIsEnabled || serviceIsEnabledExceptionProcessamento!=null) {
  493.             if(serviceIsEnabledExceptionProcessamento!=null){
  494.                 logError(logCore, "["+ IntegrationManager.ID_MODULO+ "]["+tipoOperazione+"] Identificazione stato servizio IntegrationManager non riuscita: "+serviceIsEnabledExceptionProcessamento.getMessage(),serviceIsEnabledExceptionProcessamento);
  495.             }else{
  496.                 logError(logCore, "["+ IntegrationManager.ID_MODULO+ "]["+tipoOperazione+"] Servizio IntegrationManager disabilitato");
  497.             }
  498.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  499.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_552_IM_SERVICE_NOT_ACTIVE),
  500.                     IntegrationFunctionError.API_SUSPEND, this.getErroriProperties(logCore));
  501.         }

  502.     }
  503.    
  504.     /* -------- Utility -------------- */
  505.     private IUniqueIdentifier getUniqueIdentifier(Logger logCore, IProtocolFactory<?> protocolFactory,MsgDiagnostico msgDiag,String tipoOperazione) throws IntegrationManagerException {
  506.         try{
  507.             return UniqueIdentifierManager.newUniqueIdentifier();
  508.         }catch(Exception e){
  509.             msgDiag.logErroreGenerico(e,"("+tipoOperazione+").getUniqueIdentifier()");
  510.             throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),
  511.                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  512.         }
  513.     }
  514.     private MsgDiagnostico getMsgDiagnostico(){
  515.         MsgDiagnostico msgDiag = MsgDiagnostico.newInstance(IntegrationManager.ID_MODULO);
  516.         msgDiag.setPrefixMsgPersonalizzati(MsgDiagnosticiProperties.MSG_DIAG_INTEGRATION_MANAGER);
  517.         return msgDiag;
  518.     }
  519.    
  520.     private EsitoTransazione getEsitoTransazione(IProtocolFactory<?> pf,IntegrationManagerRequestContext imRequestContext, EsitoTransazioneName name) throws ProtocolException{
  521.         TransportRequestContext t = null;
  522.         if(imRequestContext!=null && imRequestContext.getConnettore()!=null){
  523.             t = imRequestContext.getConnettore().getUrlProtocolContext();
  524.         }
  525.         return pf.createEsitoBuilder().getEsito(t,name);
  526.     }
  527.    


  528.     /*-------- getAllMessagesID ----*/

  529.     /**
  530.      * Restituisce gli id di tutti i messaggi in base al servizio_applicativo
  531.      * Al servizio e all'azione se presenti
  532.      *
  533.      * @param tipoServizio Filtro per Servizio
  534.      * @param servizio Filtro per Servizio
  535.      * @param azione Filtro per Azione
  536.      * @param counter Indica il numero di id da ritornare
  537.      * @return una Collezione di ID di risposte applicative destinate al servizio applicativo che ha invocato il servizio
  538.      *
  539.      */
  540.     private List<String> getAllMessagesId_engine(Operazione tipoOperazione,String tipoServizio,String servizio, Integer versioneServizio,
  541.             String azione,int counter, int offset) throws IntegrationManagerException {

  542.         // Timestamp
  543.         Date dataRichiestaOperazione = DateManager.getTimestamp();
  544.        
  545.         // Logger
  546.         Logger logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  547.         if(logCore==null)
  548.             logCore = LoggerWrapperFactory.getLogger(IntegrationManager.ID_MODULO);
  549.        
  550.         // check Autorizzazione
  551.         checkIMAuthorization(logCore);
  552.        
  553.         // ProtocolFactoyr
  554.         IProtocolFactory<?> protocolFactory = getProtocolFactory(logCore);
  555.        
  556.         // Verifica risorse sistema
  557.         this.verificaRisorseSistema(protocolFactory,logCore, tipoOperazione.toString());

  558.         MsgDiagnostico msgDiag = getMsgDiagnostico();
  559.         msgDiag.addKeyword(CostantiPdD.KEY_TIPO_OPERAZIONE_IM, tipoOperazione.toString());
  560.        
  561.         IDServizioApplicativo idServizioApplicativo = null;
  562.         OpenSPCoopStateful stato = null;
  563.        
  564.         // PddContext
  565.         PdDContext pddContext = new PdDContext();
  566.         String idTransazione = this.getUniqueIdentifier(logCore, protocolFactory,msgDiag,tipoOperazione.toString()).getAsString();
  567.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, idTransazione);
  568.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  569.        
  570.         IDServizio idServizio = null;
  571.         try {
  572.             int ver = -1;
  573.             if(versioneServizio!=null) {
  574.                 ver = versioneServizio;
  575.             }
  576.             idServizio = IDServizioFactory.getInstance().getIDServizioFromValuesWithoutCheck(tipoServizio,servizio,
  577.                 OpenSPCoop2Properties.getInstance().getIdentitaPortaDefault(protocolFactory.getProtocol(), null).getTipo(),
  578.                 OpenSPCoop2Properties.getInstance().getIdentitaPortaDefault(protocolFactory.getProtocol(), null).getNome(),
  579.                 ver);
  580.         } catch(Exception e) {
  581.             msgDiag.logErroreGenerico(e, "IDServizioFactory.getIDServizioFromValues");
  582.             ErroreIntegrazione erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione();
  583.             throw new IntegrationManagerException(protocolFactory,erroreIntegrazione,
  584.                     IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  585.         }
  586.         idServizio.setAzione(azione);
  587.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_SERVIZIO,idServizio);
  588.         msgDiag.setPddContext(pddContext, protocolFactory);
  589.        
  590.        
  591.        
  592.         /* ------------  IntegrationManagerRequestHandler ------------- */
  593.         IntegrationManagerRequestContext imRequestContext = null;
  594.         try {
  595.             imRequestContext = buildIMRequestContext(dataRichiestaOperazione, tipoOperazione, pddContext,logCore,protocolFactory);
  596.             GestoreHandlers.integrationManagerRequest(imRequestContext, msgDiag, logCore);
  597.         } catch(Exception e) {
  598.             ErroreIntegrazione erroreIntegrazione = null;
  599.             IntegrationFunctionError integrationFunctionError = null;
  600.             if(e instanceof HandlerException){
  601.                 HandlerException he = (HandlerException) e;
  602.                 integrationFunctionError = he.getIntegrationFunctionError();
  603.                 if(he.isEmettiDiagnostico()){
  604.                     msgDiag.logErroreGenerico(e, ((HandlerException)e).getIdentitaHandler());
  605.                 }
  606.                 erroreIntegrazione = he.convertToErroreIntegrazione();
  607.             } else {
  608.                 msgDiag.logErroreGenerico(e, "IntegrationManagerRequestHandler");
  609.             }
  610.             if(erroreIntegrazione==null){
  611.                 erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione();
  612.             }
  613.             if(integrationFunctionError==null) {
  614.                 integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  615.             }
  616.             throw new IntegrationManagerException(protocolFactory,erroreIntegrazione,
  617.                     integrationFunctionError, this.getErroriProperties(logCore));
  618.         }

  619.        
  620.        
  621.         /* ------------  Gestione Operazione ------------- */
  622.         IntegrationManagerResponseContext imResponseContext =
  623.             new IntegrationManagerResponseContext(dataRichiestaOperazione,tipoOperazione,pddContext,logCore,protocolFactory);
  624.         if(imRequestContext!=null){
  625.             imResponseContext.setConnettore(imRequestContext.getConnettore());
  626.         }
  627.        
  628.         try{
  629.            
  630.             // init stato
  631.             stato = new OpenSPCoopStateful();
  632.             stato.initResource(this.propertiesReader.getIdentitaPortaDefault(protocolFactory.getProtocol(), null),IntegrationManager.ID_MODULO, idTransazione,
  633.                     OpenSPCoopStateDBManager.messageBox);
  634.             ConfigurazionePdDManager configPdDManager = ConfigurazionePdDManager.getInstance(stato.getStatoRichiesta(),stato.getStatoRisposta());
  635.             msgDiag.updateState(configPdDManager);
  636.            
  637.             // gestione credenziali
  638.             this.gestioneCredenziali(logCore, protocolFactory,msgDiag, imRequestContext.getConnettore(),pddContext);
  639.                        
  640.             // Autenticazione Servizio Applicativo
  641.             idServizioApplicativo = autenticazione(logCore, protocolFactory,msgDiag,imRequestContext.getConnettore(),configPdDManager,pddContext);
  642.             imResponseContext.setServizioApplicativo(idServizioApplicativo);
  643.             String tipoServizioLog = "";
  644.             String servizioLog = "";
  645.             String azioneLog = "";
  646.             String counterLog = "";
  647.             if(tipoServizio!=null)
  648.                 tipoServizioLog = " tipoServizio["+tipoServizio+"]";
  649.             if(servizio!=null)
  650.                 servizioLog = " servizio["+servizio+"]";
  651.             if(azione!=null)
  652.                 azioneLog = " azione["+azione+"]";
  653.             if(counter>=0)
  654.                 counterLog = " counter["+counter+"]";
  655.             String param = "ServizioApplicativo["+idServizioApplicativo.getNome()+"]"+tipoServizioLog+servizioLog+azioneLog+counterLog;
  656.             msgDiag.addKeyword(CostantiPdD.KEY_PARAMETRI_OPERAZIONE_IM, param);
  657.             msgDiag.logPersonalizzato("logInvocazioneOperazione");

  658.             // Ricerca Messaggi
  659.             List<IdentificativoIM> ids = null;

  660.             GestoreMessaggi gestoreMessaggi = new GestoreMessaggi(stato, true, msgDiag,pddContext);

  661.             if(counter<0 && offset<0){
  662.                 ids = gestoreMessaggi.getIDMessaggi_ServizioApplicativo(idServizioApplicativo.getNome(),tipoServizio,servizio,azione);
  663.             }else if(offset<0){
  664.                 ids = gestoreMessaggi.getIDMessaggi_ServizioApplicativo(idServizioApplicativo.getNome(),tipoServizio,servizio,azione,counter);
  665.             }else{
  666.                 ids = gestoreMessaggi.getIDMessaggi_ServizioApplicativo(idServizioApplicativo.getNome(),tipoServizio,servizio,azione,counter,offset);
  667.             }
  668.             if(ids==null || ids.isEmpty()){
  669.                 msgDiag.logPersonalizzato("messaggiNonPresenti");
  670.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_406_INTEGRATION_MANAGER_MESSAGGI_FOR_SIL_NON_TROVATI.
  671.                         getErroreIntegrazione(),idServizioApplicativo,
  672.                         IntegrationFunctionError.IM_MESSAGES_NOT_FOUND, this.getErroriProperties(logCore));
  673.             }
  674.             List<String> listResponse = new ArrayList<>();
  675.             if(ids!=null && !ids.isEmpty()){
  676.                 for (IdentificativoIM id : ids) {
  677.                     if(this.propertiesReader.isIntegrationManagerIdWithDate()) {
  678.                         listResponse.add(id.getIdWithDate());
  679.                     }
  680.                     else {
  681.                         listResponse.add(id.getId());
  682.                     }  
  683.                 }
  684.             }

  685.             imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.OK));
  686.            
  687.             return listResponse;

  688.         }catch(Exception e){
  689.            
  690.             try{
  691.                 imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX));
  692.    
  693.                 if(e instanceof IntegrationManagerException){
  694.                     IntegrationManagerException exc = (IntegrationManagerException) e;
  695.                     if(CodiceErroreIntegrazione.CODICE_402_AUTENTICAZIONE_FALLITA.equals(exc.getCodiceErroreIntegrazione()) ||
  696.                             CodiceErroreIntegrazione.CODICE_431_GESTORE_CREDENZIALI_ERROR.equals(exc.getCodiceErroreIntegrazione())){
  697.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.AUTENTICAZIONE_FALLITA));
  698.                     }else if(CodiceErroreIntegrazione.CODICE_406_INTEGRATION_MANAGER_MESSAGGI_FOR_SIL_NON_TROVATI.equals(exc.getCodiceErroreIntegrazione())){
  699.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.MESSAGGI_NON_PRESENTI));
  700.                     }
  701.                 }
  702.             }catch(Exception eInteral){
  703.                 logError(logCore, "Errore durante la generazione dell'esito: "+eInteral.getMessage(),eInteral);
  704.                 imResponseContext.setEsito(EsitoTransazione.ESITO_TRANSAZIONE_ERROR);
  705.             }
  706.            
  707.             // Controllo Eccezioni
  708.             if(e instanceof IntegrationManagerException){
  709.                 // Lanciata all'interno del metodo
  710.                 throw (IntegrationManagerException)e;
  711.             }else{
  712.                 msgDiag.logErroreGenerico(e,"getAllMessagesId("+tipoOperazione+")");
  713.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),idServizioApplicativo,
  714.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  715.             }
  716.         }finally{
  717.             try{
  718.                 if(stato!=null)
  719.                     stato.releaseResource();
  720.             }catch(Exception eClose){}
  721.            
  722.            
  723.             /* ------------  IntegrationManagerResponseHandler ------------- */
  724.             imResponseContext.setDataCompletamentoOperazione(DateManager.getDate());
  725.             try{
  726.                 GestoreHandlers.integrationManagerResponse(imResponseContext, msgDiag, logCore);
  727.             }catch(Exception e){
  728.                 if(e instanceof HandlerException){
  729.                     HandlerException he = (HandlerException) e;
  730.                     if(he.isEmettiDiagnostico()){
  731.                         msgDiag.logErroreGenerico(e, ((HandlerException)e).getIdentitaHandler());
  732.                     }
  733.                 }else{
  734.                     msgDiag.logErroreGenerico(e, "IntegrationManagerResponseHandler");
  735.                 }
  736.             }
  737.         }
  738.     }
  739.     /**
  740.      * Restituisce gli id di tutti i messaggi in base al servizio_applicativo
  741.      *
  742.      * @return una Collezione di ID di risposte applicative destinate al servizio applicativo che ha invocato il servizio
  743.      *
  744.      */
  745.     @Override
  746.     public List<String> getAllMessagesId() throws IntegrationManagerException {
  747.         init();
  748.         return getAllMessagesId_engine(Operazione.getAllMessagesId,null,null,null,null,-1,-1);
  749.     }


  750.     /**
  751.      * Restituisce gli id di tutti i messaggi in base a servizio_applicativo, servizio
  752.      *
  753.      * @param tipoServizio Filtro per Servizio
  754.      * @param servizio Filtro per Servizio
  755.      * @param azione Filtro per Azione
  756.      * @return una Collezione di ID di risposte applicative destinate al servizio applicativo che ha invocato il servizio
  757.      *
  758.      */
  759.     @Override
  760.     public List<String> getAllMessagesIdByService(String tipoServizio, String servizio, String azione) throws IntegrationManagerException {
  761.         init();
  762.         return getAllMessagesId_engine(Operazione.getAllMessagesIdByService,tipoServizio,servizio,null,azione,-1,-1);
  763.     }


  764.     /**
  765.      * Restituisce gli id dei primi <var>counter</var> i messaggi, in base al servizio_applicativo,
  766.      *
  767.      * @param counter Indica il numero di id da ritornare
  768.      * @return una Collezione di ID di risposte applicative destinate al servizio applicativo che ha invocato il servizio
  769.      *
  770.      */
  771.     @Override
  772.     @Deprecated
  773.     public List<String> getNextMessagesId(int counter) throws IntegrationManagerException {
  774.         init();
  775.         return getAllMessagesId_engine(Operazione.getNextMessagesId,null,null,null,null,counter,-1);    
  776.     }

  777.     /**
  778.      *  Restituisce gli id dei primi <var>counter</var> i messaggi, in base a servizio_applicativo, servizio
  779.      *
  780.      * @param counter Indica il numero di id da ritornare
  781.      * @param tipoServizio Filtro per Servizio
  782.      * @param servizio Filtro per Servizio
  783.      * @param azione Filtro per Azione
  784.      * @return una Collezione di ID di risposte applicative destinate al servizio applicativo che ha invocato il servizio
  785.      *
  786.      */
  787.     @Override
  788.     @Deprecated
  789.     public List<String> getNextMessagesIdByService(int counter,String tipoServizio,String servizio, String azione) throws IntegrationManagerException {
  790.         init();
  791.         return getAllMessagesId_engine(Operazione.getNextMessagesIdByService,tipoServizio,servizio,null,azione,counter,-1);
  792.     }
  793.    
  794.     /**
  795.      * Restituisce gli id dei primi <var>counter</var> i messaggi, in base al servizio_applicativo,
  796.      *
  797.      * @param counter Indica il numero di id da ritornare
  798.      * @return una Collezione di ID di risposte applicative destinate al servizio applicativo che ha invocato il servizio
  799.      *
  800.      */
  801.     @Override
  802.     public List<String> getMessagesIdArray(int offset,int counter) throws IntegrationManagerException {
  803.         init();
  804.         return getAllMessagesId_engine(Operazione.getMessagesIdArray,null,null,null,null,counter,offset);  
  805.     }

  806.     /**
  807.      *  Restituisce gli id dei primi <var>counter</var> i messaggi, in base a servizio_applicativo, servizio
  808.      *
  809.      * @param counter Indica il numero di id da ritornare
  810.      * @param tipoServizio Filtro per Servizio
  811.      * @param servizio Filtro per Servizio
  812.      * @param azione Filtro per Azione
  813.      * @return una Collezione di ID di risposte applicative destinate al servizio applicativo che ha invocato il servizio
  814.      *
  815.      */
  816.     @Override
  817.     public List<String> getMessagesIdArrayByService(int offset,int counter,String tipoServizio,String servizio, String azione) throws IntegrationManagerException {
  818.         init();
  819.         return getAllMessagesId_engine(Operazione.getMessagesIdArrayByService,tipoServizio,servizio,null,azione,counter,offset);    
  820.     }









  821.     /* ------ Get ----- */

  822.     /**
  823.      * Recupera e restituisce un messaggio
  824.      *
  825.      * @param idMessaggio ID del Messaggio da recuperare
  826.      * @param isRiferimentoMessaggio Indicazione se l'id e' un riferimento messaggio
  827.      * @return un Message contenente il messaggio recuperato (e informazioni supplementari)
  828.      *
  829.      */
  830.     private IntegrationManagerMessage getMessage_engine(Operazione tipoOperazione, String idMessaggioParam, boolean isRiferimentoMessaggio) throws IntegrationManagerException {

  831.         // Timestamp
  832.         Date dataRichiestaOperazione = DateManager.getTimestamp();
  833.        
  834.         // Logger
  835.         Logger logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  836.         if(logCore==null)
  837.             logCore = LoggerWrapperFactory.getLogger(IntegrationManager.ID_MODULO);

  838.         // check Autorizzazione
  839.         checkIMAuthorization(logCore);
  840.        
  841.         // ProtocolFactoyr
  842.         IProtocolFactory<?> protocolFactory = getProtocolFactory(logCore);
  843.        
  844.         // Verifica risorse sistema
  845.         this.verificaRisorseSistema(protocolFactory,logCore, tipoOperazione.toString());

  846.         MsgDiagnostico msgDiag = getMsgDiagnostico();
  847.         msgDiag.addKeyword(CostantiPdD.KEY_TIPO_OPERAZIONE_IM, tipoOperazione.toString());

  848.         // Parse identificativo
  849.         String idMessaggio = null;
  850.         Date dataMessaggio = null;
  851.         if(this.propertiesReader.isIntegrationManagerIdWithDate()) {
  852.             IdentificativoIM idIM = IdentificativoIM.getIdentificativoIM(idMessaggioParam, logCore);
  853.             idMessaggio = idIM.getId();
  854.             dataMessaggio = idIM.getData();
  855.         }
  856.         else {
  857.             idMessaggio = idMessaggioParam;
  858.         }
  859.        
  860.         // Context
  861.         if(isRiferimentoMessaggio){
  862.             msgDiag.addKeyword(CostantiPdD.KEY_RIFERIMENTO_MESSAGGIO_RICHIESTA, idMessaggio);
  863.             msgDiag.addKeyword(CostantiPdD.KEY_RIFERIMENTO_MESSAGGIO_RISPOSTA, idMessaggio);
  864.         }else{
  865.             msgDiag.addKeyword(CostantiPdD.KEY_ID_MESSAGGIO_RICHIESTA, idMessaggio);
  866.             msgDiag.addKeyword(CostantiPdD.KEY_ID_MESSAGGIO_RISPOSTA, idMessaggio);
  867.         }
  868.        
  869.         IDServizioApplicativo idServizioApplicativo = null;
  870.         OpenSPCoopStateful stato = null;
  871.         // PddContext
  872.         PdDContext pddContext = new PdDContext();
  873.         String idTransazione = this.getUniqueIdentifier(logCore, protocolFactory,msgDiag,tipoOperazione.toString()).getAsString();
  874.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, idTransazione);
  875.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_MESSAGGIO,idMessaggio);
  876.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME,protocolFactory.getProtocol());
  877.         msgDiag.setPddContext(pddContext, protocolFactory);
  878.        
  879.        
  880.         /* ------------  IntegrationManagerRequesCHandler ------------- */
  881.         IntegrationManagerRequestContext imRequestContext = null;
  882.         try{
  883.             imRequestContext = buildIMRequestContext(dataRichiestaOperazione, tipoOperazione, pddContext,logCore,protocolFactory);
  884.             imRequestContext.setIdMessaggio(idMessaggio);
  885.             GestoreHandlers.integrationManagerRequest(imRequestContext, msgDiag, logCore);
  886.         }catch(Exception e){
  887.             ErroreIntegrazione erroreIntegrazione = null;
  888.             IntegrationFunctionError integrationFunctionError = null;
  889.             if(e instanceof HandlerException){
  890.                 HandlerException he = (HandlerException) e;
  891.                 integrationFunctionError = he.getIntegrationFunctionError();
  892.                 if(he.isEmettiDiagnostico()){
  893.                     msgDiag.logErroreGenerico(e, ((HandlerException)e).getIdentitaHandler());
  894.                 }
  895.                 erroreIntegrazione = he.convertToErroreIntegrazione();
  896.             }else{
  897.                 msgDiag.logErroreGenerico(e, "IntegrationManagerRequestHandler");
  898.             }
  899.             if(erroreIntegrazione==null){
  900.                 erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione();
  901.             }
  902.             if(integrationFunctionError==null) {
  903.                 integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  904.             }
  905.             throw new IntegrationManagerException(protocolFactory,erroreIntegrazione,
  906.                     integrationFunctionError, this.getErroriProperties(logCore));
  907.         }
  908.        
  909.        
  910.         /* ------------  Gestione Operazione ------------- */
  911.         IntegrationManagerResponseContext imResponseContext =
  912.             new IntegrationManagerResponseContext(dataRichiestaOperazione,tipoOperazione,pddContext,logCore,protocolFactory);
  913.         if(imRequestContext!=null){
  914.             imResponseContext.setConnettore(imRequestContext.getConnettore());
  915.         }
  916.         imResponseContext.setIdMessaggio(idMessaggio);
  917.         try{

  918.             // init stato
  919.             stato = new OpenSPCoopStateful();
  920.             stato.initResource(this.propertiesReader.getIdentitaPortaDefault(protocolFactory.getProtocol(), null),IntegrationManager.ID_MODULO, idTransazione,
  921.                     OpenSPCoopStateDBManager.messageBox);
  922.             ConfigurazionePdDManager configPdDManager = ConfigurazionePdDManager.getInstance(stato.getStatoRichiesta(),stato.getStatoRisposta());
  923.             msgDiag.updateState(configPdDManager);
  924.            
  925.             // gestione credenziali
  926.             this.gestioneCredenziali(logCore, protocolFactory,msgDiag, imRequestContext.getConnettore(),pddContext);
  927.            
  928.             // Autenticazione Servizio Applicativo
  929.             idServizioApplicativo = autenticazione(logCore, protocolFactory,msgDiag,imRequestContext.getConnettore(),configPdDManager,pddContext);
  930.             imResponseContext.setServizioApplicativo(idServizioApplicativo);
  931.             String param = "ServizioApplicativo["+idServizioApplicativo.getNome()+"] ID["+idMessaggio+"]";
  932.             msgDiag.addKeyword(CostantiPdD.KEY_PARAMETRI_OPERAZIONE_IM, param);
  933.             msgDiag.logPersonalizzato("logInvocazioneOperazione");

  934.             // Gestore Messaggio
  935.             GestoreMessaggi gestoreMessaggi = new GestoreMessaggi(stato, true, idMessaggio, Costanti.INBOX, msgDiag, pddContext);
  936.             MessaggioIM messaggioIM = null;
  937.             if(useNewMethod) {
  938.                 messaggioIM = gestoreMessaggi.readMessageForSIL(idServizioApplicativo.getNome(),isRiferimentoMessaggio, dataMessaggio);
  939.             }
  940.            
  941.             // Check Esistenza Messaggio
  942.             boolean exists = false;
  943.             if(useNewMethod) {
  944.                 exists = messaggioIM!=null;
  945.             }
  946.             else {
  947.                 exists = gestoreMessaggi.existsMessageForSIL(idServizioApplicativo.getNome(),isRiferimentoMessaggio);
  948.             }
  949.             if(!exists){
  950.                 msgDiag.addKeyword(CostantiPdD.KEY_ID_MESSAGGIO_TRANSACTION_MANAGER, idMessaggio);
  951.                 msgDiag.logPersonalizzato("messaggioNonTrovato");
  952.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_407_INTEGRATION_MANAGER_MSG_RICHIESTO_NON_TROVATO.
  953.                         getErroreIntegrazione(),idServizioApplicativo,
  954.                         IntegrationFunctionError.IM_MESSAGE_NOT_FOUND, this.getErroriProperties(logCore));
  955.             }

  956.             // Check Autorizzazione all'utilizzo di IntegrationManager
  957.             boolean authorized = false;
  958.             if(useNewMethod) {
  959.                 authorized = messaggioIM.isAuthorized();
  960.             }
  961.             else {
  962.                 authorized = gestoreMessaggi.checkAutorizzazione(idServizioApplicativo.getNome(),isRiferimentoMessaggio);
  963.             }
  964.             if(!authorized){
  965.                 msgDiag.logPersonalizzato("servizioApplicativo.nonAutorizzato");
  966.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_404_AUTORIZZAZIONE_FALLITA_SA.
  967.                         getErrore404_AutorizzazioneFallitaServizioApplicativo(idServizioApplicativo.getNome()),
  968.                         idServizioApplicativo,
  969.                         IntegrationFunctionError.AUTHORIZATION, this.getErroriProperties(logCore));
  970.             }

  971.             // GetIDMessaggio Richiesto
  972.             String idMessaggioRichiesto = idMessaggio;
  973.             try{
  974.                 if(isRiferimentoMessaggio) {
  975.                     if(useNewMethod) {
  976.                         idMessaggioRichiesto = messaggioIM.getIdentificativoRichiesta();
  977.                     }
  978.                     else {
  979.                         idMessaggioRichiesto = gestoreMessaggi.mapRiferimentoIntoIDBusta();
  980.                     }
  981.                 }
  982.             }catch(Exception e){
  983.                 msgDiag.addKeywordErroreProcessamento(e);
  984.                 msgDiag.logPersonalizzato("mappingRifMsgToId.nonRiuscito");
  985.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  986.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  987.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  988.             }

  989.             // Proprieta' Protocollo del Messaggio da ritornare
  990.             RepositoryBuste repository = new RepositoryBuste(stato.getStatoRichiesta(), true, protocolFactory);
  991.             ProtocolHeaderInfo protocolHeaderInfo = null;
  992.             IDSoggetto fruitore = null;
  993.             IDServizio idServizio = null;
  994.             Busta busta = null;
  995.             try{
  996.                 LetturaParametriBusta parametri = new LetturaParametriBusta();
  997.                 parametri.setMittente(true);
  998.                 parametri.setDestinatario(true);
  999.                 parametri.setRiferimentoMessaggio(true);
  1000.                 parametri.setServizio(true);
  1001.                 parametri.setAzione(true);
  1002.                 parametri.setCollaborazione(true);
  1003.                 busta = repository.getSomeValuesFromInBox(idMessaggioRichiesto,parametri,dataMessaggio);
  1004.                 if(busta!=null){
  1005.                     protocolHeaderInfo = new ProtocolHeaderInfo();
  1006.                     protocolHeaderInfo.setID(idMessaggioRichiesto);
  1007.                     protocolHeaderInfo.setRiferimentoMessaggio(busta.getRiferimentoMessaggio());
  1008.                     protocolHeaderInfo.setTipoMittente(busta.getTipoMittente());
  1009.                     protocolHeaderInfo.setMittente(busta.getMittente());
  1010.                     protocolHeaderInfo.setTipoDestinatario(busta.getTipoDestinatario());
  1011.                     protocolHeaderInfo.setDestinatario(busta.getDestinatario());
  1012.                     protocolHeaderInfo.setTipoServizio(busta.getTipoServizio());
  1013.                     protocolHeaderInfo.setServizio(busta.getServizio());
  1014.                     protocolHeaderInfo.setAzione(busta.getAzione());
  1015.                     protocolHeaderInfo.setIdCollaborazione(busta.getCollaborazione());
  1016.                     busta.setID(idMessaggioRichiesto);
  1017.                     msgDiag.addKeywords(busta, true);
  1018.                    
  1019.                     fruitore = new IDSoggetto(busta.getTipoMittente(),busta.getMittente());
  1020.                     idServizio = IDServizioFactory.getInstance().getIDServizioFromValues(busta.getTipoServizio(),busta.getServizio(),
  1021.                             busta.getTipoDestinatario(),busta.getDestinatario(),
  1022.                             busta.getVersioneServizio());

  1023.                 }
  1024.             }catch(Exception e){
  1025.                 msgDiag.logErroreGenerico(e,"ReadInformazioniProtocollo("+tipoOperazione+","+idMessaggioRichiesto+")");
  1026.                 if(e.getMessage()==null || (e.getMessage().indexOf("Busta non trovata")<0) ){
  1027.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1028.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1029.                             IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1030.                 }// else
  1031.                 //{
  1032.                 //busta non presente, il msg puo' cmq essere consumato
  1033.                 //}
  1034.             }


  1035.             // Indicazione se il messaggio deve essere sbustato
  1036.             boolean sbustamentoSoap = false;
  1037.             if(useNewMethod) {
  1038.                 sbustamentoSoap = messaggioIM.isSbustamentoSoap();
  1039.             }
  1040.             else {
  1041.                 sbustamentoSoap = gestoreMessaggi.sbustamentoSOAP(idServizioApplicativo.getNome(),isRiferimentoMessaggio);
  1042.             }
  1043.             boolean sbustamentoInformazioniProtocollo = false;
  1044.             if(useNewMethod) {
  1045.                 sbustamentoInformazioniProtocollo = messaggioIM.isSbustamentoInformazioniProtocollo();
  1046.             }
  1047.             else {
  1048.                 sbustamentoInformazioniProtocollo = gestoreMessaggi.sbustamentoInformazioniProtocollo(idServizioApplicativo.getNome(),isRiferimentoMessaggio);
  1049.             }

  1050.             // TipoMessaggio
  1051.             GestoreMessaggi gestoreMessaggiIdentificativoReale = null;
  1052.             RuoloMessaggio ruoloMessaggio = RuoloMessaggio.RICHIESTA;
  1053.             try{
  1054.                 gestoreMessaggiIdentificativoReale = new GestoreMessaggi(stato, true, idMessaggioRichiesto, Costanti.INBOX, msgDiag, pddContext);
  1055.                 if(useNewMethod) {
  1056.                     ruoloMessaggio = messaggioIM.getRiferimentoMessaggio()==null ? RuoloMessaggio.RICHIESTA : RuoloMessaggio.RISPOSTA;
  1057.                 }
  1058.                 else {
  1059.                     ruoloMessaggio = gestoreMessaggiIdentificativoReale.getRiferimentoMessaggio()==null ? RuoloMessaggio.RICHIESTA : RuoloMessaggio.RISPOSTA;
  1060.                 }
  1061.             }catch(Exception e){
  1062.                 logError(logCore, "Identificazione tipo messaggio non riuscita: "+e.getMessage(),e);
  1063.             }
  1064.            
  1065.             // Messaggio
  1066.             OpenSPCoop2Message consegnaMessage = null;
  1067.             try{
  1068.                 if(useNewMethod && gestoreMessaggiIdentificativoReale!=null) {
  1069.                     consegnaMessage = gestoreMessaggiIdentificativoReale.getMessage(dataMessaggio); // risoluzione riferimento messaggio gia' effettuata
  1070.                 }
  1071.                 else {
  1072.                     consegnaMessage = gestoreMessaggi.getMessage(isRiferimentoMessaggio);
  1073.                 }
  1074.             }catch(Exception e){
  1075.                 msgDiag.logErroreGenerico(e,"gestoreMessaggi.getMessage("+isRiferimentoMessaggio+","+tipoOperazione+")");
  1076.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1077.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1078.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1079.             }
  1080.            
  1081.             // Eventuale sbustamento
  1082.             if(sbustamentoInformazioniProtocollo){
  1083.                 try{
  1084.                     IBustaBuilder<?> bustaBuilder = protocolFactory.createBustaBuilder(stato.getStatoRichiesta());
  1085.                    
  1086.                     FaseSbustamento fase = null;
  1087.                     if(RuoloMessaggio.RICHIESTA.equals(ruoloMessaggio)){
  1088.                         fase = FaseSbustamento.PRE_CONSEGNA_RICHIESTA;
  1089.                     }else{
  1090.                         fase = FaseSbustamento.PRE_CONSEGNA_RISPOSTA;
  1091.                     }
  1092.                    
  1093.                     // attachments non gestiti!
  1094.                     ProprietaManifestAttachments proprietaManifest = this.propertiesReader.getProprietaManifestAttachments("standard");
  1095.                     proprietaManifest.setGestioneManifest(false);
  1096.                     ProtocolMessage  protocolMessage = bustaBuilder.sbustamento(consegnaMessage, pddContext,
  1097.                             busta, ruoloMessaggio, proprietaManifest, fase, null, null);
  1098.                     if(protocolMessage!=null) {
  1099.                         consegnaMessage = protocolMessage.getMessage(); // updated
  1100.                     }
  1101.                 }catch(Exception e){
  1102.                     msgDiag.logErroreGenerico(e,"gestoreMessaggi.getMessage("+isRiferimentoMessaggio+","+tipoOperazione+")");
  1103.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1104.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1105.                             IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));                
  1106.                 }
  1107.             }
  1108.            
  1109.             //  dump applicativo
  1110.             msgDiag.mediumDebug("Dump applicativo messaggio ritornato...");
  1111.             Dump dumpApplicativo = new Dump(this.propertiesReader.getIdentitaPortaDefault(protocolFactory.getProtocol(), null),
  1112.                     IntegrationManager.ID_MODULO,idMessaggio,
  1113.                     fruitore,idServizio,
  1114.                     TipoPdD.INTEGRATION_MANAGER,null,pddContext,
  1115.                     stato.getStatoRichiesta(),stato.getStatoRisposta(),
  1116.                     null);
  1117.             dumpApplicativo.dumpIntegrationManagerGetMessage(consegnaMessage);

  1118.             // Costruzione Message da ritornare
  1119.             IntegrationManagerMessage msgReturn = null;
  1120.             try{
  1121.                 if(!sbustamentoSoap){
  1122.                     msgReturn = new IntegrationManagerMessage(consegnaMessage,false,protocolHeaderInfo);
  1123.                 }else{
  1124.                     byte [] sbustato = TunnelSoapUtils.sbustamentoMessaggio(consegnaMessage);
  1125.                     msgReturn = new IntegrationManagerMessage(sbustato,false,protocolHeaderInfo);
  1126.                 }
  1127.             }catch(Exception e){
  1128.                 msgDiag.logErroreGenerico(e,"buildMsgReturn("+idMessaggio+","+tipoOperazione+")");
  1129.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1130.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_523_CREAZIONE_PROTOCOL_MESSAGE),idServizioApplicativo,
  1131.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1132.             }

  1133.             imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.OK));
  1134.             imResponseContext.setDimensioneMessaggioBytes(Long.valueOf(msgReturn.getMessage().length));
  1135.            
  1136.             // Informazione da salvare
  1137.             try {
  1138.                 TransazioneApplicativoServer transazioneApplicativoServer = null;
  1139.                 String nomePorta = null;
  1140.                 if(useNewMethod) {
  1141.                     transazioneApplicativoServer = new TransazioneApplicativoServer();
  1142.                     transazioneApplicativoServer.setIdTransazione(messaggioIM.getIdTransazione());
  1143.                     transazioneApplicativoServer.setServizioApplicativoErogatore(messaggioIM.getServizioApplicativo());
  1144.                     transazioneApplicativoServer.setDataRegistrazione(messaggioIM.getOraRegistrazione());
  1145.                     transazioneApplicativoServer.setDataPrelievoIm(DateManager.getDate());
  1146.                     transazioneApplicativoServer.setProtocollo(protocolFactory.getProtocol());
  1147.                     nomePorta = messaggioIM.getNomePorta();
  1148.                 }
  1149.                 else {
  1150.                     MessaggioServizioApplicativo info = gestoreMessaggiIdentificativoReale.readInfoDestinatario(idServizioApplicativo.getNome(), true, logCore);
  1151.                     if(info!=null) {
  1152.                         transazioneApplicativoServer = new TransazioneApplicativoServer();
  1153.                         transazioneApplicativoServer.setIdTransazione(info.getIdTransazione());
  1154.                         transazioneApplicativoServer.setServizioApplicativoErogatore(info.getServizioApplicativo());
  1155.                         transazioneApplicativoServer.setDataRegistrazione(info.getOraRegistrazione());
  1156.                         transazioneApplicativoServer.setDataPrelievoIm(DateManager.getDate());
  1157.                         transazioneApplicativoServer.setProtocollo(protocolFactory.getProtocol());
  1158.                         nomePorta = info.getNomePorta();
  1159.                     }
  1160.                 }
  1161.                 if(transazioneApplicativoServer!=null) {
  1162.                     IDPortaApplicativa idPA = new IDPortaApplicativa();
  1163.                     idPA.setNome(nomePorta);
  1164.                     try {
  1165.                         GestoreConsegnaMultipla.getInstance().safeUpdatePrelievoIM(transazioneApplicativoServer, idPA, stato, pddContext);
  1166.                     }catch(Throwable t) {
  1167.                         logError(logCore, "["+transazioneApplicativoServer.getIdTransazione()+"]["+transazioneApplicativoServer.getServizioApplicativoErogatore()+"] Errore durante il salvataggio delle informazioni relative al servizio applicativo: "+t.getMessage(),t);
  1168.                     }
  1169.                 }
  1170.             }catch(Exception e){
  1171.                 logError(logCore, "Salvataggio informazioni sulla transazione non riuscita: "+e.getMessage(),e);
  1172.             }
  1173.            
  1174.             return msgReturn;

  1175.         }catch(Exception e){
  1176.            
  1177.             try{
  1178.                 imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX));
  1179.                
  1180.                 if(e instanceof IntegrationManagerException){
  1181.                     IntegrationManagerException exc = (IntegrationManagerException) e;
  1182.                     if(CodiceErroreIntegrazione.CODICE_402_AUTENTICAZIONE_FALLITA.equals(exc.getCodiceErroreIntegrazione()) ||
  1183.                             CodiceErroreIntegrazione.CODICE_431_GESTORE_CREDENZIALI_ERROR.equals(exc.getCodiceErroreIntegrazione())){
  1184.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.AUTENTICAZIONE_FALLITA));
  1185.                     }else if(CodiceErroreIntegrazione.CODICE_407_INTEGRATION_MANAGER_MSG_RICHIESTO_NON_TROVATO.equals(exc.getCodiceErroreIntegrazione())){
  1186.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.MESSAGGIO_NON_TROVATO));
  1187.                     }else if(CodiceErroreIntegrazione.CODICE_404_AUTORIZZAZIONE_FALLITA.equals(exc.getCodiceErroreIntegrazione())){
  1188.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.AUTORIZZAZIONE_FALLITA));
  1189.                     }
  1190.                 }
  1191.             }catch(Exception eInteral){
  1192.                 logError(logCore, "Errore durante la generazione dell'esito: "+eInteral.getMessage(),eInteral);
  1193.                 imResponseContext.setEsito(EsitoTransazione.ESITO_TRANSAZIONE_ERROR);
  1194.             }
  1195.            
  1196.             // Controllo Eccezioni
  1197.             if(e instanceof IntegrationManagerException){
  1198.                 // Lanciata all'interno del metodo
  1199.                 throw (IntegrationManagerException)e;
  1200.             }else{  
  1201.                 msgDiag.logErroreGenerico(e,"getMessage("+tipoOperazione+")");
  1202.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),idServizioApplicativo,
  1203.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1204.             }
  1205.         }finally{
  1206.             try{
  1207.                 if(stato!=null)
  1208.                     stato.releaseResource();
  1209.             }catch(Exception eClose){}
  1210.            
  1211.            
  1212.            
  1213.             /* ------------  IntegrationManagerResponseHandler ------------- */
  1214.             imResponseContext.setDataCompletamentoOperazione(DateManager.getDate());
  1215.             try{
  1216.                 GestoreHandlers.integrationManagerResponse(imResponseContext, msgDiag, logCore);
  1217.             }catch(Exception e){
  1218.                 if(e instanceof HandlerException){
  1219.                     HandlerException he = (HandlerException) e;
  1220.                     if(he.isEmettiDiagnostico()){
  1221.                         msgDiag.logErroreGenerico(e, ((HandlerException)e).getIdentitaHandler());
  1222.                     }
  1223.                 }else{
  1224.                     msgDiag.logErroreGenerico(e, "IntegrationManagerResponseHandler");
  1225.                 }
  1226.             }
  1227.         }
  1228.     }

  1229.     /**
  1230.      * Recupera e restituisce un messaggio
  1231.      *
  1232.      * @param idMessaggio ID del Messaggio da recuperare
  1233.      * @return un Message contenente il messaggio recuperato (e informazioni supplementari)
  1234.      *
  1235.      */
  1236.     @Override
  1237.     public IntegrationManagerMessage getMessage(String idMessaggio) throws IntegrationManagerException {
  1238.         init();
  1239.         return getMessage_engine(Operazione.getMessage,idMessaggio,false);
  1240.     }

  1241.     /**
  1242.      * Recupera e restituisce un messaggio cercandolo per riferimentoMessaggio
  1243.      *
  1244.      * @param riferimentoMsg del Messaggio da recuperare
  1245.      * @return un Message contenente il messaggio recuperato (e informazioni supplementari)
  1246.      *
  1247.      */
  1248.     @Override
  1249.     public IntegrationManagerMessage getMessageByReference(String riferimentoMsg) throws IntegrationManagerException {
  1250.         init();
  1251.         return getMessage_engine(Operazione.getMessageByReference,riferimentoMsg,true);
  1252.     }





















  1253.     /* -------- delete ------ */
  1254.     /**
  1255.      * Cancella un messaggio
  1256.      *
  1257.      * @param idMessaggio ID del Messaggio da recuperare
  1258.      * @param isRiferimentoMessaggio Indicazione se l'id e' un riferimento messaggio
  1259.      *
  1260.      */
  1261.     private void deleteMessage_engine(Operazione tipoOperazione,String idMessaggioParam,boolean isRiferimentoMessaggio) throws IntegrationManagerException {

  1262.         // Timestamp
  1263.         Date dataRichiestaOperazione = DateManager.getTimestamp();
  1264.        
  1265.         // Logger
  1266.         Logger logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  1267.         if(logCore==null)
  1268.             logCore = LoggerWrapperFactory.getLogger(IntegrationManager.ID_MODULO);

  1269.         // check Autorizzazione
  1270.         checkIMAuthorization(logCore);
  1271.        
  1272.         // ProtocolFactoyr
  1273.         IProtocolFactory<?> protocolFactory = getProtocolFactory(logCore);
  1274.        
  1275.         // Verifica risorse sistema
  1276.         this.verificaRisorseSistema(protocolFactory,logCore, tipoOperazione.toString());

  1277.         MsgDiagnostico msgDiag = getMsgDiagnostico();
  1278.         msgDiag.addKeyword(CostantiPdD.KEY_TIPO_OPERAZIONE_IM, tipoOperazione.toString());
  1279.        
  1280.         // Parse identificativo
  1281.         String idMessaggio = null;
  1282.         Date dataMessaggio = null;
  1283.         if(this.propertiesReader.isIntegrationManagerIdWithDate()) {
  1284.             IdentificativoIM idIM = IdentificativoIM.getIdentificativoIM(idMessaggioParam, logCore);
  1285.             idMessaggio = idIM.getId();
  1286.             dataMessaggio = idIM.getData();
  1287.         }
  1288.         else {
  1289.             idMessaggio = idMessaggioParam;
  1290.         }
  1291.        
  1292.         // Context
  1293.         if(isRiferimentoMessaggio){
  1294.             msgDiag.addKeyword(CostantiPdD.KEY_RIFERIMENTO_MESSAGGIO_RICHIESTA, idMessaggio);
  1295.             msgDiag.addKeyword(CostantiPdD.KEY_RIFERIMENTO_MESSAGGIO_RISPOSTA, idMessaggio);
  1296.         }else{
  1297.             msgDiag.addKeyword(CostantiPdD.KEY_ID_MESSAGGIO_RICHIESTA, idMessaggio);
  1298.             msgDiag.addKeyword(CostantiPdD.KEY_ID_MESSAGGIO_RISPOSTA, idMessaggio);
  1299.         }
  1300.        
  1301.         GestoreMessaggi gestoreMessaggi = null;
  1302.         IDServizioApplicativo idServizioApplicativo = null;
  1303.         String servizioApplicativo = null;
  1304.         OpenSPCoopStateful stato = null;
  1305.         // PddContext
  1306.         PdDContext pddContext = new PdDContext();
  1307.         String idTransazione = this.getUniqueIdentifier(logCore, protocolFactory,msgDiag,tipoOperazione.toString()).getAsString();
  1308.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, idTransazione);
  1309.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_MESSAGGIO,idMessaggio);
  1310.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  1311.         msgDiag.setPddContext(pddContext, protocolFactory);
  1312.        
  1313.        
  1314.        
  1315.         /* ------------  IntegrationManagerRequesCHandler ------------- */
  1316.         IntegrationManagerRequestContext imRequestContext = null;
  1317.         try{
  1318.             imRequestContext = buildIMRequestContext(dataRichiestaOperazione, tipoOperazione, pddContext,logCore,protocolFactory);
  1319.             imRequestContext.setIdMessaggio(idMessaggio);
  1320.             GestoreHandlers.integrationManagerRequest(imRequestContext, msgDiag, logCore);
  1321.         }catch(Exception e){
  1322.             ErroreIntegrazione erroreIntegrazione = null;
  1323.             IntegrationFunctionError integrationFunctionError = null;
  1324.             if(e instanceof HandlerException){
  1325.                 HandlerException he = (HandlerException) e;
  1326.                 integrationFunctionError = he.getIntegrationFunctionError();
  1327.                 if(he.isEmettiDiagnostico()){
  1328.                     msgDiag.logErroreGenerico(e, ((HandlerException)e).getIdentitaHandler());
  1329.                 }
  1330.                 erroreIntegrazione = he.convertToErroreIntegrazione();
  1331.             }else{
  1332.                 msgDiag.logErroreGenerico(e, "IntegrationManagerRequestHandler");
  1333.             }
  1334.             if(erroreIntegrazione==null){
  1335.                 erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione();
  1336.             }
  1337.             if(integrationFunctionError==null) {
  1338.                 integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  1339.             }
  1340.             throw new IntegrationManagerException(protocolFactory,erroreIntegrazione,
  1341.                     integrationFunctionError, this.getErroriProperties(logCore));
  1342.         }
  1343.        
  1344.        
  1345.         /* ------------  Gestione Operazione ------------- */
  1346.         IntegrationManagerResponseContext imResponseContext =
  1347.             new IntegrationManagerResponseContext(dataRichiestaOperazione,tipoOperazione,pddContext,logCore,protocolFactory);
  1348.         if(imRequestContext!=null){
  1349.             imResponseContext.setConnettore(imRequestContext.getConnettore());
  1350.         }
  1351.         imResponseContext.setIdMessaggio(idMessaggio);
  1352.         try{    

  1353.             // init stato
  1354.             stato = new OpenSPCoopStateful();
  1355.             stato.initResource(this.propertiesReader.getIdentitaPortaDefault(protocolFactory.getProtocol(), null),IntegrationManager.ID_MODULO, idTransazione,
  1356.                     OpenSPCoopStateDBManager.messageBox);
  1357.             ConfigurazionePdDManager configPdDManager = ConfigurazionePdDManager.getInstance(stato.getStatoRichiesta(),stato.getStatoRisposta());
  1358.             msgDiag.updateState(configPdDManager);  
  1359.            
  1360.             // gestione credenziali
  1361.             this.gestioneCredenziali(logCore, protocolFactory,msgDiag, imRequestContext.getConnettore(),pddContext);
  1362.            
  1363.             // Autenticazione Servizio Applicativo
  1364.             idServizioApplicativo = autenticazione(logCore, protocolFactory,msgDiag,imRequestContext.getConnettore(),configPdDManager,pddContext);
  1365.             servizioApplicativo = idServizioApplicativo.getNome();
  1366.             imResponseContext.setServizioApplicativo(idServizioApplicativo);
  1367.             String param = "ServizioApplicativo["+servizioApplicativo+"] ID["+idMessaggio+"]";
  1368.             msgDiag.addKeyword(CostantiPdD.KEY_PARAMETRI_OPERAZIONE_IM, param);
  1369.             msgDiag.logPersonalizzato("logInvocazioneOperazione");

  1370.             // Gestore Messaggio
  1371.             gestoreMessaggi = new GestoreMessaggi(stato, true, idMessaggio, Costanti.INBOX, msgDiag, pddContext);
  1372.             MessaggioIM messaggioIM = null;
  1373.             if(useNewMethod) {
  1374.                 messaggioIM = gestoreMessaggi.readMessageForSIL(idServizioApplicativo.getNome(),isRiferimentoMessaggio, dataMessaggio);
  1375.             }
  1376.            
  1377.             // Check Esistenza Messaggio
  1378.             boolean exists = false;
  1379.             if(useNewMethod) {
  1380.                 exists = messaggioIM!=null;
  1381.             }
  1382.             else {
  1383.                 exists = gestoreMessaggi.existsMessageForSIL(servizioApplicativo,isRiferimentoMessaggio);
  1384.             }
  1385.             if(!exists){
  1386.                 msgDiag.addKeyword(CostantiPdD.KEY_ID_MESSAGGIO_TRANSACTION_MANAGER, idMessaggio);
  1387.                 msgDiag.logPersonalizzato("messaggioNonTrovato");
  1388.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_407_INTEGRATION_MANAGER_MSG_RICHIESTO_NON_TROVATO.
  1389.                         getErroreIntegrazione(),idServizioApplicativo,
  1390.                         IntegrationFunctionError.IM_MESSAGE_NOT_FOUND, this.getErroriProperties(logCore));
  1391.             }

  1392.             // Check Autorizzazione all'utilizzo di IntegrationManager
  1393.             boolean authorized = false;
  1394.             if(useNewMethod) {
  1395.                 authorized = messaggioIM.isAuthorized();
  1396.             }
  1397.             else {
  1398.                 authorized = gestoreMessaggi.checkAutorizzazione(servizioApplicativo,isRiferimentoMessaggio);
  1399.             }
  1400.             if(!authorized){
  1401.                 msgDiag.logPersonalizzato("servizioApplicativo.nonAutorizzato");
  1402.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_404_AUTORIZZAZIONE_FALLITA_SA.
  1403.                         getErrore404_AutorizzazioneFallitaServizioApplicativo(servizioApplicativo),
  1404.                         idServizioApplicativo,
  1405.                         IntegrationFunctionError.AUTHORIZATION, this.getErroriProperties(logCore));
  1406.             }

  1407.             //  GetIDMessaggio Richiesto
  1408.             String idMessaggioRichiesto = idMessaggio;
  1409.             try{
  1410.                 if(isRiferimentoMessaggio) {
  1411.                     if(useNewMethod) {
  1412.                         idMessaggioRichiesto = messaggioIM.getIdentificativoRichiesta();
  1413.                     }
  1414.                     else {
  1415.                         idMessaggioRichiesto = gestoreMessaggi.mapRiferimentoIntoIDBusta();
  1416.                     }
  1417.                 }
  1418.             }catch(Exception e){
  1419.                 msgDiag.addKeywordErroreProcessamento(e);
  1420.                 msgDiag.logPersonalizzato("mappingRifMsgToId.nonRiuscito");
  1421.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1422.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1423.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1424.             }

  1425.             //  Gestore Messaggio da eliminare
  1426.             GestoreMessaggi gestoreEliminazione = null;
  1427.             try{
  1428.                 gestoreEliminazione = new GestoreMessaggi(stato, true, idMessaggioRichiesto,Costanti.INBOX,msgDiag,pddContext);
  1429.             }catch(Exception e){
  1430.                 msgDiag.logErroreGenerico(e,"gestoreMessaggi.eliminaDestinatarioMessaggio("+tipoOperazione+","+servizioApplicativo+","+idMessaggio+")");
  1431.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1432.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_522_DELETE_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1433.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1434.             }
  1435.            
  1436.             // Aggiorno la transazione prima di eliminare il messaggio
  1437.             try {
  1438.                 TransazioneApplicativoServer transazioneApplicativoServer = null;
  1439.                 String nomePorta = null;
  1440.                 if(useNewMethod) {
  1441.                     transazioneApplicativoServer = new TransazioneApplicativoServer();
  1442.                     transazioneApplicativoServer.setIdTransazione(messaggioIM.getIdTransazione());
  1443.                     transazioneApplicativoServer.setServizioApplicativoErogatore(messaggioIM.getServizioApplicativo());
  1444.                     transazioneApplicativoServer.setDataRegistrazione(messaggioIM.getOraRegistrazione());
  1445.                     transazioneApplicativoServer.setDataEliminazioneIm(DateManager.getDate());
  1446.                     transazioneApplicativoServer.setProtocollo(protocolFactory.getProtocol());
  1447.                     nomePorta = messaggioIM.getNomePorta();
  1448.                 }
  1449.                 else {
  1450.                     MessaggioServizioApplicativo info = gestoreEliminazione.readInfoDestinatario(idServizioApplicativo.getNome(), true, logCore);
  1451.                     if(info!=null) {
  1452.                         transazioneApplicativoServer = new TransazioneApplicativoServer();
  1453.                         transazioneApplicativoServer.setIdTransazione(info.getIdTransazione());
  1454.                         transazioneApplicativoServer.setServizioApplicativoErogatore(info.getServizioApplicativo());
  1455.                         transazioneApplicativoServer.setDataRegistrazione(info.getOraRegistrazione());
  1456.                         transazioneApplicativoServer.setDataEliminazioneIm(DateManager.getDate());
  1457.                         transazioneApplicativoServer.setProtocollo(protocolFactory.getProtocol());
  1458.                         nomePorta = info.getNomePorta();
  1459.                     }
  1460.                 }
  1461.                 if(transazioneApplicativoServer!=null) {
  1462.                     IDPortaApplicativa idPA = new IDPortaApplicativa();
  1463.                     idPA.setNome(nomePorta);
  1464.                     try {
  1465.                         GestoreConsegnaMultipla.getInstance().safeUpdateEliminazioneIM(transazioneApplicativoServer, idPA, stato, pddContext);
  1466.                     }catch(Throwable t) {
  1467.                         logError(logCore, "["+transazioneApplicativoServer.getIdTransazione()+"]["+transazioneApplicativoServer.getServizioApplicativoErogatore()+"] Errore durante il salvataggio delle informazioni relative al servizio applicativo: "+t.getMessage(),t);
  1468.                     }
  1469.                 }
  1470.             }catch(Exception e){
  1471.                 logError(logCore, "Salvataggio informazioni sulla transazione non riuscita: "+e.getMessage(),e);
  1472.             }
  1473.            
  1474.             // Elimino Messaggio
  1475.             try{
  1476.                 gestoreEliminazione.eliminaDestinatarioMessaggio(servizioApplicativo, gestoreEliminazione.getRiferimentoMessaggio(), dataMessaggio);
  1477.             }catch(Exception e){
  1478.                 msgDiag.logErroreGenerico(e,"gestoreMessaggi.eliminaDestinatarioMessaggio("+tipoOperazione+","+servizioApplicativo+","+idMessaggio+")");
  1479.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1480.                         get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_522_DELETE_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1481.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1482.             }

  1483.             imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.OK));
  1484.            
  1485.         }catch(Exception e){
  1486.            
  1487.             try{
  1488.                 imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX));
  1489.                
  1490.                 if(e instanceof IntegrationManagerException){
  1491.                     IntegrationManagerException exc = (IntegrationManagerException) e;
  1492.                     if(CodiceErroreIntegrazione.CODICE_402_AUTENTICAZIONE_FALLITA.equals(exc.getCodiceErroreIntegrazione()) ||
  1493.                             CodiceErroreIntegrazione.CODICE_431_GESTORE_CREDENZIALI_ERROR.equals(exc.getCodiceErroreIntegrazione())){
  1494.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.AUTENTICAZIONE_FALLITA));
  1495.                     }else if(CodiceErroreIntegrazione.CODICE_407_INTEGRATION_MANAGER_MSG_RICHIESTO_NON_TROVATO.equals(exc.getCodiceErroreIntegrazione())){
  1496.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.MESSAGGIO_NON_TROVATO));
  1497.                     }else if(CodiceErroreIntegrazione.CODICE_404_AUTORIZZAZIONE_FALLITA.equals(exc.getCodiceErroreIntegrazione())){
  1498.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.AUTORIZZAZIONE_FALLITA));
  1499.                     }
  1500.                 }
  1501.             }catch(Exception eInteral){
  1502.                 logError(logCore, "Errore durante la generazione dell'esito: "+eInteral.getMessage(),eInteral);
  1503.                 imResponseContext.setEsito(EsitoTransazione.ESITO_TRANSAZIONE_ERROR);
  1504.             }
  1505.            
  1506.             // Controllo Eccezioni
  1507.             if(e instanceof IntegrationManagerException){
  1508.                 // Lanciata all'interno del metodo
  1509.                 throw (IntegrationManagerException)e;
  1510.             }else{
  1511.                 msgDiag.logErroreGenerico(e,"deleteMessage("+tipoOperazione+")");
  1512.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),idServizioApplicativo,
  1513.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1514.             }
  1515.         }finally{
  1516.             try{
  1517.                 if(stato!=null)
  1518.                     stato.releaseResource();
  1519.             }catch(Exception eClose){}
  1520.            
  1521.            
  1522.             /* ------------  IntegrationManagerResponseHandler ------------- */
  1523.             imResponseContext.setDataCompletamentoOperazione(DateManager.getDate());
  1524.             try{
  1525.                 GestoreHandlers.integrationManagerResponse(imResponseContext, msgDiag, logCore);
  1526.             }catch(Exception e){
  1527.                 if(e instanceof HandlerException){
  1528.                     HandlerException he = (HandlerException) e;
  1529.                     if(he.isEmettiDiagnostico()){
  1530.                         msgDiag.logErroreGenerico(e, ((HandlerException)e).getIdentitaHandler());
  1531.                     }
  1532.                 }else{
  1533.                     msgDiag.logErroreGenerico(e, "IntegrationManagerResponseHandler");
  1534.                 }
  1535.             }
  1536.         }
  1537.     }

  1538.     /**
  1539.      * Cancella un messaggio
  1540.      *
  1541.      * @param idMessaggio ID del Messaggio da recuperare
  1542.      *
  1543.      */
  1544.     @Override
  1545.     public void deleteMessage(String idMessaggio) throws IntegrationManagerException {
  1546.         init();
  1547.         deleteMessage_engine(Operazione.deleteMessage,idMessaggio,false);
  1548.     }

  1549.     /**
  1550.      * Cancella un messaggio cercandolo per riferimentoMessaggio
  1551.      *
  1552.      * @param riferimentoMsg del Messaggio da recuperare
  1553.      *
  1554.      */
  1555.     @Override
  1556.     public void deleteMessageByReference(String riferimentoMsg) throws IntegrationManagerException {
  1557.         init();
  1558.         deleteMessage_engine(Operazione.deleteMessageByReference,riferimentoMsg,true);
  1559.     }






















  1560.     /* --------- delete All Messages ----------- */

  1561.     /**
  1562.      * Cancella tutti i messaggi di un servizio applicativo
  1563.      *
  1564.      *
  1565.      */
  1566.     @Override
  1567.     public void deleteAllMessages() throws IntegrationManagerException {

  1568.         init();
  1569.        
  1570.         Operazione tipoOperazione = Operazione.deleteAllMessages;

  1571.         // Timestamp
  1572.         Date dataRichiestaOperazione = DateManager.getTimestamp();
  1573.        
  1574.         // Logger
  1575.         Logger logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  1576.         if(logCore==null)
  1577.             logCore = LoggerWrapperFactory.getLogger(IntegrationManager.ID_MODULO);

  1578.         // check Autorizzazione
  1579.         checkIMAuthorization(logCore);
  1580.        
  1581.         // ProtocolFactoyr
  1582.         IProtocolFactory<?> protocolFactory = getProtocolFactory(logCore);
  1583.        
  1584.         // Verifica risorse sistema
  1585.         this.verificaRisorseSistema(protocolFactory,logCore, tipoOperazione.toString());

  1586.         MsgDiagnostico msgDiag = getMsgDiagnostico();
  1587.         msgDiag.addKeyword(CostantiPdD.KEY_TIPO_OPERAZIONE_IM, tipoOperazione.toString());
  1588.        
  1589.         IDServizioApplicativo idServizioApplicativo = null;
  1590.         OpenSPCoopStateful stato = null;
  1591.         // PddContext
  1592.         PdDContext pddContext = new PdDContext();
  1593.         String idTransazione = this.getUniqueIdentifier(logCore, protocolFactory,msgDiag,tipoOperazione.toString()).getAsString();
  1594.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, idTransazione);
  1595.         pddContext.addObject(org.openspcoop2.core.constants.Costanti.PROTOCOL_NAME, protocolFactory.getProtocol());
  1596.         msgDiag.setPddContext(pddContext, protocolFactory);
  1597.        
  1598.        
  1599.        
  1600.        
  1601.         /* ------------  IntegrationManagerRequesCHandler ------------- */
  1602.         IntegrationManagerRequestContext imRequestContext = null;
  1603.         try{
  1604.             imRequestContext = buildIMRequestContext(dataRichiestaOperazione, tipoOperazione, pddContext,logCore,protocolFactory);
  1605.             GestoreHandlers.integrationManagerRequest(imRequestContext, msgDiag, logCore);
  1606.         }catch(Exception e){
  1607.             ErroreIntegrazione erroreIntegrazione = null;
  1608.             IntegrationFunctionError integrationFunctionError = null;
  1609.             if(e instanceof HandlerException){
  1610.                 HandlerException he = (HandlerException) e;
  1611.                 integrationFunctionError = he.getIntegrationFunctionError();
  1612.                 if(he.isEmettiDiagnostico()){
  1613.                     msgDiag.logErroreGenerico(e, ((HandlerException)e).getIdentitaHandler());
  1614.                 }
  1615.                 erroreIntegrazione = he.convertToErroreIntegrazione();
  1616.             }else{
  1617.                 msgDiag.logErroreGenerico(e, "IntegrationManagerRequestHandler");
  1618.             }
  1619.             if(erroreIntegrazione==null){
  1620.                 erroreIntegrazione = ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione();
  1621.             }
  1622.             if(integrationFunctionError==null) {
  1623.                 integrationFunctionError = IntegrationFunctionError.INTERNAL_REQUEST_ERROR;
  1624.             }
  1625.             throw new IntegrationManagerException(protocolFactory,erroreIntegrazione,
  1626.                     integrationFunctionError, getErroriProperties(logCore));
  1627.         }
  1628.        
  1629.        
  1630.         /* ------------  Gestione Operazione ------------- */
  1631.         IntegrationManagerResponseContext imResponseContext =
  1632.             new IntegrationManagerResponseContext(dataRichiestaOperazione,tipoOperazione,pddContext,logCore,protocolFactory);
  1633.         if(imRequestContext!=null){
  1634.             imResponseContext.setConnettore(imRequestContext.getConnettore());
  1635.         }
  1636.         try{

  1637.             // init stato
  1638.             stato = new OpenSPCoopStateful();
  1639.             stato.initResource(this.propertiesReader.getIdentitaPortaDefault(protocolFactory.getProtocol(), null),IntegrationManager.ID_MODULO, idTransazione,
  1640.                     OpenSPCoopStateDBManager.messageBox);
  1641.             ConfigurazionePdDManager configPdDManager = ConfigurazionePdDManager.getInstance(stato.getStatoRichiesta(),stato.getStatoRisposta());
  1642.             msgDiag.updateState(configPdDManager);  
  1643.            
  1644.             // gestione credenziali
  1645.             this.gestioneCredenziali(logCore, protocolFactory,msgDiag, imRequestContext.getConnettore(),pddContext);
  1646.            
  1647.             // Autenticazione Servizio Applicativo
  1648.             idServizioApplicativo = autenticazione(logCore, protocolFactory,msgDiag,imRequestContext.getConnettore(),configPdDManager,pddContext);
  1649.             imResponseContext.setServizioApplicativo(idServizioApplicativo);
  1650.             String param = "ServizioApplicativo["+idServizioApplicativo.getNome()+"]";
  1651.             msgDiag.addKeyword(CostantiPdD.KEY_PARAMETRI_OPERAZIONE_IM, param);
  1652.             msgDiag.logPersonalizzato("logInvocazioneOperazione");

  1653.             // Effettuo ricerca ID DEL SERVIZIO APPLICATIVO
  1654.             GestoreMessaggi gestoreSearchID = new GestoreMessaggi(stato, true,msgDiag,pddContext);

  1655.             List<IdentificativoIM> ids =  gestoreSearchID.getIDMessaggi_ServizioApplicativo(idServizioApplicativo.getNome());      
  1656.             if(ids.isEmpty()){
  1657.                 msgDiag.logPersonalizzato("messaggiNonPresenti");
  1658.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_406_INTEGRATION_MANAGER_MESSAGGI_FOR_SIL_NON_TROVATI.
  1659.                         getErroreIntegrazione(),idServizioApplicativo,
  1660.                         IntegrationFunctionError.IM_MESSAGES_NOT_FOUND, this.getErroriProperties(logCore));
  1661.             }

  1662.             // Creo i vari gestori di messaggi
  1663.             List<MessaggioIM> messaggiIM = new ArrayList<MessaggioIM>();
  1664.             for(int i=0; i<ids.size(); i++){
  1665.                 IdentificativoIM idIM = ids.get(i);
  1666.                 String idMessaggio = idIM.getId();
  1667.                 Date dataMessaggio = idIM.getData();
  1668.                
  1669.                 GestoreMessaggi gestoreMessaggi = new GestoreMessaggi(stato, true,idMessaggio,Costanti.INBOX,msgDiag,pddContext);
  1670.                 MessaggioIM messaggioIM = null;
  1671.                 if(useNewMethod) {
  1672.                     messaggioIM = gestoreMessaggi.readMessageForSIL(idServizioApplicativo.getNome(), dataMessaggio);
  1673.                     if(messaggioIM!=null) {
  1674.                         messaggiIM.add(messaggioIM);
  1675.                     }
  1676.                 }
  1677.                
  1678.                 // Check Esistenza Messaggio
  1679.                 boolean exists = false;
  1680.                 if(useNewMethod) {
  1681.                     exists = messaggioIM!=null;
  1682.                 }
  1683.                 else {
  1684.                     exists = gestoreMessaggi.existsMessageForSIL(idServizioApplicativo.getNome());
  1685.                 }
  1686.                 if(!exists){
  1687.                     msgDiag.addKeyword(CostantiPdD.KEY_ID_MESSAGGIO_TRANSACTION_MANAGER, idMessaggio);
  1688.                     msgDiag.logPersonalizzato("messaggioNonTrovato");
  1689.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1690.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_520_READ_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1691.                             IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1692.                 }

  1693.                 // Check Autorizzazione all'utilizzo di IntegrationManager
  1694.                 boolean authorized = false;
  1695.                 if(useNewMethod) {
  1696.                     authorized = messaggioIM.isAuthorized();
  1697.                 }
  1698.                 else {
  1699.                     authorized = gestoreMessaggi.checkAutorizzazione(idServizioApplicativo.getNome());
  1700.                 }
  1701.                 if(!authorized){
  1702.                     msgDiag.logPersonalizzato("servizioApplicativo.nonAutorizzato");
  1703.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_404_AUTORIZZAZIONE_FALLITA_SA
  1704.                             .getErrore404_AutorizzazioneFallitaServizioApplicativo(idServizioApplicativo.getNome()),
  1705.                             idServizioApplicativo,
  1706.                             IntegrationFunctionError.AUTHORIZATION, this.getErroriProperties(logCore));
  1707.                 }
  1708.             }

  1709.             // Elimino i messaggi
  1710.             while(!ids.isEmpty()){
  1711.                 // Elimino Messaggio
  1712.                 IdentificativoIM idIM = ids.remove(0);
  1713.                 String idMessaggio = idIM.getId();
  1714.                 Date dataMessaggio = idIM.getData();
  1715.                 MessaggioIM messaggioIM = null;
  1716.                 if(useNewMethod) {
  1717.                     messaggioIM = messaggiIM.remove(0);
  1718.                 }
  1719.                
  1720.                 // Gestore Messaggio da eliminare
  1721.                 GestoreMessaggi gestoreEliminazione = null;
  1722.                 try{
  1723.                     //  Elimino accesso daPdD
  1724.                     gestoreEliminazione = new GestoreMessaggi(stato, true,idMessaggio,Costanti.INBOX,msgDiag,pddContext);
  1725.                 }catch(Exception e){
  1726.                     msgDiag.logErroreGenerico(e,"gestoreMessaggi.eliminaDestinatarioMessaggio("+tipoOperazione+","+idServizioApplicativo.getNome()+","+idMessaggio+")");
  1727.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1728.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_522_DELETE_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1729.                             IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1730.                 }
  1731.                
  1732.                 // Aggiorno la transazione prima di eliminare il messaggio
  1733.                 try {
  1734.                     TransazioneApplicativoServer transazioneApplicativoServer = null;
  1735.                     String nomePorta = null;
  1736.                     if(useNewMethod) {
  1737.                         transazioneApplicativoServer = new TransazioneApplicativoServer();
  1738.                         transazioneApplicativoServer.setIdTransazione(messaggioIM.getIdTransazione());
  1739.                         transazioneApplicativoServer.setServizioApplicativoErogatore(messaggioIM.getServizioApplicativo());
  1740.                         transazioneApplicativoServer.setDataRegistrazione(messaggioIM.getOraRegistrazione());
  1741.                         transazioneApplicativoServer.setDataEliminazioneIm(DateManager.getDate());
  1742.                         transazioneApplicativoServer.setProtocollo(protocolFactory.getProtocol());
  1743.                         nomePorta = messaggioIM.getNomePorta();
  1744.                     }
  1745.                     else {              
  1746.                         MessaggioServizioApplicativo info = gestoreEliminazione.readInfoDestinatario(idServizioApplicativo.getNome(), true, logCore);
  1747.                         if(info!=null) {
  1748.                             transazioneApplicativoServer = new TransazioneApplicativoServer();
  1749.                             transazioneApplicativoServer.setIdTransazione(info.getIdTransazione());
  1750.                             transazioneApplicativoServer.setServizioApplicativoErogatore(info.getServizioApplicativo());
  1751.                             transazioneApplicativoServer.setDataRegistrazione(info.getOraRegistrazione());
  1752.                             transazioneApplicativoServer.setDataEliminazioneIm(DateManager.getDate());
  1753.                             transazioneApplicativoServer.setProtocollo(protocolFactory.getProtocol());
  1754.                             nomePorta = info.getNomePorta();
  1755.                         }
  1756.                     }
  1757.                     if(transazioneApplicativoServer!=null) {
  1758.                         IDPortaApplicativa idPA = new IDPortaApplicativa();
  1759.                         idPA.setNome(nomePorta);
  1760.                         try {
  1761.                             GestoreConsegnaMultipla.getInstance().safeUpdateEliminazioneIM(transazioneApplicativoServer, idPA, stato, pddContext);
  1762.                         }catch(Throwable t) {
  1763.                             logError(logCore, "["+transazioneApplicativoServer.getIdTransazione()+"]["+transazioneApplicativoServer.getServizioApplicativoErogatore()+"] Errore durante il salvataggio delle informazioni relative al servizio applicativo: "+t.getMessage(),t);
  1764.                         }
  1765.                     }
  1766.                 }catch(Exception e){
  1767.                     logError(logCore, "Salvataggio informazioni sulla transazione non riuscita: "+e.getMessage(),e);
  1768.                 }
  1769.                
  1770.                 // Elimino Messaggio
  1771.                 try{
  1772.                     gestoreEliminazione.eliminaDestinatarioMessaggio(idServizioApplicativo.getNome(), gestoreEliminazione.getRiferimentoMessaggio(), dataMessaggio);
  1773.                 }catch(Exception e){
  1774.                     msgDiag.logErroreGenerico(e,"gestoreMessaggi.eliminaDestinatarioMessaggio("+tipoOperazione+","+idServizioApplicativo.getNome()+","+idMessaggio+")");
  1775.                     throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  1776.                             get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_522_DELETE_MSG_FROM_INTEGRATION_MANAGER),idServizioApplicativo,
  1777.                             IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1778.                 }
  1779.             }
  1780.            
  1781.             imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.OK));


  1782.         }catch(Exception e){
  1783.            
  1784.             try{
  1785.                 imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.ERRORE_PROCESSAMENTO_PDD_5XX));
  1786.                
  1787.                 if(e instanceof IntegrationManagerException){
  1788.                     IntegrationManagerException exc = (IntegrationManagerException) e;
  1789.                     if(CodiceErroreIntegrazione.CODICE_402_AUTENTICAZIONE_FALLITA.equals(exc.getCodiceErroreIntegrazione()) ||
  1790.                             CodiceErroreIntegrazione.CODICE_431_GESTORE_CREDENZIALI_ERROR.equals(exc.getCodiceErroreIntegrazione())){
  1791.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.AUTENTICAZIONE_FALLITA));
  1792.                     }else if(CodiceErroreIntegrazione.CODICE_406_INTEGRATION_MANAGER_MESSAGGI_FOR_SIL_NON_TROVATI.equals(exc.getCodiceErroreIntegrazione())){
  1793.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.MESSAGGI_NON_PRESENTI));
  1794.                     }else if(CodiceErroreIntegrazione.CODICE_404_AUTORIZZAZIONE_FALLITA.equals(exc.getCodiceErroreIntegrazione())){
  1795.                         imResponseContext.setEsito(this.getEsitoTransazione(protocolFactory, imRequestContext, EsitoTransazioneName.AUTORIZZAZIONE_FALLITA));
  1796.                     }
  1797.                 }
  1798.             }catch(Exception eInteral){
  1799.                 logError(logCore, "Errore durante la generazione dell'esito: "+eInteral.getMessage(),eInteral);
  1800.                 imResponseContext.setEsito(EsitoTransazione.ESITO_TRANSAZIONE_ERROR);
  1801.             }
  1802.            
  1803.             // Controllo Eccezioni
  1804.             if(e instanceof IntegrationManagerException){
  1805.                 // Lanciata all'interno del metodo
  1806.                 throw (IntegrationManagerException)e;
  1807.             }else{
  1808.                 msgDiag.logErroreGenerico(e,"deleteAllMessages("+tipoOperazione+")");
  1809.                 throw new IntegrationManagerException(protocolFactory,ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreIntegrazione(),idServizioApplicativo,
  1810.                         IntegrationFunctionError.INTERNAL_REQUEST_ERROR, this.getErroriProperties(logCore));
  1811.             }
  1812.         }finally{
  1813.             try{
  1814.                 if(stato!=null)
  1815.                     stato.releaseResource();
  1816.             }catch(Exception eClose){}
  1817.            
  1818.            
  1819.            
  1820.             /* ------------  IntegrationManagerResponseHandler ------------- */
  1821.             imResponseContext.setDataCompletamentoOperazione(DateManager.getDate());
  1822.             try{
  1823.                 GestoreHandlers.integrationManagerResponse(imResponseContext, msgDiag, logCore);
  1824.             }catch(Exception e){
  1825.                 if(e instanceof HandlerException){
  1826.                     HandlerException he = (HandlerException) e;
  1827.                     if(he.isEmettiDiagnostico()){
  1828.                         msgDiag.logErroreGenerico(e, ((HandlerException)e).getIdentitaHandler());
  1829.                     }
  1830.                 }else{
  1831.                     msgDiag.logErroreGenerico(e, "IntegrationManagerResponseHandler");
  1832.                 }
  1833.             }
  1834.         }

  1835.     }























  1836.     /* ------- Invocazione Porta Delegata ---------------*/

  1837.     /**
  1838.      * Invoca una porta delegata
  1839.      *
  1840.      * @param portaDelegata Porta Delegata da invocare
  1841.      * @param msg Message da utilizza come messaggio da invocare (contiene anche il servizio che si desidera invocare)
  1842.      * @return un Message contenente il messaggio di risposta
  1843.      *
  1844.      */
  1845.     @Override
  1846.     public IntegrationManagerMessage invocaPortaDelegata(String portaDelegata,IntegrationManagerMessage msg) throws IntegrationManagerException {
  1847.         init();
  1848.         String tipoOperazione = "invocaPortaDelegata";
  1849.         return invocaPortaDelegata_engine(tipoOperazione,portaDelegata,msg,null);

  1850.     }


  1851.     /**
  1852.      * Invoca una porta delegata per riferimento
  1853.      *
  1854.      * @param portaDelegata Porta Delegata da invocare
  1855.      * @param msg Message da utilizza come messaggio da invocare (contiene anche il servizio che si desidera invocare)
  1856.      * @param riferimentoMessaggio ID che identifica un Messaggio da utilizzare
  1857.      *
  1858.      * @return un Message contenente il messaggio di risposta
  1859.      *
  1860.      */
  1861.     @Override
  1862.     public IntegrationManagerMessage invocaPortaDelegataPerRiferimento(String portaDelegata,
  1863.             IntegrationManagerMessage msg,String riferimentoMessaggio) throws IntegrationManagerException {
  1864.         init();
  1865.         String tipoOperazione = "invocaPortaDelegataPerRiferimento";
  1866.         return invocaPortaDelegata_engine(tipoOperazione,portaDelegata,msg,riferimentoMessaggio);

  1867.     }


  1868.     /**
  1869.      * Invia una risposta asicrona a OpenSPCoop
  1870.      * @param portaDelegata Porta Delegata da invocare
  1871.      * @param msg Message da utilizza come messaggio da invocare (contiene anche il servizio che si desidera invocare)
  1872.      * @return un Message contenente il messaggio di risposta
  1873.      *
  1874.      */
  1875.     @Override
  1876.     public IntegrationManagerMessage sendRispostaAsincronaSimmetrica(String portaDelegata,IntegrationManagerMessage msg) throws IntegrationManagerException {
  1877.         init();
  1878.         String tipoOperazione = "sendRispostaAsincronaSimmetrica";      
  1879.         return invocaPortaDelegata_engine(tipoOperazione,portaDelegata,msg,null);

  1880.     }

  1881.     /**
  1882.      * Invia una risposta asicrona a OpenSPCoop
  1883.      * @param portaDelegata Porta Delegata da invocare
  1884.      * @param msg Message da utilizza come messaggio da invocare (contiene anche il servizio che si desidera invocare)
  1885.      * @return un Message contenente il messaggio di risposta
  1886.      *
  1887.      */
  1888.     @Override
  1889.     public IntegrationManagerMessage sendRichiestaStatoAsincronaAsimmetrica(String portaDelegata,IntegrationManagerMessage msg) throws IntegrationManagerException {
  1890.         init();
  1891.         String tipoOperazione = "sendRichiestaStatoAsincronaAsimmetrica";
  1892.         return invocaPortaDelegata_engine(tipoOperazione,portaDelegata,msg,null);

  1893.     }


  1894.     private IntegrationManagerMessage invocaPortaDelegata_engine(String tipoOperazione, String portaDelegata, IntegrationManagerMessage msg,
  1895.             String idInvocazionePerRiferimento) throws IntegrationManagerException {

  1896.         // Timestamp
  1897.         Date dataAccettazioneRichiesta = DateManager.getDate();
  1898.         Date dataIngressoRichiesta = dataAccettazioneRichiesta;
  1899.        
  1900.         // Logger
  1901.         Logger logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  1902.         if(logCore==null)
  1903.             logCore = LoggerWrapperFactory.getLogger(IntegrationManager.ID_MODULO);
  1904.        
  1905.         // check Autorizzazione
  1906.         checkIMAuthorization(logCore);
  1907.        
  1908.         // ProtocolFactory
  1909.         IProtocolFactory<?> protocolFactory = getProtocolFactory(logCore);
  1910.        
  1911.         // Verifica risorse sistema
  1912.         this.verificaRisorseSistema(protocolFactory,logCore, tipoOperazione);
  1913.        
  1914.         // SetNomePD
  1915.         this.setNomePortaDelegata(logCore, portaDelegata);
  1916.        
  1917.         RicezioneContenutiApplicativiIntegrationManagerService service = new RicezioneContenutiApplicativiIntegrationManagerService();
  1918.         return service.process(tipoOperazione, portaDelegata, msg, idInvocazionePerRiferimento,
  1919.                 logCore, getHttpServletRequest(), getHttpServletResponse(),
  1920.                 protocolFactory, dataAccettazioneRichiesta, dataIngressoRichiesta);

  1921.     }

  1922. }