TransactionDriverTracciamento.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.logger;


  21. import java.sql.Connection;
  22. import java.sql.DriverManager;
  23. import java.sql.SQLException;
  24. import java.sql.Timestamp;
  25. import java.util.ArrayList;
  26. import java.util.Date;
  27. import java.util.HashMap;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Properties;

  31. import javax.naming.InitialContext;
  32. import javax.sql.DataSource;

  33. import org.apache.commons.lang.StringUtils;
  34. import org.openspcoop2.core.commons.CoreException;
  35. import org.openspcoop2.core.commons.dao.DAOFactory;
  36. import org.openspcoop2.core.constants.CostantiDB;
  37. import org.openspcoop2.core.constants.TipoPdD;
  38. import org.openspcoop2.core.id.IDServizioApplicativo;
  39. import org.openspcoop2.core.id.IDSoggetto;
  40. import org.openspcoop2.core.transazioni.CredenzialeMittente;
  41. import org.openspcoop2.core.transazioni.Transazione;
  42. import org.openspcoop2.core.transazioni.dao.IDBCredenzialeMittenteServiceSearch;
  43. import org.openspcoop2.core.transazioni.dao.ITransazioneServiceSearch;
  44. import org.openspcoop2.core.transazioni.dao.jdbc.JDBCServiceManager;
  45. import org.openspcoop2.core.transazioni.utils.CredenzialiMittente;
  46. import org.openspcoop2.core.transazioni.utils.ProjectInfo;
  47. import org.openspcoop2.core.transazioni.utils.PropertiesSerializator;
  48. import org.openspcoop2.core.transazioni.utils.credenziali.CredenzialeTokenClient;
  49. import org.openspcoop2.generic_project.beans.IField;
  50. import org.openspcoop2.generic_project.beans.NonNegativeNumber;
  51. import org.openspcoop2.generic_project.exception.ExpressionException;
  52. import org.openspcoop2.generic_project.exception.ExpressionNotImplementedException;
  53. import org.openspcoop2.generic_project.exception.MultipleResultException;
  54. import org.openspcoop2.generic_project.exception.NotFoundException;
  55. import org.openspcoop2.generic_project.exception.NotImplementedException;
  56. import org.openspcoop2.generic_project.exception.ServiceException;
  57. import org.openspcoop2.generic_project.expression.IExpression;
  58. import org.openspcoop2.generic_project.expression.IPaginatedExpression;
  59. import org.openspcoop2.generic_project.expression.SortOrder;
  60. import org.openspcoop2.pdd.core.transazioni.DateUtility;
  61. import org.openspcoop2.pdd.logger.record.AbstractDatoRicostruzione;
  62. import org.openspcoop2.pdd.logger.traccia.CostantiMappingTracciamento;
  63. import org.openspcoop2.pdd.logger.traccia.InformazioniRecordTraccia;
  64. import org.openspcoop2.pdd.logger.traccia.MappingRicostruzioneTraccia;
  65. import org.openspcoop2.pdd.logger.traccia.PopolamentoTracciaUtils;
  66. import org.openspcoop2.protocol.basic.BasicComponentFactory;
  67. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  68. import org.openspcoop2.protocol.sdk.Busta;
  69. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  70. import org.openspcoop2.protocol.sdk.ProtocolException;
  71. import org.openspcoop2.protocol.sdk.Riscontro;
  72. import org.openspcoop2.protocol.sdk.Trasmissione;
  73. import org.openspcoop2.protocol.sdk.builder.IBustaBuilder;
  74. import org.openspcoop2.protocol.sdk.constants.EsitoElaborazioneMessaggioTracciatura;
  75. import org.openspcoop2.protocol.sdk.constants.Inoltro;
  76. import org.openspcoop2.protocol.sdk.constants.ProfiloDiCollaborazione;
  77. import org.openspcoop2.protocol.sdk.constants.RuoloMessaggio;
  78. import org.openspcoop2.protocol.sdk.constants.TipoOraRegistrazione;
  79. import org.openspcoop2.protocol.sdk.tracciamento.DriverTracciamentoException;
  80. import org.openspcoop2.protocol.sdk.tracciamento.DriverTracciamentoNotFoundException;
  81. import org.openspcoop2.protocol.sdk.tracciamento.EsitoElaborazioneMessaggioTracciato;
  82. import org.openspcoop2.protocol.sdk.tracciamento.FiltroRicercaTracce;
  83. import org.openspcoop2.protocol.sdk.tracciamento.FiltroRicercaTracceConPaginazione;
  84. import org.openspcoop2.protocol.sdk.tracciamento.ITracciaDriver;
  85. import org.openspcoop2.protocol.sdk.tracciamento.InformazioniProtocollo;
  86. import org.openspcoop2.protocol.sdk.tracciamento.Traccia;
  87. import org.openspcoop2.utils.LoggerWrapperFactory;
  88. import org.openspcoop2.utils.TipiDatabase;
  89. import org.openspcoop2.utils.jdbc.JDBCUtilities;
  90. import org.slf4j.Logger;

  91. /**    
  92.  * TransactionDriverTracciamento
  93.  *
  94.  * @author Poli Andrea (poli@link.it)
  95.  * @author $Author$
  96.  * @version $Rev$, $Date$
  97.  */
  98. public class TransactionDriverTracciamento implements ITracciaDriver {

  99.     private static final String TIPO_DB_NON_GESTITO = "Tipo database non gestito";
  100.     private static final String NON_IMPLEMENTATO = "Metodo non implementato";


  101.     /**
  102.      * DataSource
  103.      */
  104.     DataSource datasource = null;
  105.    
  106.     /**
  107.      * Connessione
  108.      */
  109.     Connection connection = null;
  110.     boolean connectionOpenViaJDBCInCostructor = false;

  111.     /**
  112.      * SQLQueryObject
  113.      */
  114.     String tipoDatabase = null;

  115.     /** Driver Tracciamento originale */
  116.     DriverTracciamento driverTracciamento = null;

  117.     /** DAO Factory */
  118.     DAOFactory daoFactory = null;
  119.    
  120.     /** Logger utilizzato per info. */
  121.     private Logger log = null;
  122.     private void logDebug(String msg) {
  123.         if(this.log!=null) {
  124.             this.log.debug(msg);
  125.         }
  126.     }

  127.     public TransactionDriverTracciamento(String nomeDataSource, String tipoDatabase, Properties prop) throws DriverTracciamentoException {
  128.         this(nomeDataSource,tipoDatabase,prop,null);
  129.     }

  130.     public TransactionDriverTracciamento(String nomeDataSource, String tipoDatabase, Properties prop, Logger log) throws DriverTracciamentoException {
  131.         // Logger
  132.         try {
  133.             if(log==null)
  134.                 this.log = LoggerWrapperFactory.getLogger(org.openspcoop2.protocol.basic.Costanti.LOGANALIZER_DRIVER_DB_LOGGER);
  135.             else
  136.                 this.log = log;
  137.         } catch (Exception e) {
  138.             throw new DriverTracciamentoException("(ds jndiName) Errore durante l'inizializzazione del logger: "+e.getMessage(),e);
  139.         }

  140.         // Datasource
  141.         try {
  142.             InitialContext initCtx = new InitialContext(prop);
  143.             this.datasource = (DataSource) initCtx.lookup(nomeDataSource);
  144.             if (this.datasource == null)
  145.                 throw new DriverTracciamentoException ("datasource is null");

  146.             initCtx.close();
  147.         } catch (Exception e) {
  148.             throw new DriverTracciamentoException("(ds jndiName) Errore durante la ricerca del datasource: "+e.getMessage(),e);
  149.         }

  150.         // ISQLQueryObject
  151.         try {
  152.             if (TipiDatabase.isAMember(tipoDatabase)) {
  153.                 this.tipoDatabase = tipoDatabase;              
  154.             } else {
  155.                 throw new DriverTracciamentoException(TIPO_DB_NON_GESTITO);
  156.             }
  157.         } catch (Exception e) {
  158.             throw new DriverTracciamentoException("(ds jndiName) Errore durante la ricerca del SQLQueryObject: "+e.getMessage(),e);
  159.         }

  160.         // Driver tracciamento
  161.         try{
  162.             this.driverTracciamento = new DriverTracciamento(nomeDataSource, tipoDatabase, prop, log);
  163.         } catch (Exception e) {
  164.             throw new DriverTracciamentoException("(ds jndiName) Errore durante l'inizializzazione del driver delle tracce: "+e.getMessage(),e);
  165.         }
  166.        
  167.         // DAO Factory
  168.         try{
  169.             this.daoFactory = DAOFactory.getInstance(log);
  170.         }catch (Exception e) {
  171.             throw new DriverTracciamentoException("(ds jndiName) Errore durante l'inizializzazione del dao factory: "+e.getMessage(),e);
  172.         }
  173.     }
  174.    
  175.     public TransactionDriverTracciamento(DataSource dataSourceObject, String tipoDatabase) throws DriverTracciamentoException {
  176.         this(dataSourceObject,tipoDatabase,null);
  177.     }

  178.     public TransactionDriverTracciamento(DataSource dataSourceObject, String tipoDatabase, Logger log) throws DriverTracciamentoException {
  179.         // Logger
  180.         try {
  181.             if(log==null)
  182.                 this.log = LoggerWrapperFactory.getLogger(org.openspcoop2.protocol.basic.Costanti.LOGANALIZER_DRIVER_DB_LOGGER);
  183.             else
  184.                 this.log = log;
  185.         } catch (Exception e) {
  186.             throw new DriverTracciamentoException("(ds) Errore durante l'inizializzazione del logger: "+e.getMessage(),e);
  187.         }

  188.         // Datasource
  189.         try {
  190.             this.datasource = dataSourceObject;
  191.             if (this.datasource == null)
  192.                 throw new DriverTracciamentoException ("datasource is null");
  193.         } catch (Exception e) {
  194.             throw new DriverTracciamentoException("(ds) Errore durante la ricerca del datasource: "+e.getMessage(),e);
  195.         }

  196.         // ISQLQueryObject
  197.         try {
  198.             if (TipiDatabase.isAMember(tipoDatabase)) {
  199.                 this.tipoDatabase = tipoDatabase;              
  200.             } else {
  201.                 throw new DriverTracciamentoException(TIPO_DB_NON_GESTITO);
  202.             }
  203.         } catch (Exception e) {
  204.             throw new DriverTracciamentoException("(ds) Errore durante la ricerca del SQLQueryObject: "+e.getMessage(),e);
  205.         }

  206.         // Driver tracciamento
  207.         try{
  208.             this.driverTracciamento = new DriverTracciamento(this.datasource, tipoDatabase, log);
  209.         } catch (Exception e) {
  210.             throw new DriverTracciamentoException("(ds) Errore durante l'inizializzazione del driver delle tracce: "+e.getMessage(),e);
  211.         }  
  212.        
  213.         // DAO Factory
  214.         try{
  215.             this.daoFactory = DAOFactory.getInstance(log);
  216.         }catch (Exception e) {
  217.             throw new DriverTracciamentoException("(ds) Errore durante l'inizializzazione del dao factory: "+e.getMessage(),e);
  218.         }
  219.     }
  220.    
  221.    
  222.     public TransactionDriverTracciamento(Connection connection, String tipoDatabase) throws DriverTracciamentoException {
  223.         this(connection,tipoDatabase,null);
  224.     }

  225.     public TransactionDriverTracciamento(Connection connection, String tipoDatabase, Logger log) throws DriverTracciamentoException {
  226.         // Logger
  227.         try {
  228.             if(log==null)
  229.                 this.log = LoggerWrapperFactory.getLogger(org.openspcoop2.protocol.basic.Costanti.LOGANALIZER_DRIVER_DB_LOGGER);
  230.             else
  231.                 this.log = log;
  232.         } catch (Exception e) {
  233.             throw new DriverTracciamentoException("(connection) Errore durante l'inizializzazione del logger: "+e.getMessage(),e);
  234.         }

  235.         // connection
  236.         this.connection = connection;

  237.         // ISQLQueryObject
  238.         try {
  239.             if (TipiDatabase.isAMember(tipoDatabase)) {
  240.                 this.tipoDatabase = tipoDatabase;              
  241.             } else {
  242.                 throw new DriverTracciamentoException(TIPO_DB_NON_GESTITO);
  243.             }
  244.         } catch (Exception e) {
  245.             throw new DriverTracciamentoException("(connection) Errore durante la ricerca del SQLQueryObject: "+e.getMessage(),e);
  246.         }

  247.         // Driver tracciamento
  248.         try{
  249.             this.driverTracciamento = new DriverTracciamento(this.connection, tipoDatabase, log);
  250.         } catch (Exception e) {
  251.             throw new DriverTracciamentoException("(connection) Errore durante l'inizializzazione del driver delle tracce: "+e.getMessage(),e);
  252.         }  
  253.        
  254.         // DAO Factory
  255.         try{
  256.             this.daoFactory = DAOFactory.getInstance(log);
  257.         }catch (Exception e) {
  258.             throw new DriverTracciamentoException("(connection) Errore durante l'inizializzazione del dao factory: "+e.getMessage(),e);
  259.         }
  260.     }
  261.    
  262.    
  263.     public TransactionDriverTracciamento(String urlJDBC,String driverJDBC,
  264.             String username,String password, String tipoDatabase) throws DriverTracciamentoException {
  265.         this(urlJDBC,driverJDBC,username,password,tipoDatabase,null);
  266.     }

  267.     public TransactionDriverTracciamento(String urlJDBC,String driverJDBC,
  268.             String username,String password, String tipoDatabase, Logger log) throws DriverTracciamentoException {
  269.         // Logger
  270.         try {
  271.             if(log==null)
  272.                 this.log = LoggerWrapperFactory.getLogger(org.openspcoop2.protocol.basic.Costanti.LOGANALIZER_DRIVER_DB_LOGGER);
  273.             else
  274.                 this.log = log;
  275.         } catch (Exception e) {
  276.             throw new DriverTracciamentoException("(connection url) Errore durante l'inizializzazione del logger: "+e.getMessage(),e);
  277.         }

  278.         // connection
  279.         try {
  280.             Class.forName(driverJDBC);
  281.            
  282.             if(username!=null){
  283.                 this.connection = DriverManager.getConnection(urlJDBC,username,password);
  284.             }else{
  285.                 this.connection = DriverManager.getConnection(urlJDBC);
  286.             }
  287.             this.connectionOpenViaJDBCInCostructor = true;
  288.            
  289.         } catch (Exception e) {
  290.             throw new DriverTracciamentoException("(connection url) Errore durante l'inizializzazione della connessione: "+e.getMessage(),e);
  291.         }

  292.         // ISQLQueryObject
  293.         try {
  294.             if (TipiDatabase.isAMember(tipoDatabase)) {
  295.                 this.tipoDatabase = tipoDatabase;              
  296.             } else {
  297.                 throw new DriverTracciamentoException(TIPO_DB_NON_GESTITO);
  298.             }
  299.         } catch (Exception e) {
  300.             throw new DriverTracciamentoException("(connection url) Errore durante la ricerca del SQLQueryObject: "+e.getMessage(),e);
  301.         }

  302.         // Driver tracciamento
  303.         try{
  304.             this.driverTracciamento = new DriverTracciamento(this.connection, tipoDatabase, log);
  305.         } catch (Exception e) {
  306.             throw new DriverTracciamentoException("(connection url) Errore durante l'inizializzazione del driver delle tracce: "+e.getMessage(),e);
  307.         }  
  308.        
  309.         // DAO Factory
  310.         try{
  311.             this.daoFactory = DAOFactory.getInstance(log);
  312.         }catch (Exception e) {
  313.             throw new DriverTracciamentoException("(connection url) Errore durante l'inizializzazione del dao factory: "+e.getMessage(),e);
  314.         }
  315.     }
  316.    
  317.    
  318.    
  319.     @Override
  320.     public IProtocolFactory<?> getProtocolFactory() {
  321.         return null;
  322.     }

  323.     private Connection getConnection() throws SQLException {
  324.         Connection con = null;
  325.         if(this.connection!=null){
  326.             con = this.connection;
  327.         }else{
  328.             con = this.datasource.getConnection();
  329.         }
  330.         return  con;
  331.     }
  332.     private void checkConnection(Connection con) throws DriverTracciamentoException {
  333.         if(con==null)
  334.             throw new DriverTracciamentoException("Connection non ottenuta");
  335.     }
  336.     private void closeConnection(Connection con) {
  337.         if(this.connection==null){
  338.             try{
  339.                 JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), con, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  340.             }catch(Exception e){
  341.                 // close
  342.             }
  343.         }
  344.     }
  345.    
  346.     @Override
  347.     public int countTracce(FiltroRicercaTracce filtro)
  348.             throws DriverTracciamentoException {

  349.         Connection con = null;
  350.         JDBCServiceManager transazioniServiceManager = null;
  351.         long transazioniTrovate = 0;
  352.         try{
  353.             con = getConnection();
  354.             checkConnection(con);
  355.                        
  356.             transazioniServiceManager =
  357.                     (JDBCServiceManager) this.daoFactory.getServiceManager(new ProjectInfo(), con, true);
  358.            
  359.             ITransazioneServiceSearch transazioneServiceSearch = transazioniServiceManager.getTransazioneServiceSearch();
  360.                        
  361.             IExpression expression = this.newExpressionEngine(transazioneServiceSearch, filtro);
  362.             NonNegativeNumber nn = transazioneServiceSearch.count(expression);
  363.             if(nn!=null){
  364.                 transazioniTrovate = nn.longValue();
  365.             }          
  366.         }catch(Exception e){
  367.             throw new DriverTracciamentoException("Riscontrato errore durante la lettura (count) dei dati (Filtro:"+filtro.toString()+"): "+e.getMessage(),e);
  368.         }finally{
  369.             try{
  370.                 if(transazioniServiceManager!=null) {
  371.                     transazioniServiceManager.close();
  372.                 }
  373.             }catch(Exception e){
  374.                 // close
  375.             }
  376.             closeConnection(con);
  377.         }
  378.            
  379.         int offset = 0;
  380.         int limit = 25;
  381.         int count = 0;
  382.         FiltroRicercaTracceConPaginazione filtroPaginato = new FiltroRicercaTracceConPaginazione(filtro);
  383.         filtroPaginato.setOffset(offset);
  384.         filtroPaginato.setLimit(limit);
  385.         List<Traccia> list = null;
  386.         try{
  387.             list = this.getTracceEngine(filtroPaginato);
  388.             while(offset<transazioniTrovate){
  389.                 count = count + list.size();
  390.                 offset = offset + limit; // analizzo 25 transazioni alla volta, le quali possono avere all'interno 0/1/2 tracce
  391.                 filtroPaginato.setOffset(offset);
  392.                 list = this.getTracceEngine(filtroPaginato);
  393.             }
  394.         }catch(DriverTracciamentoNotFoundException notFound){
  395.             // ignore
  396.         }
  397.         return count;
  398.     }

  399.     @Override
  400.     public List<Traccia> getTracce(FiltroRicercaTracceConPaginazione filtro)
  401.             throws DriverTracciamentoException,
  402.             DriverTracciamentoNotFoundException {
  403.        
  404.         if(filtro.getOffset()>0){
  405.             throw new DriverTracciamentoException("Metodo non implementato in questa versione (Offset >0 non è ricostruibile)");
  406.         }
  407.        
  408.         List<Traccia> list = this.getTracceEngine(filtro);
  409.         if(filtro.getLimit()>0 && list.size()>filtro.getLimit()){
  410.             List<Traccia> listWithFilter = new ArrayList<>();
  411.             for (int i = 0; i < 25; i++) {
  412.                 listWithFilter.add(list.get(i));
  413.             }
  414.             return listWithFilter;
  415.         }
  416.         else{
  417.             return list;
  418.         }
  419.     }
  420.     private void addTracciaSafe(List<Traccia> tracce, RuoloMessaggio ruolo, Connection con, Map<String, String> propertiesRicerca, FiltroRicercaTracceConPaginazione filtro) throws DriverTracciamentoException {
  421.         try{
  422.             tracce.add(this.getTracciaByPropertiesEngine(con, propertiesRicerca, ruolo,
  423.                     filtro.getMinDate(), filtro.getMaxDate()));
  424.         }catch(DriverTracciamentoNotFoundException dNotFound){
  425.             // ignore
  426.         }
  427.     }
  428.     private List<Traccia> getTracceEngine(FiltroRicercaTracceConPaginazione filtro)
  429.             throws DriverTracciamentoException,
  430.             DriverTracciamentoNotFoundException {
  431.        
  432.         Connection con = null;

  433.         JDBCServiceManager transazioniServiceManager = null;
  434.         try{
  435.             con = getConnection();
  436.             checkConnection(con);
  437.                        
  438.             transazioniServiceManager =
  439.                     (JDBCServiceManager) this.daoFactory.getServiceManager(new ProjectInfo(), con, true);
  440.            
  441.             ITransazioneServiceSearch transazioneServiceSearch = transazioniServiceManager.getTransazioneServiceSearch();
  442.                        
  443.             IPaginatedExpression expression = this.newPaginatedExpressionEngine(transazioneServiceSearch, filtro);
  444.                        
  445.             List<Map<String, Object>> lstTransazioni = transazioneServiceSearch.select(expression, Transazione.model().ID_TRANSAZIONE,
  446.                     Transazione.model().ID_MESSAGGIO_RICHIESTA,Transazione.model().ID_MESSAGGIO_RISPOSTA);
  447.            
  448.             List<Traccia> tracce = new ArrayList<>();

  449.             for(Map<String, Object> transazioneMap : lstTransazioni) {
  450.                
  451.                 // **** Lettura da database ****
  452.                
  453.                 String idTransazione = (String) transazioneMap.get(Transazione.model().ID_TRANSAZIONE.getFieldName());
  454.                
  455.                 Object oIdBustaRichiesta = transazioneMap.get(Transazione.model().ID_MESSAGGIO_RICHIESTA.getFieldName());
  456.                 String idBustaRichiesta = (oIdBustaRichiesta instanceof String) ? (String) oIdBustaRichiesta : null;
  457.                
  458.                 Object oIdBustaRisposta = transazioneMap.get(Transazione.model().ID_MESSAGGIO_RISPOSTA.getFieldName());
  459.                 String idBustaRisposta = (oIdBustaRisposta instanceof String)  ? (String) oIdBustaRisposta : null;
  460.                
  461.                 Map<String, String> propertiesRicerca = new HashMap<>();
  462.                 propertiesRicerca.put(CostantiDB.TRACCE_COLUMN_ID_TRANSAZIONE, idTransazione);
  463.                
  464.                 if(filtro.getIdBusta()!=null){
  465.                     if(filtro.getTipoTraccia()==null){
  466.                         if(filtro.getIdBusta().equals(idBustaRichiesta)){
  467.                             addTracciaSafe(tracce, RuoloMessaggio.RICHIESTA, con, propertiesRicerca, filtro);
  468.                         }else if(filtro.getIdBusta().equals(idBustaRisposta)){
  469.                             addTracciaSafe(tracce, RuoloMessaggio.RISPOSTA, con, propertiesRicerca, filtro);
  470.                         }
  471.                     }
  472.                     else{
  473.                         switch (filtro.getTipoTraccia()) {
  474.                         case RICHIESTA:
  475.                             addTracciaSafe(tracce, RuoloMessaggio.RICHIESTA, con, propertiesRicerca, filtro);
  476.                             break;
  477.                         case RISPOSTA:
  478.                             addTracciaSafe(tracce, RuoloMessaggio.RISPOSTA, con, propertiesRicerca, filtro);
  479.                             break;
  480.                         default:
  481.                             break;
  482.                         }
  483.                     }
  484.                 }
  485.                 else if(filtro.getIdBustaRichiesta()!=null || filtro.getIdBustaRisposta()!=null){
  486.                     if(filtro.getIdBustaRichiesta()!=null){
  487.                         addTracciaSafe(tracce, RuoloMessaggio.RICHIESTA, con, propertiesRicerca, filtro);
  488.                     }
  489.                     if(filtro.getIdBustaRisposta()!=null){
  490.                         addTracciaSafe(tracce, RuoloMessaggio.RISPOSTA, con, propertiesRicerca, filtro);
  491.                     }
  492.                 }
  493.                 else if(filtro.getRiferimentoMessaggio()!=null){
  494.                     addTracciaSafe(tracce, RuoloMessaggio.RISPOSTA, con, propertiesRicerca, filtro);
  495.                 }
  496.                 else{
  497.                     // aggiungo sia richiesta che risposta se presenti
  498.                     addTracciaSafe(tracce, RuoloMessaggio.RICHIESTA, con, propertiesRicerca, filtro);
  499.                     addTracciaSafe(tracce, RuoloMessaggio.RISPOSTA, con, propertiesRicerca, filtro);
  500.                 }              
  501.             }
  502.            
  503.             if(tracce.isEmpty()){
  504.                 throw new DriverTracciamentoNotFoundException("Tracce non trovate che rispettano il filtro di ricerca (Filtro:"+filtro.toString()+")");
  505.             }
  506.             else{
  507.                 return tracce;
  508.             }
  509.                
  510.         }catch(DriverTracciamentoNotFoundException e){
  511.             throw e;
  512.         }catch(NotFoundException e){
  513.             throw new DriverTracciamentoNotFoundException(e.getMessage(),e);
  514.         }catch(Exception e){
  515.             throw new DriverTracciamentoException("Riscontrato errore durante la lettura dei dati (Filtro:"+filtro.toString()+"): "+e.getMessage(),e);
  516.         }finally{
  517.             try{
  518.                 if(transazioniServiceManager!=null) {
  519.                     transazioniServiceManager.close();
  520.                 }
  521.             }catch(Exception e){
  522.                 // close
  523.             }
  524.             closeConnection(con);
  525.         }
  526.        
  527.     }
  528.    
  529.     private IExpression newExpressionEngine(ITransazioneServiceSearch transazioneServiceSearch,FiltroRicercaTracce filtro) throws ServiceException, NotImplementedException, ExpressionNotImplementedException, ExpressionException, ProtocolException {
  530.         IExpression expression = transazioneServiceSearch.newExpression();
  531.        
  532.         if(filtro.getMaxDate()!=null){
  533.             expression.lessEquals(Transazione.model().DATA_INGRESSO_RICHIESTA, filtro.getMaxDate());
  534.         }
  535.         if(filtro.getMinDate()!=null){
  536.             expression.greaterEquals(Transazione.model().DATA_INGRESSO_RICHIESTA, filtro.getMinDate());
  537.         }
  538.         if(filtro.getTipoPdD()!=null){
  539.             expression.equals(Transazione.model().PDD_RUOLO, filtro.getTipoPdD().getTipo());
  540.         }
  541.         if(filtro.getDominio()!=null){
  542.             if(filtro.getDominio().getCodicePorta()!=null){
  543.                 expression.equals(Transazione.model().PDD_CODICE, filtro.getDominio().getCodicePorta());
  544.             }
  545.             if(filtro.getDominio().getTipo()!=null){
  546.                 expression.equals(Transazione.model().PDD_TIPO_SOGGETTO, filtro.getDominio().getTipo());
  547.             }
  548.             if(filtro.getDominio().getNome()!=null){
  549.                 expression.equals(Transazione.model().PDD_NOME_SOGGETTO, filtro.getDominio().getNome());
  550.             }
  551.         }
  552.        
  553.         boolean isOttimizzazioniTransazioniIdProtocolloDateInCampiSeparati = true; // static info
  554.        
  555.         if(filtro.getIdBusta()!=null){
  556.             IExpression expressionIdBusta = transazioneServiceSearch.newExpression();
  557.             if(isOttimizzazioniTransazioniIdProtocolloDateInCampiSeparati){
  558.                
  559.                 if(filtro.getProtocollo()==null){
  560.                     throw new ServiceException("Se nel filtro viene impostato l'id della busta, ed è attiva l'opzione della comprensione delle date interne agli id, deve essere specificato nel filtro anche il protocollo");
  561.                 }
  562.                 IProtocolFactory<?> protocolFactory = ProtocolFactoryManager.getInstance().getProtocolFactoryByName(filtro.getProtocollo());
  563.                 IBustaBuilder<?> protocolBustaBuilder = protocolFactory.createBustaBuilder(null);
  564.                
  565.                 Timestamp tIdBusta = DateUtility.getTimestampIntoIdProtocollo(this.log,protocolBustaBuilder,filtro.getIdBusta());
  566.                 if(tIdBusta==null){
  567.                     if(filtro.getTipoTraccia()==null){
  568.                         expressionIdBusta.equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBusta());
  569.                         expressionIdBusta.or();
  570.                         expressionIdBusta.equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBusta());
  571.                     }
  572.                     else{
  573.                         switch (filtro.getTipoTraccia()) {
  574.                         case RICHIESTA:
  575.                             expressionIdBusta.equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBusta());
  576.                             break;
  577.                         case RISPOSTA:
  578.                             expressionIdBusta.equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBusta());
  579.                             break;
  580.                         default:
  581.                             break;
  582.                         }
  583.                     }
  584.                 }else{
  585.                     IExpression expressionRichiesta = transazioneServiceSearch.newExpression();
  586.                     IExpression expressionRisposta = transazioneServiceSearch.newExpression();
  587.                    
  588.                     if(filtro.getTipoTraccia()==null){
  589.                         expressionRichiesta.equals(Transazione.model().DATA_ID_MSG_RICHIESTA, tIdBusta).and().equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBusta());
  590.                         expressionRisposta.equals(Transazione.model().DATA_ID_MSG_RISPOSTA, tIdBusta).and().equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBusta());
  591.                         expressionIdBusta.or(expressionRichiesta, expressionRisposta);
  592.                     }
  593.                     else{
  594.                         switch (filtro.getTipoTraccia()) {
  595.                         case RICHIESTA:
  596.                             expressionIdBusta.equals(Transazione.model().DATA_ID_MSG_RICHIESTA, tIdBusta).and().equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBusta());
  597.                             break;
  598.                         case RISPOSTA:
  599.                             expressionIdBusta.equals(Transazione.model().DATA_ID_MSG_RISPOSTA, tIdBusta).and().equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBusta());
  600.                             break;
  601.                         default:
  602.                             break;
  603.                         }
  604.                     }
  605.                 }
  606.             }else{
  607.                 if(filtro.getTipoTraccia()==null){
  608.                     expressionIdBusta.equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBusta()).
  609.                         or().
  610.                         equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBusta());
  611.                 }
  612.                 else{
  613.                     switch (filtro.getTipoTraccia()) {
  614.                     case RICHIESTA:
  615.                         expressionIdBusta.equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBusta());
  616.                         break;
  617.                     case RISPOSTA:
  618.                         expressionIdBusta.equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBusta());
  619.                         break;
  620.                     default:
  621.                         break;
  622.                     }
  623.                 }
  624.             }
  625.             expression.and(expressionIdBusta);
  626.         }
  627.        
  628.         if(filtro.getIdBustaRichiesta()!=null){
  629.             if(isOttimizzazioniTransazioniIdProtocolloDateInCampiSeparati){
  630.                
  631.                 if(filtro.getProtocollo()==null){
  632.                     throw new ServiceException("Se nel filtro viene impostato l'identificativo di richiesta della busta, ed è attiva l'opzione della comprensione delle date interne agli id, deve essere specificato nel filtro anche il protocollo");
  633.                 }
  634.                 IProtocolFactory<?> protocolFactory = ProtocolFactoryManager.getInstance().getProtocolFactoryByName(filtro.getProtocollo());
  635.                 IBustaBuilder<?> protocolBustaBuilder = protocolFactory.createBustaBuilder(null);
  636.                
  637.                 Timestamp tIdBusta = DateUtility.getTimestampIntoIdProtocollo(this.log,protocolBustaBuilder,filtro.getIdBustaRichiesta());
  638.                 if(tIdBusta==null){
  639.                     expression.equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBustaRichiesta());
  640.                 }else{
  641.                     IExpression expressionIdBusta = transazioneServiceSearch.newExpression();
  642.                     expressionIdBusta.equals(Transazione.model().DATA_ID_MSG_RICHIESTA, tIdBusta).and().
  643.                         equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBustaRichiesta());
  644.                     expression.and(expressionIdBusta);
  645.                 }
  646.             }else{
  647.                 expression.equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getIdBustaRichiesta());
  648.             }
  649.         }
  650.        
  651.         if(filtro.getIdBustaRisposta()!=null){
  652.             if(isOttimizzazioniTransazioniIdProtocolloDateInCampiSeparati){
  653.                
  654.                 if(filtro.getProtocollo()==null){
  655.                     throw new ServiceException("Se nel filtro viene impostato l'identificativo di risposta della busta, ed è attiva l'opzione della comprensione delle date interne agli id, deve essere specificato nel filtro anche il protocollo");
  656.                 }
  657.                 IProtocolFactory<?> protocolFactory = ProtocolFactoryManager.getInstance().getProtocolFactoryByName(filtro.getProtocollo());
  658.                 IBustaBuilder<?> protocolBustaBuilder = protocolFactory.createBustaBuilder(null);
  659.                
  660.                 Timestamp tIdBusta = DateUtility.getTimestampIntoIdProtocollo(this.log,protocolBustaBuilder,filtro.getIdBustaRisposta());
  661.                 if(tIdBusta==null){
  662.                     expression.equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBustaRisposta());
  663.                 }else{
  664.                     IExpression expressionIdBusta = transazioneServiceSearch.newExpression();
  665.                     expressionIdBusta.equals(Transazione.model().DATA_ID_MSG_RISPOSTA, tIdBusta).and().
  666.                         equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBustaRisposta());
  667.                     expression.and(expressionIdBusta);
  668.                 }
  669.             }else{
  670.                 expression.equals(Transazione.model().ID_MESSAGGIO_RISPOSTA, filtro.getIdBustaRisposta());
  671.             }
  672.         }
  673.        
  674.         if(filtro.getRiferimentoMessaggio()!=null){
  675.             if(isOttimizzazioniTransazioniIdProtocolloDateInCampiSeparati){
  676.                
  677.                 if(filtro.getProtocollo()==null){
  678.                     throw new ServiceException("Se nel filtro viene impostato il riferimento messaggio della busta, ed è attiva l'opzione della comprensione delle date interne agli id, deve essere specificato nel filtro anche il protocollo");
  679.                 }
  680.                 IProtocolFactory<?> protocolFactory = ProtocolFactoryManager.getInstance().getProtocolFactoryByName(filtro.getProtocollo());
  681.                 IBustaBuilder<?> protocolBustaBuilder = protocolFactory.createBustaBuilder(null);
  682.                
  683.                 Timestamp tRifMessaggio = DateUtility.getTimestampIntoIdProtocollo(this.log,protocolBustaBuilder,filtro.getRiferimentoMessaggio());
  684.                 if(tRifMessaggio==null){
  685.                     expression.equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getRiferimentoMessaggio());
  686.                 }else{
  687.                     IExpression expressionRiferimento = transazioneServiceSearch.newExpression();
  688.                     expressionRiferimento.equals(Transazione.model().DATA_ID_MSG_RICHIESTA, tRifMessaggio).and().equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getRiferimentoMessaggio());
  689.                     expression.and(expressionRiferimento);
  690.                 }
  691.             }else{
  692.                 expression.equals(Transazione.model().ID_MESSAGGIO_RICHIESTA, filtro.getRiferimentoMessaggio());
  693.             }
  694.         }

  695.         if(filtro.getInformazioniProtocollo()!=null){
  696.             InformazioniProtocollo info = filtro.getInformazioniProtocollo();
  697.             if(info.getMittente()!=null){
  698.                 if(info.getMittente().getTipo()!=null){
  699.                     expression.equals(Transazione.model().TIPO_SOGGETTO_FRUITORE, info.getMittente().getTipo());
  700.                 }
  701.                 if(info.getMittente().getNome()!=null){
  702.                     expression.equals(Transazione.model().NOME_SOGGETTO_FRUITORE, info.getMittente().getNome());
  703.                 }
  704.                 if(info.getMittente().getCodicePorta()!=null){
  705.                     expression.equals(Transazione.model().IDPORTA_SOGGETTO_FRUITORE, info.getMittente().getCodicePorta());
  706.                 }
  707.             }
  708.             if(info.getDestinatario()!=null){
  709.                 if(info.getDestinatario().getTipo()!=null){
  710.                     expression.equals(Transazione.model().TIPO_SOGGETTO_EROGATORE, info.getDestinatario().getTipo());
  711.                 }
  712.                 if(info.getDestinatario().getNome()!=null){
  713.                     expression.equals(Transazione.model().NOME_SOGGETTO_EROGATORE, info.getDestinatario().getNome());
  714.                 }
  715.                 if(info.getDestinatario().getCodicePorta()!=null){
  716.                     expression.equals(Transazione.model().IDPORTA_SOGGETTO_EROGATORE, info.getDestinatario().getCodicePorta());
  717.                 }
  718.             }
  719.             if(info.getTipoServizio()!=null){
  720.                 expression.equals(Transazione.model().TIPO_SERVIZIO, info.getTipoServizio());
  721.             }
  722.             if(info.getServizio()!=null){
  723.                 expression.equals(Transazione.model().NOME_SERVIZIO, info.getServizio());
  724.             }
  725.             if(info.getAzione()!=null){
  726.                 expression.equals(Transazione.model().AZIONE, info.getAzione());
  727.             }
  728.             if(info.getProfiloCollaborazioneEngine()!=null){
  729.                 expression.equals(Transazione.model().PROFILO_COLLABORAZIONE_OP_2, info.getProfiloCollaborazioneEngine().getEngineValue());
  730.             }
  731.             if(info.getProfiloCollaborazioneProtocollo()!=null){
  732.                 expression.equals(Transazione.model().PROFILO_COLLABORAZIONE_PROT, info.getProfiloCollaborazioneProtocollo());
  733.             }
  734.         }

  735.         // Correlazione Applicativa Richiesta / Risposta:
  736.         // - se vengono forniti entrambi i campi, li controllo entrambi (in AND o OR a seconda del parametro isIdCorrelazioneApplicativaOrMatch)
  737.         // - se viene fornito uno solo dei campi viene aggiunto in maniera canonica
  738.        
  739.         if(filtro.getIdCorrelazioneApplicativa() != null && filtro.getIdCorrelazioneApplicativaRisposta() != null){
  740.            
  741.             IExpression correlazioneExpression = transazioneServiceSearch.newExpression();
  742.            
  743.             correlazioneExpression.equals(Transazione.model().ID_CORRELAZIONE_APPLICATIVA, filtro.getIdCorrelazioneApplicativa());
  744.             if(filtro.isIdCorrelazioneApplicativaOrMatch()) {
  745.                 correlazioneExpression.or();
  746.             } else {
  747.                 correlazioneExpression.and();
  748.             }
  749.             correlazioneExpression.equals(Transazione.model().ID_CORRELAZIONE_APPLICATIVA_RISPOSTA, filtro.getIdCorrelazioneApplicativaRisposta());

  750.             expression.and(correlazioneExpression);
  751.            
  752.         }   else if(filtro.getIdCorrelazioneApplicativa() != null){
  753.             expression.equals(Transazione.model().ID_CORRELAZIONE_APPLICATIVA, filtro.getIdCorrelazioneApplicativa());
  754.         }   else if(filtro.getIdCorrelazioneApplicativaRisposta() != null){
  755.             expression.equals(Transazione.model().ID_CORRELAZIONE_APPLICATIVA_RISPOSTA, filtro.getIdCorrelazioneApplicativaRisposta());
  756.         }
  757.        
  758.         if(filtro.getServizioApplicativoFruitore()!=null){
  759.             expression.equals(Transazione.model().SERVIZIO_APPLICATIVO_FRUITORE, filtro.getServizioApplicativoFruitore());
  760.         }
  761.         if(filtro.getServizioApplicativoErogatore()!=null){
  762.             expression.equals(Transazione.model().SERVIZIO_APPLICATIVO_EROGATORE, filtro.getServizioApplicativoErogatore());
  763.         }

  764.         if(filtro.getProtocollo()!=null){
  765.             expression.equals(Transazione.model().PROTOCOLLO, filtro.getProtocollo());
  766.         }
  767.        
  768.         return expression;
  769.     }
  770.     private IPaginatedExpression newPaginatedExpressionEngine(ITransazioneServiceSearch transazioneServiceSearch,FiltroRicercaTracceConPaginazione filtro) throws ServiceException, NotImplementedException, ExpressionNotImplementedException, ExpressionException, ProtocolException {
  771.         IPaginatedExpression expression = transazioneServiceSearch.toPaginatedExpression(this.newExpressionEngine(transazioneServiceSearch, filtro));
  772.        
  773.         expression.sortOrder(filtro.isAsc() ? SortOrder.ASC : SortOrder.DESC);
  774.         expression.addOrder(Transazione.model().DATA_INGRESSO_RICHIESTA);
  775.        
  776.         expression.offset(filtro.getOffset());
  777.         if(filtro.getLimit()>0)
  778.             expression.limit(filtro.getLimit());
  779.        
  780.         return expression;
  781.     }

  782.     @Override
  783.     public int deleteTracce(FiltroRicercaTracce filter)
  784.             throws DriverTracciamentoException {
  785.         throw new DriverTracciamentoException(NON_IMPLEMENTATO);
  786.     }

  787.     @Override
  788.     public Traccia getTraccia(String idBusta, IDSoggetto codicePorta)
  789.             throws DriverTracciamentoException,
  790.             DriverTracciamentoNotFoundException {
  791.         throw new DriverTracciamentoException(NON_IMPLEMENTATO);
  792.     }

  793.     @Override
  794.     public Traccia getTraccia(String idBusta, IDSoggetto codicePorta,
  795.             boolean ricercaIdBustaComeRiferimentoMessaggio)
  796.             throws DriverTracciamentoException,
  797.             DriverTracciamentoNotFoundException {
  798.         throw new DriverTracciamentoException(NON_IMPLEMENTATO);
  799.     }

  800.     @Override
  801.     public Traccia getTraccia(RuoloMessaggio tipoTraccia,
  802.             Map<String, String> propertiesRicerca)
  803.             throws DriverTracciamentoException,
  804.             DriverTracciamentoNotFoundException {
  805.         try{
  806.             Traccia tr = getTracciaByPropertiesEngine(null, propertiesRicerca, tipoTraccia,
  807.                     null, null);            
  808.             if(tr==null){
  809.                 throw new DriverTracciamentoNotFoundException("NotFound");
  810.             }
  811.             return tr;
  812.            
  813.         }catch(DriverTracciamentoNotFoundException e){
  814.             throw e;
  815.         }catch(Exception e){
  816.             throw new DriverTracciamentoException(e.getMessage(),e);
  817.         }
  818.     }
  819.    
  820.     @Override
  821.     public Traccia getTraccia(String idTransazione, RuoloMessaggio tipoTraccia)
  822.             throws DriverTracciamentoException, DriverTracciamentoNotFoundException {
  823.        
  824.         Map<String, String> propertiesRicerca = new HashMap<>();
  825.         propertiesRicerca.put(CostantiDB.TRACCE_COLUMN_ID_TRANSAZIONE, idTransazione);
  826.         return this.getTraccia(tipoTraccia, propertiesRicerca);
  827.        
  828.     }
  829.    
  830.    
  831.    
  832.     /* ******* RISORSE INTERNE ********** */
  833.    
  834.     @Override
  835.     public void close() throws DriverTracciamentoException {
  836.         try{
  837.             if(this.driverTracciamento!=null){
  838.                 this.driverTracciamento.close();
  839.             }
  840.         }finally{
  841.             try{
  842.                 if(this.connectionOpenViaJDBCInCostructor &&
  843.                     this.connection!=null && !this.connection.isClosed()){
  844.                     JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), this.connection, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  845.                 }
  846.             }catch(Exception e){
  847.                 if(this.log!=null) {
  848.                     this.log.error("Close connection failure: "+e.getMessage(),e);
  849.                 }
  850.                 /**throw new DriverTracciamentoException(e.getMessage(),e);*/
  851.             }
  852.         }
  853.     }
  854.    
  855.    
  856.    
  857.     private static final long ID_TRACCIA_RICOSTRUITA = -2;  // viene usato il valore -2 per indicare che si tratta di una traccia ricostruita (per funzionare dove viene usato org.openspcoop2.protocol.basic.tracciamento.DriverTracciamento.IDTRACCIA)
  858.     private static final String ID_TRACCIA_RICOSTRUITA_AS_STRING = ID_TRACCIA_RICOSTRUITA + "";
  859.    
  860.     private Connection close(Connection con) {
  861.         try{
  862.             if(con!=null) {
  863.                 JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), con, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  864.                 con = null;
  865.             }
  866.         }catch(Exception e){
  867.             // close
  868.         }
  869.         return con;
  870.     }
  871.     private JDBCServiceManager close(JDBCServiceManager transazioniServiceManager) {
  872.         try{
  873.             if(transazioniServiceManager!=null) {
  874.                 transazioniServiceManager.close();
  875.                 transazioniServiceManager = null;
  876.             }
  877.         }catch(Exception e){
  878.             // ignore
  879.         }
  880.         return transazioniServiceManager;
  881.     }
  882.    
  883.     private Traccia getTracciaByPropertiesEngine(
  884.             Connection conDB,
  885.             Map<String, String> propertiesRicerca,
  886.             RuoloMessaggio tipoTraccia,
  887.             Date minDate,
  888.             Date maxDate)
  889.             throws DriverTracciamentoException,
  890.             DriverTracciamentoNotFoundException {
  891.        
  892.         String idTransazione = propertiesRicerca.get(CostantiDB.TRACCE_COLUMN_ID_TRANSAZIONE);
  893.         if(idTransazione==null){
  894.             throw new DriverTracciamentoException("Identificativo di transazione non fornito");
  895.         }
  896.         String idTraccia = propertiesRicerca.get(org.openspcoop2.protocol.basic.tracciamento.TracciaDriver.IDTRACCIA);
  897.         boolean removeIdTraccia = false;
  898.         if(idTraccia!=null && ID_TRACCIA_RICOSTRUITA_AS_STRING.equals(idTraccia)){
  899.             propertiesRicerca.remove(org.openspcoop2.protocol.basic.tracciamento.TracciaDriver.IDTRACCIA);
  900.             removeIdTraccia = true;
  901.         }
  902.        
  903.         Connection con = null;
  904.         boolean closeConnection = true;
  905.         JDBCServiceManager transazioniServiceManager = null;
  906.         try{
  907.             if(conDB!=null){
  908.                 con = conDB;
  909.                 closeConnection = false;
  910.             }else{
  911.                 if(this.connection!=null){
  912.                     con = this.connection;
  913.                     closeConnection = false;
  914.                 }else{
  915.                     con = this.datasource.getConnection();
  916.                 }
  917.             }
  918.             if(con==null)
  919.                 throw new DriverTracciamentoException("Connection non ottenuta");
  920.            
  921.             transazioniServiceManager =
  922.                     (JDBCServiceManager) this.daoFactory.getServiceManager(new ProjectInfo(), con, true);
  923.            
  924.            
  925.             // Informazioni salvataggio tracce
  926.             CredenzialiMittente credentialsFiller = new CredenzialiMittente();
  927.             InformazioniRecordTraccia informazioniSalvataggioTraccia = getInformazioniSalvataggioTraccia(transazioniServiceManager, idTransazione, tipoTraccia, credentialsFiller,
  928.                     minDate,
  929.                     maxDate);
  930.            
  931.             // Non vi sono informazioni eventuali sulla simulazione. Provo a recuperarla direttamente
  932.             if(informazioniSalvataggioTraccia==null){
  933.                
  934.                 // per evitare deadlock di connessioni
  935.                 transazioniServiceManager = close(transazioniServiceManager);
  936.                 if(closeConnection){
  937.                     con = close(con);
  938.                 }
  939.                
  940.                 Traccia traccia = this.driverTracciamento.getTraccia(tipoTraccia, propertiesRicerca);
  941.                 // set Properties
  942.                 setPropertiesEngine(traccia, propertiesRicerca, idTransazione);
  943.                 return traccia;
  944.             }
  945.            
  946.             // Non era stata emessa una traccia di richiesta per la transazione
  947.             if(!informazioniSalvataggioTraccia.isPresente()){
  948.                 throw new DriverTracciamentoNotFoundException("non presente");
  949.             }
  950.            
  951.             // La traccia era stata interamente salvata nel database delle tracce, poiche' non possedeva tutti i valori ricostruibili automaticamente
  952.             if(!informazioniSalvataggioTraccia.isRicostruibile()){
  953.                
  954.                 // per evitare deadlock di connessioni
  955.                 transazioniServiceManager = close(transazioniServiceManager);
  956.                 if(closeConnection){
  957.                     close(con);
  958.                 }
  959.                
  960.                 Traccia traccia = this.driverTracciamento.getTraccia(tipoTraccia, propertiesRicerca);
  961.                 // set Properties
  962.                 setPropertiesEngine(traccia, propertiesRicerca, idTransazione);
  963.                 return traccia;
  964.             }
  965.            
  966.             // Recupero transazione
  967.             ITransazioneServiceSearch transazioneServiceSearch = transazioniServiceManager.getTransazioneServiceSearch();
  968.             Transazione transazione = null;
  969.             if(maxDate!=null && minDate!=null){
  970.                 // ottimizzazione per partizioni
  971.                 IPaginatedExpression exprGetIdTransazione = transazioneServiceSearch.newPaginatedExpression();
  972.                 if(maxDate!=null){
  973.                     exprGetIdTransazione.lessEquals(Transazione.model().DATA_INGRESSO_RICHIESTA, maxDate);
  974.                 }
  975.                 if(minDate!=null){
  976.                     exprGetIdTransazione.greaterEquals(Transazione.model().DATA_INGRESSO_RICHIESTA, minDate);
  977.                 }
  978.                 exprGetIdTransazione.equals(Transazione.model().ID_TRANSAZIONE,idTransazione);
  979.                 /**transazione = transazioneServiceSearch.find(exprGetIdTransazione);*/
  980.                 // NOTA: findAll più efficiente
  981.                 List<Transazione> transazioni = transazioneServiceSearch.findAll(exprGetIdTransazione);
  982.                 if(transazioni==null || transazioni.isEmpty()) {
  983.                     throw new DriverTracciamentoNotFoundException("Transazione con id '"+idTransazione+"' non trovata minDate:"+minDate+" maxDate:"+maxDate+"");
  984.                 }
  985.                 transazione = transazioni.get(0);
  986.                 if(transazione == null) {
  987.                     throw new DriverTracciamentoNotFoundException("Transazione con id '"+idTransazione+"' minDate:"+minDate+" maxDate:"+maxDate+" ritornata null?");
  988.                 }          
  989.             }
  990.             else {
  991.                 transazione = transazioneServiceSearch.get(idTransazione);
  992.             }
  993.            
  994.             // Costruzione traccia
  995.             Traccia traccia = this.buildTraccia(tipoTraccia, transazione, credentialsFiller.getTokenClientId(), informazioniSalvataggioTraccia);
  996.             // set Properties
  997.             setPropertiesEngine(traccia, propertiesRicerca, idTransazione);
  998.             return traccia;
  999.                                
  1000.         }catch(DriverTracciamentoNotFoundException e){
  1001.             throw e;
  1002.         }catch(Exception e){
  1003.             throw new DriverTracciamentoException("Riscontrato errore durante la lettura dei dati (Transazione:"+idTransazione+"): "+e.getMessage(),e);
  1004.         }finally{
  1005.             close(transazioniServiceManager);
  1006.             if(closeConnection){
  1007.                 close(con);
  1008.             }
  1009.             if(removeIdTraccia){
  1010.                 propertiesRicerca.put(org.openspcoop2.protocol.basic.tracciamento.TracciaDriver.IDTRACCIA,idTraccia);
  1011.             }
  1012.         }
  1013.        
  1014.     }
  1015.     private void setPropertiesEngine(Traccia traccia, Map<String, String> propertiesRicerca, String idTransazione){
  1016.         // set Properties
  1017.         if(traccia.getProperties()==null){
  1018.             traccia.setProperties(new HashMap<>());
  1019.         }
  1020.         if(propertiesRicerca!=null && propertiesRicerca.size()>0){
  1021.             traccia.getProperties().putAll(propertiesRicerca);
  1022.         }
  1023.         if(!traccia.getProperties().containsKey(CostantiDB.TRACCE_COLUMN_ID_TRANSAZIONE)){
  1024.             traccia.getProperties().put(CostantiDB.TRACCE_COLUMN_ID_TRANSAZIONE, idTransazione);
  1025.         }
  1026.         if(!traccia.getProperties().containsKey(org.openspcoop2.protocol.basic.tracciamento.TracciaDriver.IDTRACCIA)){
  1027.             traccia.getProperties().put(org.openspcoop2.protocol.basic.tracciamento.TracciaDriver.IDTRACCIA, ID_TRACCIA_RICOSTRUITA_AS_STRING);
  1028.         }
  1029.     }

  1030.     private Traccia buildTraccia(RuoloMessaggio tipoTraccia, Transazione transazione, CredenzialeMittente credenzialeClientId, InformazioniRecordTraccia infoSalvataggioTraccia) throws CoreException {
  1031.        
  1032.         Traccia traccia = new Traccia();
  1033.        
  1034.         Object oGdo = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_DATA_REGISTRAZIONE).getDato();
  1035.         traccia.setGdo(oGdo!=null ? (Date)oGdo : null);
  1036.        
  1037.         IDSoggetto idSoggetto = null;
  1038.         if(transazione.getPddCodice()!=null || transazione.getPddTipoSoggetto()!=null || transazione.getPddNomeSoggetto()!=null){
  1039.             idSoggetto = new IDSoggetto(transazione.getPddTipoSoggetto(), transazione.getPddNomeSoggetto(), transazione.getPddCodice());
  1040.         }
  1041.         traccia.setIdSoggetto(idSoggetto);
  1042.        
  1043.         switch (transazione.getPddRuolo()) {
  1044.         case APPLICATIVA:
  1045.             traccia.setTipoPdD(TipoPdD.APPLICATIVA);    
  1046.             break;
  1047.         case DELEGATA:
  1048.             traccia.setTipoPdD(TipoPdD.DELEGATA);  
  1049.             break;
  1050.         case INTEGRATION_MANAGER:
  1051.             traccia.setTipoPdD(TipoPdD.INTEGRATION_MANAGER);    
  1052.             break;
  1053.         case ROUTER:
  1054.             traccia.setTipoPdD(TipoPdD.ROUTER);
  1055.             break;
  1056.         default:
  1057.             break;
  1058.         }
  1059.        
  1060.         traccia.setTipoMessaggio(tipoTraccia);

  1061.         traccia.setBusta(this.buildBusta(tipoTraccia, transazione, credenzialeClientId, infoSalvataggioTraccia ));
  1062.        
  1063.         if(tipoTraccia.equals(RuoloMessaggio.RICHIESTA)) {
  1064.             traccia.setBustaAsString(transazione.getHeaderProtocolloRichiesta());
  1065.         } else {
  1066.             traccia.setBustaAsString(transazione.getHeaderProtocolloRisposta());
  1067.         }
  1068.        
  1069.         traccia.setCorrelazioneApplicativa(transazione.getIdCorrelazioneApplicativa());
  1070.         traccia.setCorrelazioneApplicativaRisposta(transazione.getIdCorrelazioneApplicativaRisposta());
  1071.        
  1072.         if(tipoTraccia.equals(RuoloMessaggio.RICHIESTA)) {
  1073.             traccia.setLocation(transazione.getLocationRichiesta());
  1074.         } else {
  1075.             traccia.setLocation(transazione.getLocationRisposta());
  1076.         }
  1077.        
  1078.         traccia.setProtocollo(transazione.getProtocollo());
  1079.        
  1080.         EsitoElaborazioneMessaggioTracciato esito = new EsitoElaborazioneMessaggioTracciato();
  1081.         Object oEsito = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_ESITO_TRACCIA).getDato();
  1082.         if(oEsito!=null){
  1083.             Character esitoChar = (Character) oEsito;
  1084.             if(CostantiMappingTracciamento.TRACCIA_BUSTA_ESITO_TRACCIA_INVIATA == esitoChar ){
  1085.                 esito.setEsito(EsitoElaborazioneMessaggioTracciatura.INVIATO);
  1086.             }
  1087.             else if(CostantiMappingTracciamento.TRACCIA_BUSTA_ESITO_TRACCIA_RICEVUTA == esitoChar ){
  1088.                 esito.setEsito(EsitoElaborazioneMessaggioTracciatura.RICEVUTO);
  1089.             }
  1090.             else if(CostantiMappingTracciamento.TRACCIA_BUSTA_ESITO_TRACCIA_ERRORE == esitoChar ){
  1091.                 esito.setEsito(EsitoElaborazioneMessaggioTracciatura.ERRORE);
  1092.             }
  1093.         }
  1094.         if(esito.getEsito()!=null && esito.getEsito().equals(EsitoElaborazioneMessaggioTracciatura.ERRORE) &&
  1095.                 TipoPdD.DELEGATA.equals(traccia.getTipoPdD())) {
  1096.             esito.setDettaglio(transazione.getFaultCooperazione());
  1097.         }
  1098.        
  1099.         traccia.setEsitoElaborazioneMessaggioTracciato(esito);
  1100.        
  1101.         return traccia;
  1102.     }
  1103.    
  1104.     private Busta buildBusta(RuoloMessaggio tipoTraccia, Transazione transazione, CredenzialeMittente credenzialeClientId,
  1105.             InformazioniRecordTraccia infoSalvataggioTraccia) throws CoreException {
  1106.        
  1107.         boolean richiesta = tipoTraccia.equals(RuoloMessaggio.RICHIESTA);
  1108.        
  1109.         IDSoggetto mittente = PopolamentoTracciaUtils.getIdSoggettoMittente(transazione, richiesta);
  1110.         IDSoggetto destinatario = PopolamentoTracciaUtils.getIdSoggettoDestinatario(transazione, richiesta);
  1111.        
  1112.        
  1113.         Busta busta = new Busta(transazione.getProtocollo());
  1114.        
  1115.         busta.setMittente(mittente.getNome());
  1116.         busta.setTipoMittente(mittente.getTipo());
  1117.         busta.setIdentificativoPortaMittente(mittente.getCodicePorta());
  1118.         busta.setIndirizzoMittente(richiesta ? transazione.getIndirizzoSoggettoFruitore() :  transazione.getIndirizzoSoggettoErogatore());
  1119.        
  1120.         busta.setDestinatario(destinatario.getNome());
  1121.         busta.setTipoDestinatario(destinatario.getTipo());
  1122.         busta.setIdentificativoPortaDestinatario(destinatario.getCodicePorta());
  1123.         busta.setIndirizzoDestinatario(richiesta ? transazione.getIndirizzoSoggettoErogatore() :  transazione.getIndirizzoSoggettoFruitore());
  1124.        
  1125.         boolean applicativoToken = false;
  1126.        
  1127.         if(credenzialeClientId!=null) {
  1128.             AbstractDatoRicostruzione<?> dato = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_SOGGETTO_APPLICATIVO_TOKEN);
  1129.             Object tracciaBustaSoggettoApplicativoToken = null;
  1130.             if(dato!=null) {
  1131.                 tracciaBustaSoggettoApplicativoToken = dato.getDato();
  1132.             }
  1133.             if(tracciaBustaSoggettoApplicativoToken != null) {
  1134.                 boolean soggettoApplicativoToken = ((Character)tracciaBustaSoggettoApplicativoToken) == CostantiMappingTracciamento.TRACCIA_BUSTA_SOGGETTO_APPLICATIVO_TOKEN_TRUE;
  1135.                 if(soggettoApplicativoToken) {
  1136.                     IDServizioApplicativo idApplicativoToken = null;
  1137.                     if(credenzialeClientId!=null && credenzialeClientId.getCredenziale()!=null) {
  1138.                         try {
  1139.                             idApplicativoToken = CredenzialeTokenClient.convertApplicationDBValueToOriginal(credenzialeClientId.getCredenziale());
  1140.                         }catch(Exception e) {
  1141.                             // ignore
  1142.                         }
  1143.                     }
  1144.                     if(idApplicativoToken!=null && idApplicativoToken.getIdSoggettoProprietario()!=null) {
  1145.                         if(RuoloMessaggio.RICHIESTA.equals(tipoTraccia)) {
  1146.                             busta.setMittente(idApplicativoToken.getIdSoggettoProprietario().getNome());
  1147.                             busta.setTipoMittente(idApplicativoToken.getIdSoggettoProprietario().getTipo());
  1148.                             busta.setIdentificativoPortaMittente(null);
  1149.                             busta.setIndirizzoMittente(null);
  1150.                             applicativoToken=true;
  1151.                         }
  1152.                         else {
  1153.                             busta.setDestinatario(idApplicativoToken.getIdSoggettoProprietario().getNome());
  1154.                             busta.setTipoDestinatario(idApplicativoToken.getIdSoggettoProprietario().getTipo());
  1155.                             busta.setIdentificativoPortaDestinatario(null);
  1156.                             busta.setIndirizzoDestinatario(null);
  1157.                             applicativoToken=true;
  1158.                         }
  1159.                     }
  1160.                 }
  1161.             }
  1162.         }
  1163.        
  1164.         busta.setProfiloDiCollaborazione(ProfiloDiCollaborazione.toProfiloDiCollaborazione(transazione.getProfiloCollaborazioneOp2()));
  1165.         busta.setProfiloDiCollaborazioneValue(transazione.getProfiloCollaborazioneProt());
  1166.        
  1167.         Object oServizioCorrelatoPresente = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_SERVIZIO_CORRELATO_PRESENTE).getDato();

  1168.         if(((Character)oServizioCorrelatoPresente).equals(CostantiMappingTracciamento.TRACCIA_BUSTA_SERVIZIO_CORRELATO_PRESENTE_TRUE)) {
  1169.             busta.setServizioCorrelato(transazione.getNomeServizioCorrelato());
  1170.             busta.setTipoServizioCorrelato(transazione.getTipoServizioCorrelato());
  1171.         }
  1172.        
  1173.         busta.setCollaborazione(transazione.getIdCollaborazione());
  1174.        
  1175.         busta.setServizio(transazione.getNomeServizio());
  1176.         busta.setTipoServizio(transazione.getTipoServizio());
  1177.         busta.setVersioneServizio(transazione.getVersioneServizio());
  1178.        
  1179.         busta.setAzione(transazione.getAzione());
  1180.        
  1181.        
  1182.         if(RuoloMessaggio.RICHIESTA.equals(tipoTraccia)){
  1183.             busta.setID(transazione.getIdMessaggioRichiesta());
  1184.         }else{
  1185.             busta.setID(transazione.getIdMessaggioRisposta());
  1186.         }
  1187.        
  1188.         Object oRiferimentoMessaggio = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_RIFERIMENTO_MESSAGGIO).getDato();
  1189.         if(oRiferimentoMessaggio!=null){
  1190.             char riferimento = ((Character)oRiferimentoMessaggio);
  1191.             String riferimentoMessaggio;
  1192.             if(CostantiMappingTracciamento.TRACCIA_BUSTA_RIFERIMENTO_MESSAGGIO_ID_MESSAGGIO_RICHIESTA == riferimento) {
  1193.                 riferimentoMessaggio = transazione.getIdMessaggioRichiesta();
  1194.             } else if(CostantiMappingTracciamento.TRACCIA_BUSTA_RIFERIMENTO_MESSAGGIO_ID_MESSAGGIO_RISPOSTA == riferimento) {
  1195.                 riferimentoMessaggio = transazione.getIdMessaggioRisposta();
  1196.             } else {
  1197.                 riferimentoMessaggio = transazione.getIdAsincrono();
  1198.             }
  1199.            
  1200.             busta.setRiferimentoMessaggio(riferimentoMessaggio);
  1201.         }
  1202.        
  1203.         Object oOraRegistrazione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_ORA_REGISTRAZIONE).getDato();
  1204.         busta.setOraRegistrazione(oOraRegistrazione!=null ? (Date)oOraRegistrazione : null);
  1205.        
  1206.         Object oTipoOraRegistrazione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_TIPO_ORA_REGISTRAZIONE_BY_OPENSPCOOP).getDato();
  1207.         TipoOraRegistrazione tipoOraRegistrazione=null;
  1208.         if(oTipoOraRegistrazione!=null){
  1209.             char tipo = ((Character)oTipoOraRegistrazione);
  1210.             if(CostantiMappingTracciamento.TIPO_ORA_REGISTRAZIONE_BY_OPENSPCOOP_SCONOSCIUTO == tipo){
  1211.                 tipoOraRegistrazione = TipoOraRegistrazione.UNKNOWN;
  1212.             }
  1213.             else if(CostantiMappingTracciamento.TIPO_ORA_REGISTRAZIONE_BY_OPENSPCOOP_SINCRONIZZATO == tipo){
  1214.                 tipoOraRegistrazione = TipoOraRegistrazione.SINCRONIZZATO;
  1215.             }
  1216.             else if(CostantiMappingTracciamento.TIPO_ORA_REGISTRAZIONE_BY_OPENSPCOOP_LOCALE == tipo){
  1217.                 tipoOraRegistrazione = TipoOraRegistrazione.LOCALE;
  1218.             }
  1219.         }
  1220.         Object oTipoOraRegistrazioneValue = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_TIPO_ORA_REGISTRAZIONE_BY_PROTOCOLLO).getDato();
  1221.         busta.setTipoOraRegistrazione(tipoOraRegistrazione,
  1222.                 oTipoOraRegistrazioneValue!=null ? (String)oTipoOraRegistrazioneValue : null);
  1223.        

  1224.         Object oScadenza = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_SCADENZA).getDato();
  1225.         if(oScadenza != null) {
  1226.             busta.setScadenza((Date) oScadenza);
  1227.         }

  1228.         Object oConfermaRicezione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_CONFERMA_RICHIESTA).getDato();
  1229.        
  1230.         if(oConfermaRicezione != null) {
  1231.             busta.setConfermaRicezione(((Character)oConfermaRicezione) == CostantiMappingTracciamento.TRACCIA_BUSTA_CONFERMA_RICHIESTA_TRUE);
  1232.         }

  1233.         Object oInoltro = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_FILTRO_DUPLICATI_CODE).getDato();
  1234.         Inoltro inoltro = null;
  1235.        
  1236.         if(oInoltro != null) {
  1237.             char value = ((Character)oInoltro);
  1238.             if(CostantiMappingTracciamento.TRACCIA_FILTRO_DUPLICATI_CODE_ALPIUUNAVOLTA == value) {
  1239.                 inoltro = Inoltro.SENZA_DUPLICATI;
  1240.             } else if(CostantiMappingTracciamento.TRACCIA_FILTRO_DUPLICATI_CODE_PIUDIUNAVOLTA == value) {
  1241.                 inoltro = Inoltro.CON_DUPLICATI;
  1242.             } else {
  1243.                 inoltro = Inoltro.UNKNOWN;
  1244.             }
  1245.            
  1246.         }
  1247.        
  1248.         Object oInoltroValue = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_FILTRO_DUPLICATI).getDato();
  1249.         busta.setInoltro(inoltro, oInoltroValue != null ? (String)oInoltroValue : null);

  1250.         Object oSequenza = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_SEQUENZA).getDato();
  1251.         if(oSequenza != null) {
  1252.             busta.setSequenza(Long.valueOf((String)oSequenza));
  1253.         }
  1254.        
  1255.         busta.setServizioApplicativoFruitore(transazione.getServizioApplicativoFruitore());
  1256.         busta.setServizioApplicativoErogatore(transazione.getServizioApplicativoErogatore());
  1257.        
  1258.         busta.setProtocollo(transazione.getProtocollo());

  1259.         busta.setDigest(richiesta ? transazione.getDigestRichiesta() : transazione.getDigestRisposta());
  1260.        
  1261.         String properties = richiesta ? transazione.getProtocolloExtInfoRichiesta() : transazione.getProtocolloExtInfoRisposta();
  1262.         Map<String, List<String>> bustaProperties = PropertiesSerializator.convertoFromDBColumnValue(properties);
  1263.         if(bustaProperties!=null && bustaProperties.size()>0){
  1264.             for (Map.Entry<String,List<String>> entry : bustaProperties.entrySet()) {
  1265.                 String key = entry.getKey();
  1266.                 List<String> values = bustaProperties.get(key);
  1267.                 if(values!=null && !values.isEmpty()) {
  1268.                     for (String value : values) {
  1269.                         busta.addProperty(key, value);  
  1270.                     }
  1271.                 }
  1272.             }
  1273.         }

  1274.         Object oRiscontroOraRegistrazione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_RISCONTRO_ORA_REGISTRAZIONE).getDato();
  1275.         Object oRiscontroTipoOraRegistrazione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_RISCONTRO_TIPO_ORA_REGISTRAZIONE).getDato();
  1276.         Object oRiscontroTipoOraRegistrazioneCode = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_RISCONTRO_TIPO_ORA_REGISTRAZIONE_CODE).getDato();

  1277.         if(oRiscontroOraRegistrazione != null && oRiscontroTipoOraRegistrazione != null && oRiscontroTipoOraRegistrazioneCode != null) {
  1278.            
  1279.             Riscontro riscontro = new Riscontro();
  1280.             riscontro.setID(transazione.getIdMessaggioRichiesta());
  1281.             riscontro.setOraRegistrazione((Date)oRiscontroOraRegistrazione);
  1282.            
  1283.             char value = ((Character)oRiscontroTipoOraRegistrazioneCode);
  1284.             if(CostantiMappingTracciamento.TRACCIA_BUSTA_RISCONTRO_TIPO_ORA_REGISTRAZIONE_CODE_LOCALE == value) {
  1285.                 riscontro.setTipoOraRegistrazione(TipoOraRegistrazione.LOCALE);
  1286.             } else if(CostantiMappingTracciamento.TRACCIA_BUSTA_RISCONTRO_TIPO_ORA_REGISTRAZIONE_CODE_SINCRONIZZATO == value) {
  1287.                 riscontro.setTipoOraRegistrazione(TipoOraRegistrazione.SINCRONIZZATO);
  1288.             } else {
  1289.                 riscontro.setTipoOraRegistrazione(TipoOraRegistrazione.UNKNOWN);
  1290.             }
  1291.            
  1292.             riscontro.setTipoOraRegistrazioneValue((String)oRiscontroTipoOraRegistrazione);
  1293.            
  1294.             busta.addRiscontro(riscontro);
  1295.         }
  1296.        
  1297.         if(!applicativoToken) {
  1298.        
  1299.             Object oPrimaTrasmissioneOraRegistrazione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_ORA_REGISTRAZIONE).getDato();
  1300.             Object oPrimaTrasmissioneTipoOraRegistrazione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_TIPO_ORA_REGISTRAZIONE).getDato();
  1301.             Object oPrimaTrasmissioneTipoOraRegistrazioneCode = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_TIPO_ORA_REGISTRAZIONE_CODE).getDato();
  1302.    
  1303.             if(oPrimaTrasmissioneOraRegistrazione != null && oPrimaTrasmissioneTipoOraRegistrazione != null && oPrimaTrasmissioneTipoOraRegistrazioneCode != null) {
  1304.                
  1305.                 Trasmissione trasmissione = new Trasmissione();
  1306.                 trasmissione.setOraRegistrazione((Date)oPrimaTrasmissioneOraRegistrazione);
  1307.                
  1308.                 boolean trasmissioneNormale = true;
  1309.                 char value = ((Character)oPrimaTrasmissioneTipoOraRegistrazioneCode);
  1310.                 if(CostantiMappingTracciamento.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_NORMALE_TIPO_ORA_REGISTRAZIONE_CODE_LOCALE == value) {
  1311.                     trasmissione.setTempo(TipoOraRegistrazione.LOCALE);
  1312.                 } else if(CostantiMappingTracciamento.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_NORMALE_TIPO_ORA_REGISTRAZIONE_CODE_SINCRONIZZATO == value) {
  1313.                     trasmissione.setTempo(TipoOraRegistrazione.SINCRONIZZATO);
  1314.                 } else if(CostantiMappingTracciamento.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_NORMALE_TIPO_ORA_REGISTRAZIONE_CODE_SCONOSCIUTO == value) {
  1315.                     trasmissione.setTempo(TipoOraRegistrazione.UNKNOWN);
  1316.                 } else if(CostantiMappingTracciamento.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_INVERTITA_TIPO_ORA_REGISTRAZIONE_CODE_LOCALE == value) {
  1317.                     trasmissione.setTempo(TipoOraRegistrazione.LOCALE);
  1318.                     trasmissioneNormale = false;
  1319.                 } else if(CostantiMappingTracciamento.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_INVERTITA_TIPO_ORA_REGISTRAZIONE_CODE_SINCRONIZZATO == value) {
  1320.                     trasmissione.setTempo(TipoOraRegistrazione.SINCRONIZZATO);
  1321.                     trasmissioneNormale = false;
  1322.                 } else if(CostantiMappingTracciamento.TRACCIA_BUSTA_PRIMA_TRASMISSIONE_INVERTITA_TIPO_ORA_REGISTRAZIONE_CODE_SCONOSCIUTO == value) {
  1323.                     trasmissione.setTempo(TipoOraRegistrazione.UNKNOWN);
  1324.                     trasmissioneNormale = false;
  1325.                 } else {
  1326.                     trasmissione.setTempo(TipoOraRegistrazione.UNKNOWN);
  1327.                 }
  1328.                
  1329.                 trasmissione.setTempoValue((String)oPrimaTrasmissioneTipoOraRegistrazione);
  1330.                
  1331.                 if(trasmissioneNormale){
  1332.                     trasmissione.setOrigine(mittente.getNome());
  1333.                     trasmissione.setTipoOrigine(mittente.getTipo());
  1334.                     trasmissione.setIdentificativoPortaOrigine(mittente.getCodicePorta());
  1335.                     trasmissione.setIndirizzoOrigine(busta.getIndirizzoMittente());
  1336.                    
  1337.                     trasmissione.setDestinazione(destinatario.getNome());
  1338.                     trasmissione.setTipoDestinazione(destinatario.getTipo());
  1339.                     trasmissione.setIdentificativoPortaDestinazione(destinatario.getCodicePorta());
  1340.                     trasmissione.setIndirizzoDestinazione(busta.getIndirizzoDestinatario());
  1341.                 }
  1342.                 else{
  1343.                     trasmissione.setOrigine(destinatario.getNome());
  1344.                     trasmissione.setTipoOrigine(destinatario.getTipo());
  1345.                     trasmissione.setIdentificativoPortaOrigine(destinatario.getCodicePorta());
  1346.                     trasmissione.setIndirizzoOrigine(busta.getIndirizzoDestinatario());
  1347.                    
  1348.                     trasmissione.setDestinazione(mittente.getNome());
  1349.                     trasmissione.setTipoDestinazione(mittente.getTipo());
  1350.                     trasmissione.setIdentificativoPortaDestinazione(mittente.getCodicePorta());
  1351.                     trasmissione.setIndirizzoDestinazione(busta.getIndirizzoMittente());
  1352.                 }
  1353.                
  1354.                 busta.addTrasmissione(trasmissione);
  1355.                
  1356.             }      
  1357.            
  1358.             Object oSecondaTrasmissioneOraRegistrazione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_SECONDA_TRASMISSIONE_ORA_REGISTRAZIONE).getDato();
  1359.             Object oSecondaTrasmissioneTipoOraRegistrazione = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_SECONDA_TRASMISSIONE_TIPO_ORA_REGISTRAZIONE).getDato();
  1360.             Object oSecondaTrasmissioneTipoOraRegistrazioneCode = infoSalvataggioTraccia.getDato(MappingRicostruzioneTraccia.TRACCIA_BUSTA_SECONDA_TRASMISSIONE_TIPO_ORA_REGISTRAZIONE_CODE).getDato();
  1361.    
  1362.             if(oSecondaTrasmissioneOraRegistrazione != null && oSecondaTrasmissioneTipoOraRegistrazione != null && oSecondaTrasmissioneTipoOraRegistrazioneCode != null) {
  1363.                
  1364.                 Trasmissione trasmissione = new Trasmissione();
  1365.                 trasmissione.setOraRegistrazione((Date)oSecondaTrasmissioneOraRegistrazione);
  1366.                
  1367.                 char value = ((Character)oSecondaTrasmissioneTipoOraRegistrazioneCode);
  1368.                 if(CostantiMappingTracciamento.TRACCIA_BUSTA_SECONDA_TRASMISSIONE_TIPO_ORA_REGISTRAZIONE_CODE_LOCALE == value) {
  1369.                     trasmissione.setTempo(TipoOraRegistrazione.LOCALE);
  1370.                 } else if(CostantiMappingTracciamento.TRACCIA_BUSTA_SECONDA_TRASMISSIONE_TIPO_ORA_REGISTRAZIONE_CODE_SINCRONIZZATO == value) {
  1371.                     trasmissione.setTempo(TipoOraRegistrazione.SINCRONIZZATO);
  1372.                 } else {
  1373.                     trasmissione.setTempo(TipoOraRegistrazione.UNKNOWN);
  1374.                 }
  1375.                
  1376.                 trasmissione.setTempoValue((String)oSecondaTrasmissioneTipoOraRegistrazione);
  1377.                
  1378.                 trasmissione.setOrigine(destinatario.getNome());
  1379.                 trasmissione.setTipoOrigine(destinatario.getTipo());
  1380.                 trasmissione.setIdentificativoPortaOrigine(destinatario.getCodicePorta());
  1381.                 trasmissione.setIndirizzoOrigine(busta.getIndirizzoDestinatario());
  1382.                
  1383.                 trasmissione.setDestinazione(mittente.getNome());
  1384.                 trasmissione.setTipoDestinazione(mittente.getTipo());
  1385.                 trasmissione.setIdentificativoPortaDestinazione(mittente.getCodicePorta());
  1386.                 trasmissione.setIndirizzoDestinazione(busta.getIndirizzoMittente());
  1387.                
  1388.                 busta.addTrasmissione(trasmissione);
  1389.                
  1390.             }      
  1391.         }
  1392.        
  1393.        
  1394.         return busta;
  1395.        
  1396.     }
  1397.    
  1398.    
  1399.     private InformazioniRecordTraccia getInformazioniSalvataggioTraccia(
  1400.             JDBCServiceManager transazioniServiceManager,
  1401.             String idTransazione, RuoloMessaggio tipoTraccia,
  1402.             CredenzialiMittente credentialsFiller,
  1403.             Date minDate,
  1404.             Date maxDate) throws DriverTracciamentoException{

  1405.         try{
  1406.            
  1407.             ITransazioneServiceSearch transazioneServiceSearch = transazioniServiceManager.getTransazioneServiceSearch();
  1408.            
  1409.             IPaginatedExpression pagExpr = transazioneServiceSearch.newPaginatedExpression();
  1410.             if(maxDate!=null){
  1411.                 pagExpr.lessEquals(Transazione.model().DATA_INGRESSO_RICHIESTA, maxDate); // ottimizzazione partizioni
  1412.             }
  1413.             if(minDate!=null){
  1414.                 pagExpr.greaterEquals(Transazione.model().DATA_INGRESSO_RICHIESTA, minDate); // ottimizzazione partizioni
  1415.             }
  1416.             pagExpr.equals(Transazione.model().ID_TRANSAZIONE,idTransazione);
  1417.            
  1418.             List<Map<String,Object>> selectField = null;
  1419.             if(RuoloMessaggio.RICHIESTA.equals(tipoTraccia)){
  1420.                 selectField = transazioneServiceSearch.select(pagExpr, Transazione.model().TRACCIA_RICHIESTA,
  1421.                         Transazione.model().TOKEN_CLIENT_ID);
  1422.             }else{
  1423.                 selectField = transazioneServiceSearch.select(pagExpr, Transazione.model().TRACCIA_RISPOSTA,
  1424.                         Transazione.model().TOKEN_CLIENT_ID);
  1425.             }
  1426.            
  1427.             if(selectField==null || selectField.isEmpty()){
  1428.                 throw new DriverTracciamentoException("Recupero informazioni per ricostruire la traccia [isRichiesta:"+
  1429.                         tipoTraccia+"] non riuscito. Transazione con ID["+
  1430.                         idTransazione+"] non presente?");
  1431.             }
  1432.             if(selectField.size()>1){
  1433.                 throw new DriverTracciamentoException("Recupero informazioni per ricostruire la traccia [isRichiesta:"+
  1434.                         tipoTraccia+"] non riuscito. Trovata piu' di una Transazione con ID["+
  1435.                         idTransazione+"]?");
  1436.             }
  1437.            
  1438.             Map<String,Object> dbValue = selectField.get(0);
  1439.            
  1440.             String dbValueTraccia =null;
  1441.             if(RuoloMessaggio.RICHIESTA.equals(tipoTraccia)){
  1442.                 dbValueTraccia = this.readValue(dbValue, Transazione.model().TRACCIA_RICHIESTA, idTransazione);
  1443.             }
  1444.             else {
  1445.                 dbValueTraccia = this.readValue(dbValue, Transazione.model().TRACCIA_RISPOSTA, idTransazione);
  1446.             }
  1447.             if(dbValueTraccia==null){
  1448.                 return null;
  1449.             }
  1450.            
  1451.             InformazioniRecordTraccia info = InformazioniRecordTraccia.convertoFromDBColumnValue(dbValueTraccia);
  1452.             this.logDebug("RECUPERO ["+info.toString()+"]");
  1453.            
  1454.            
  1455.             if(credentialsFiller!=null) {
  1456.                 String dbValueTokenClientId = this.readValue(dbValue, Transazione.model().TOKEN_CLIENT_ID, idTransazione);
  1457.                 if(dbValueTokenClientId!=null && StringUtils.isNotEmpty(dbValueTokenClientId)) {
  1458.                     CredenzialeMittente credenzialeClientId = getCredenzialeMittente(transazioniServiceManager, dbValueTokenClientId, idTransazione);
  1459.                     credentialsFiller.setTokenClientId(credenzialeClientId);
  1460.                 }
  1461.             }
  1462.            
  1463.            
  1464.             return info;
  1465.                
  1466.         }catch(Exception e){
  1467.             throw new DriverTracciamentoException("Riscontrato errore durante la lettura dei dati (Transazione:"+idTransazione+"): "+e.getMessage(),e);
  1468.         }
  1469.     }
  1470.    
  1471.     private CredenzialeMittente getCredenzialeMittente(JDBCServiceManager transazioniServiceManager, String dbValueTokenClientId, String idTransazione) throws ServiceException, NotImplementedException, MultipleResultException{
  1472.         CredenzialeMittente credenzialeClientId = null;
  1473.         long id = -1;
  1474.         try {
  1475.             IDBCredenzialeMittenteServiceSearch credenzialeMittenteServiceSearch = (IDBCredenzialeMittenteServiceSearch) transazioniServiceManager.getCredenzialeMittenteServiceSearch();
  1476.             id = Long.parseLong(dbValueTokenClientId);
  1477.             credenzialeClientId = credenzialeMittenteServiceSearch.get(id);
  1478.             this.logDebug("RECUPERATO CLIENT ID ["+credenzialeClientId+"] per id ["+idTransazione+"]");
  1479.         }catch(NotFoundException notFound) {
  1480.             credenzialeClientId = new CredenzialeMittente();
  1481.             credenzialeClientId.setId(id);
  1482.             credenzialeClientId.setCredenziale("Informazione non disponibile");
  1483.         }
  1484.         return credenzialeClientId;
  1485.     }
  1486.    
  1487.     private String readValue(Map<String,Object> dbValue, IField field, String idTransazione) throws DriverTracciamentoException{
  1488.         Object objectDBValue = dbValue.get(field.getFieldName());
  1489.         String dbValueAsString = null;
  1490.         if((objectDBValue instanceof org.apache.commons.lang.ObjectUtils.Null)){
  1491.             objectDBValue = null;
  1492.         }
  1493.         if(objectDBValue!=null){
  1494.             if( ! (objectDBValue instanceof String)){
  1495.                 throw new DriverTracciamentoException("Recupero informazioni per ricostruire la traccia non riuscito. Trovato campo '"+field.getFieldName()
  1496.                 +"' di tipo ["+objectDBValue.getClass().getName()
  1497.                 +"] differente da quello atteso ["+String.class.getName()+"] per la Transazione con ID["+
  1498.                 idTransazione+"]?");
  1499.             }
  1500.             else{
  1501.                 dbValueAsString = (String) objectDBValue;
  1502.             }
  1503.         }
  1504.         return dbValueAsString;
  1505.     }

  1506. }