DiagnosticDriver.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.protocol.basic.diagnostica;

  21. import java.sql.Connection;
  22. import java.sql.DriverManager;
  23. import java.sql.PreparedStatement;
  24. import java.sql.ResultSet;
  25. import java.sql.SQLException;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import java.util.Properties;

  29. import javax.sql.DataSource;

  30. import org.openspcoop2.protocol.basic.BasicComponentFactory;
  31. import org.openspcoop2.protocol.basic.Costanti;
  32. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  33. import org.openspcoop2.protocol.sdk.ProtocolException;
  34. import org.openspcoop2.protocol.sdk.diagnostica.DriverMsgDiagnosticiException;
  35. import org.openspcoop2.protocol.sdk.diagnostica.DriverMsgDiagnosticiNotFoundException;
  36. import org.openspcoop2.protocol.sdk.diagnostica.FiltroRicercaDiagnostici;
  37. import org.openspcoop2.protocol.sdk.diagnostica.FiltroRicercaDiagnosticiConPaginazione;
  38. import org.openspcoop2.protocol.sdk.diagnostica.IDiagnosticDriver;
  39. import org.openspcoop2.protocol.sdk.diagnostica.MsgDiagnostico;
  40. import org.openspcoop2.protocol.sdk.tracciamento.DriverTracciamentoException;
  41. import org.openspcoop2.utils.LoggerWrapperFactory;
  42. import org.openspcoop2.utils.StringWrapper;
  43. import org.openspcoop2.utils.TipiDatabase;
  44. import org.openspcoop2.utils.jdbc.JDBCUtilities;
  45. import org.openspcoop2.utils.resources.GestoreJNDI;
  46. import org.openspcoop2.utils.sql.ISQLQueryObject;
  47. import org.slf4j.Logger;

  48. /**
  49.  * Interfaccia di ricerca dei messaggi diagnostici
  50.  *
  51.  * @author Stefano Corallo (corallo@link.it)
  52.  * @author $Author$
  53.  * @version $Rev$, $Date$
  54.  */
  55. public class DiagnosticDriver extends BasicComponentFactory implements IDiagnosticDriver {
  56.     /**
  57.      * DataSource
  58.      */
  59.     DataSource datasource = null;
  60.     /**
  61.      * SQLQueryObject
  62.      */
  63.     String tipoDatabase = null;
  64.    
  65.     Connection con = null;
  66.     boolean connectionOpenViaJDBCInCostructor = false;
  67.        
  68.     public DiagnosticDriver(IProtocolFactory<?> factory) throws ProtocolException{
  69.         super(factory);
  70.     }
  71.    
  72.     private static final String QUERY_PREFIX = "Query : ";
  73.     private static final String ROWS_SUFFIX = " rows";

  74.    
  75.     public static final String IDDIAGNOSTICI = "@@@@@-----@@@@-----IDDIAGNOSTICI-DB----@@@@@-----@@@@";
  76.    
  77.    
  78.     /**
  79.      * Properties per campi aggiuntivi
  80.      */
  81.     private List<String> propertiesMsgDiagnostici;
  82.     public void setPropertiesMsgDiagnostici(List<String> properties) {
  83.         this.propertiesMsgDiagnostici = properties;
  84.     }  
  85.    
  86.    
  87.    
  88.    
  89.     public void init(String nomeDataSource, String tipoDatabase, Properties jndiProperties) throws DriverMsgDiagnosticiException {
  90.         init(nomeDataSource,tipoDatabase,jndiProperties,null);
  91.     }
  92.    
  93.     public void init(String nomeDataSource, String tipoDatabase, Properties jndiProperties, Logger log) throws DriverMsgDiagnosticiException {
  94.         // Logger
  95.         try {
  96.             if(log==null)
  97.                 this.log = LoggerWrapperFactory.getLogger(Costanti.LOGANALIZER_DRIVER_DB_LOGGER);
  98.             else
  99.                 this.log = log;
  100.         } catch (Exception e) {
  101.             throw new DriverMsgDiagnosticiException("Errore durante l'inizializzazione del logger (datasource params): "+e.getMessage(),e);
  102.         }

  103.         // Datasource
  104.         try {
  105.             this.log.info("Inizializzo DriverLogAnalyzer...");
  106.             GestoreJNDI gestoreJNDI = new GestoreJNDI(jndiProperties);
  107.             this.datasource = (DataSource) gestoreJNDI.lookup(nomeDataSource);
  108.             if (this.datasource == null)
  109.                 throw new DriverMsgDiagnosticiException ("datasource is null");

  110.             this.log.info("Inizializzo DriverLogAnalyzer terminata.");
  111.         } catch (Exception e) {
  112.             this.logError("Errore durante la ricerca del datasource (datasource params): "+e.getMessage(),e);
  113.             throw new DriverMsgDiagnosticiException("Errore durante la ricerca del datasource (datasource params): "+e.getMessage(),e);
  114.         }

  115.         // ISQLQueryObject
  116.         try {
  117.             this.log.info("Inizializzo ISQLQueryObject (datasource params)");
  118.             if (TipiDatabase.isAMember(tipoDatabase)) {
  119.                 this.tipoDatabase = tipoDatabase;              
  120.             } else {
  121.                 throw new DriverMsgDiagnosticiException("Tipo database non gestito (datasource params)");
  122.             }
  123.             this.log.info("Inizializzo ISQLQueryObject terminata (datasource params)");

  124.         } catch (Exception e) {
  125.             this.logError("Errore durante la ricerca del SQLQueryObject (datasource params): "+e.getMessage(),e);
  126.             throw new DriverMsgDiagnosticiException("Errore durante la ricerca del SQLQueryObject (datasource params): "+e.getMessage(),e);
  127.         }
  128.     }
  129.    
  130.     public void init(DataSource dataSourceObject, String tipoDatabase) throws DriverMsgDiagnosticiException {
  131.         init(dataSourceObject,tipoDatabase,null);
  132.     }
  133.        
  134.     public void init(DataSource dataSourceObject, String tipoDatabase, Logger log) throws DriverMsgDiagnosticiException {
  135.         // Logger
  136.         try {
  137.             if(log==null)
  138.                 this.log = LoggerWrapperFactory.getLogger(Costanti.LOGANALIZER_DRIVER_DB_LOGGER);
  139.             else
  140.                 this.log = log;
  141.         } catch (Exception e) {
  142.             throw new DriverMsgDiagnosticiException("Errore durante l'inizializzazione del logger (datasource): "+e.getMessage(),e);
  143.         }

  144.         // Datasource
  145.         try {
  146.             this.datasource = dataSourceObject;
  147.             if (this.datasource == null)
  148.                 throw new DriverMsgDiagnosticiException ("datasource is null");
  149.         } catch (Exception e) {
  150.             this.logError("Errore durante l'assegnamento del datasource (datasource): "+e.getMessage(),e);
  151.             throw new DriverMsgDiagnosticiException("Errore durante l'assegnamento del datasource (datasource): "+e.getMessage(),e);
  152.         }

  153.         // ISQLQueryObject
  154.         try {
  155.             this.log.info("Inizializzo ISQLQueryObject (datasource)");
  156.             if (TipiDatabase.isAMember(tipoDatabase)) {
  157.                 this.tipoDatabase = tipoDatabase;              
  158.             } else {
  159.                 throw new DriverMsgDiagnosticiException("Tipo database non gestito (datasource)");
  160.             }
  161.             this.log.info("Inizializzo ISQLQueryObject terminata (datasource)");

  162.         } catch (Exception e) {
  163.             this.logError("Errore durante la ricerca del SQLQueryObject (datasource): "+e.getMessage(),e);
  164.             throw new DriverMsgDiagnosticiException("Errore durante la ricerca del SQLQueryObject (datasource): "+e.getMessage(),e);
  165.         }
  166.     }
  167.    
  168.     public void init(Connection connection, String tipoDatabase, Logger log) throws DriverMsgDiagnosticiException {
  169.         // Logger
  170.         try {
  171.             this.log = log;
  172.         } catch (Exception e) {
  173.             throw new DriverMsgDiagnosticiException("Errore durante l'inizializzazione del logger (connection): "+e.getMessage(),e);
  174.         }

  175.         // connection
  176.         this.con = connection;
  177.        
  178.         // ISQLQueryObject
  179.         try {
  180.             this.log.info("Inizializzo ISQLQueryObject (connection)");
  181.             if (TipiDatabase.isAMember(tipoDatabase)) {
  182.                 this.tipoDatabase = tipoDatabase;              
  183.             } else {
  184.                 throw new DriverMsgDiagnosticiException("Tipo database non gestito (connection)");
  185.             }
  186.             this.log.info("Inizializzo ISQLQueryObject terminata (connection)");

  187.         } catch (Exception e) {
  188.             this.logError("Errore durante la ricerca del SQLQueryObject (connection): "+e.getMessage(),e);
  189.             throw new DriverMsgDiagnosticiException("Errore durante la ricerca del SQLQueryObject (connection): "+e.getMessage(),e);
  190.         }
  191.     }
  192.    
  193.     public void init(String urlJDBC,String driverJDBC,
  194.             String username,String password, String tipoDatabase, Logger log) throws DriverMsgDiagnosticiException {
  195.         // Logger
  196.         try {
  197.             this.log = log;
  198.         } catch (Exception e) {
  199.             throw new DriverMsgDiagnosticiException("Errore durante l'inizializzazione del logger (connectionUrl params): "+e.getMessage(),e);
  200.         }

  201.         // connection
  202.         try {
  203.             Class.forName(driverJDBC);
  204.            
  205.             if(username!=null){
  206.                 this.con = DriverManager.getConnection(urlJDBC,username,password);
  207.             }else{
  208.                 this.con = DriverManager.getConnection(urlJDBC);
  209.             }
  210.             this.connectionOpenViaJDBCInCostructor = true;
  211.            
  212.         } catch (Exception e) {
  213.             this.logError("Errore durante l'inizializzazione della connessione (connectionUrl params): "+e.getMessage(),e);
  214.             throw new DriverMsgDiagnosticiException("Errore durante l'inizializzazione della connessione (connectionUrl params): "+e.getMessage(),e);
  215.         }
  216.                
  217.         // ISQLQueryObject
  218.         try {
  219.             this.log.info("Inizializzo ISQLQueryObject (connectionUrl params)");
  220.             if (TipiDatabase.isAMember(tipoDatabase)) {
  221.                 this.tipoDatabase = tipoDatabase;              
  222.             } else {
  223.                 throw new DriverMsgDiagnosticiException("Tipo database non gestito (connectionUrl params)");
  224.             }
  225.             this.log.info("Inizializzo ISQLQueryObject terminata (connectionUrl params)");

  226.         } catch (Exception e) {
  227.             this.logError("Errore durante la ricerca del SQLQueryObject (connectionUrl params): "+e.getMessage(),e);
  228.             throw new DriverMsgDiagnosticiException("Errore durante la ricerca del SQLQueryObject (connectionUrl params): "+e.getMessage(),e);
  229.         }
  230.     }

  231.    
  232.    
  233.    
  234.    
  235.    
  236.    
  237.    
  238.    
  239.     /* *********** ACCESSI TRAMITE RICERCHE (DIAGNOSTICI) ******* */
  240.    
  241.     /**
  242.      * Si occupa di ritornare il numero di diagnostici che rispettano il filtro di ricerca
  243.      *
  244.      * @param filtro Filtro di ricerca
  245.      * @return numero di diagnostici che rispettano il filtro di ricerca
  246.      *
  247.      */
  248.     @Override
  249.     public int countMessaggiDiagnostici(FiltroRicercaDiagnostici filtro) throws DriverMsgDiagnosticiException{
  250.         PreparedStatement stmt = null;
  251.         ResultSet rs=null;
  252.         Connection connectionDB = null;
  253.         boolean closeConnection = true;
  254.         ISQLQueryObject sqlObj =  null;
  255.         int countDiagnostici = 0;
  256.         try{
  257.             if(this.con!=null){
  258.                 connectionDB=this.con;
  259.                 closeConnection=false;
  260.             }else{
  261.                 connectionDB = this.datasource.getConnection();
  262.             }
  263.             checkConnection(connectionDB);

  264.             sqlObj = DiagnosticDriverUtilities.createSQLQueryObj_countMessaggiDiagnostici(filtro, this.tipoDatabase);
  265.            
  266.             StringWrapper sqlDebug = new StringWrapper(sqlObj.createSQLQuery());
  267.             DiagnosticDriverUtilities.setValues_countMessaggiDiagnostici(filtro, sqlDebug, 1);
  268.             this.logDebug(QUERY_PREFIX+sqlDebug);
  269.            
  270.             String sql = sqlObj.createSQLQuery();
  271.             stmt=connectionDB.prepareStatement(sql);
  272.             DiagnosticDriverUtilities.setValues_countMessaggiDiagnostici(filtro, stmt, 1);

  273.             rs=stmt.executeQuery();
  274.             if(rs.next()){
  275.                
  276.                 countDiagnostici = rs.getInt("countMsgDiagnostici");
  277.                
  278.             }
  279.            
  280.             this.logDebug("Query found "+countDiagnostici+ROWS_SUFFIX);
  281.            
  282.             return countDiagnostici;
  283.            
  284.         }catch (DriverMsgDiagnosticiException e) {
  285.             throw e;
  286.         }catch (Exception e) {
  287.             throw new DriverMsgDiagnosticiException(e);
  288.         }finally{
  289.             JDBCUtilities.closeResources(rs, stmt);
  290.             if(closeConnection){
  291.                 try{
  292.                     JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), connectionDB, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  293.                 }catch (Exception e) {
  294.                     // ignore
  295.                 }
  296.             }
  297.         }
  298.     }
  299.    
  300.     /**
  301.      * Si occupa di ritornare i diagnostici che rispettano il filtro di ricerca
  302.      *
  303.      * @param filtro Filtro di ricerca
  304.      * @return diagnostici che rispettano il filtro di ricerca
  305.      *
  306.      */
  307.     @Override
  308.     public List<MsgDiagnostico> getMessaggiDiagnostici(FiltroRicercaDiagnosticiConPaginazione filtro)  
  309.         throws DriverMsgDiagnosticiException, DriverMsgDiagnosticiNotFoundException{
  310.         PreparedStatement stmt = null;
  311.         ResultSet rs=null;
  312.         Connection connectionDB = null;
  313.         boolean closeConnection = true;
  314.         ISQLQueryObject sqlObj =  null;
  315.         try{
  316.             ArrayList<MsgDiagnostico> listaMSGDiagnostici = new ArrayList<>();
  317.             if(this.con!=null){
  318.                 connectionDB=this.con;
  319.                 closeConnection=false;
  320.             }else{
  321.                 connectionDB = this.datasource.getConnection();
  322.             }
  323.             checkConnection(connectionDB);
  324.            
  325.             sqlObj = DiagnosticDriverUtilities.createSQLQueryObj_searchMessaggiDiagnostici(filtro, this.tipoDatabase);
  326.            
  327.             StringWrapper sqlDebug = new StringWrapper(sqlObj.createSQLQuery());
  328.             DiagnosticDriverUtilities.setValues_searchMessaggiDiagnostici(filtro, sqlDebug, 1);
  329.             this.logDebug(QUERY_PREFIX+sqlDebug);
  330.            
  331.             String sql = sqlObj.createSQLQuery();
  332.             stmt=connectionDB.prepareStatement(sql);
  333.             DiagnosticDriverUtilities.setValues_searchMessaggiDiagnostici(filtro, stmt, 1);

  334.             rs=stmt.executeQuery();
  335.             while(rs.next()){
  336.                
  337.                 long idMsgDiagnostico = rs.getLong("idMsgDiagnostico");
  338.                 MsgDiagnostico msgDiag =
  339.                     DiagnosticDriverUtilities.getMsgDiagnostico(connectionDB, this.tipoDatabase,
  340.                             this.log, idMsgDiagnostico, this.propertiesMsgDiagnostici);
  341.                 listaMSGDiagnostici.add(msgDiag);
  342.             }
  343.             rs.close();
  344.             stmt.close();
  345.            
  346.             this.logDebug("Query found "+listaMSGDiagnostici.size()+ROWS_SUFFIX);
  347.            
  348.             if(!listaMSGDiagnostici.isEmpty())
  349.                 return listaMSGDiagnostici;
  350.             else
  351.                 throw new DriverMsgDiagnosticiNotFoundException("Non sono stati trovati diagnostici che rispettano il filtro impostato");
  352.            
  353.         }catch (DriverMsgDiagnosticiNotFoundException | DriverMsgDiagnosticiException e) {
  354.             throw e;
  355.         }catch (Exception e) {
  356.             throw new DriverMsgDiagnosticiException(e);
  357.         }finally{
  358.             JDBCUtilities.closeResources(rs, stmt);
  359.             if(closeConnection){
  360.                 try{
  361.                     JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), connectionDB, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  362.                 }catch (Exception e) {
  363.                     // ignore
  364.                 }
  365.             }
  366.         }
  367.     }
  368.    
  369.    
  370.     /**
  371.      * Si occupa di eliminare i diagnostici che rispettano il filtro di ricerca
  372.      *
  373.      * @param filter Filtro di ricerca
  374.      * @return numero di diagnostici eliminati
  375.      * @throws DriverTracciamentoException
  376.      */
  377.     @Override
  378.     public int deleteMessaggiDiagnostici(FiltroRicercaDiagnostici filter) throws DriverMsgDiagnosticiException{
  379.         PreparedStatement stmt = null;
  380.         int deleted = 0;
  381.         Connection connectionDB = null;
  382.         boolean closeConnection = true;
  383.         ISQLQueryObject sqlObj =  null;
  384.         try{
  385.             if(this.con!=null){
  386.                 connectionDB=this.con;
  387.                 closeConnection=false;
  388.             }else{
  389.                 connectionDB = this.datasource.getConnection();
  390.             }
  391.             checkConnection(connectionDB);
  392.            
  393.             sqlObj = DiagnosticDriverUtilities.createSQLQueryObj_deleteMessaggiDiagnostici(filter, this.tipoDatabase);
  394.            
  395.             StringWrapper sqlDebug = new StringWrapper(sqlObj.createSQLDelete());
  396.             DiagnosticDriverUtilities.setValues_deleteMessaggiDiagnostici(filter, sqlDebug, 1);
  397.             this.logDebug(QUERY_PREFIX+sqlDebug);
  398.            
  399.             String sql = sqlObj.createSQLDelete();
  400.             stmt=connectionDB.prepareStatement(sql);
  401.             DiagnosticDriverUtilities.setValues_deleteMessaggiDiagnostici(filter, stmt, 1);
  402.            
  403.             deleted = stmt.executeUpdate();    
  404.            
  405.             stmt.close();
  406.            
  407.             this.logDebug("Deleted "+deleted+ROWS_SUFFIX);
  408.            
  409.             return deleted;
  410.            
  411.         }catch (DriverMsgDiagnosticiException e) {
  412.             throw e;
  413.         }catch (Exception e) {
  414.             throw new DriverMsgDiagnosticiException(e);
  415.         }finally{
  416.             JDBCUtilities.closeResources(stmt);
  417.             if(closeConnection){
  418.                 try{
  419.                     JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), connectionDB, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  420.                 }catch (Exception e) {
  421.                     // ignore
  422.                 }
  423.             }
  424.         }
  425.     }
  426.    
  427.    
  428.    
  429.    
  430.    
  431.    
  432.    
  433.    
  434.    
  435.    
  436.    
  437.    
  438.    
  439.     /* ******* RISORSE INTERNE ********** */
  440.    
  441.     @Override
  442.     public void close() throws DriverMsgDiagnosticiException {
  443.         try{
  444.             if(this.connectionOpenViaJDBCInCostructor &&
  445.                 this.con!=null && !this.con.isClosed()){
  446.                 JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), this.con, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  447.             }
  448.         }catch(Exception e){
  449.             throw new DriverMsgDiagnosticiException(e.getMessage(),e);
  450.         }
  451.     }  
  452.    
  453.    
  454.    
  455.    
  456.    
  457.    
  458.    
  459.    
  460.    
  461.    
  462.    

  463.    
  464.    
  465.    
  466.     /* ------------- UTILITY INTERNE -------------------------- */

  467.     private void checkConnection(Connection con) throws DriverMsgDiagnosticiException {
  468.         if(con==null &&
  469.             this.con==null) {
  470.             throw new DriverMsgDiagnosticiException("Connection non ottenuta dal datasource["+this.datasource+"]");
  471.         }
  472.     }
  473.    
  474.     /**
  475.      * Viene chiamato in causa per ottenere una connessione al DB
  476.      */
  477.     public java.sql.Connection getConnection() {
  478.         if (this.datasource == null) {
  479.             return null;
  480.         }

  481.         Connection connectionDB = null;
  482.         try {
  483.             connectionDB = this.datasource.getConnection();
  484.         } catch (Exception e) {
  485.             return null;
  486.         }

  487.         return connectionDB;
  488.     }

  489.     /**
  490.      * Viene chiamato in causa per rilasciare una connessione al DB, effettuando
  491.      * precedentemente un commit
  492.      *
  493.      * @param connectionDB
  494.      *            Connessione da rilasciare.
  495.      */
  496.     public void releaseConnection(java.sql.Connection connectionDB) {
  497.         try {
  498.             JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), connectionDB, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  499.         } catch (SQLException e) {
  500.             // ignore
  501.         }
  502.     }

  503.     /**
  504.      * Viene chiamato in causa per ottenere il tipoDatabase
  505.      */
  506.     public String getTipoDatabase() {
  507.         return this.tipoDatabase;
  508.     }

  509. }