DriverMonitoraggio.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.monitor.driver;

  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.sql.Timestamp;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. import java.util.Properties;

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

  32. import org.openspcoop2.pdd.core.GestoreMessaggi;
  33. import org.openspcoop2.pdd.mdb.ConsegnaContenutiApplicativi;
  34. import org.openspcoop2.pdd.mdb.InoltroBuste;
  35. import org.openspcoop2.pdd.mdb.InoltroRisposte;
  36. import org.openspcoop2.pdd.monitor.Busta;
  37. import org.openspcoop2.pdd.monitor.BustaServizio;
  38. import org.openspcoop2.pdd.monitor.BustaSoggetto;
  39. import org.openspcoop2.pdd.monitor.Dettaglio;
  40. import org.openspcoop2.pdd.monitor.Messaggio;
  41. import org.openspcoop2.pdd.monitor.Proprieta;
  42. import org.openspcoop2.pdd.monitor.ServizioApplicativoConsegna;
  43. import org.openspcoop2.pdd.monitor.StatoPdd;
  44. import org.openspcoop2.pdd.monitor.constants.CostantiMonitoraggio;
  45. import org.openspcoop2.pdd.monitor.constants.StatoMessaggio;
  46. import org.openspcoop2.pdd.timers.TimerConsegnaContenutiApplicativiThread;
  47. import org.openspcoop2.pdd.timers.TimerGestoreMessaggi;
  48. import org.openspcoop2.protocol.basic.BasicComponentFactory;
  49. import org.openspcoop2.protocol.engine.constants.Costanti;
  50. import org.openspcoop2.utils.LoggerWrapperFactory;
  51. import org.openspcoop2.utils.TipiDatabase;
  52. import org.openspcoop2.utils.date.DateManager;
  53. import org.openspcoop2.utils.jdbc.JDBCUtilities;
  54. import org.openspcoop2.utils.resources.ClassLoaderUtilities;
  55. import org.openspcoop2.utils.sql.ISQLQueryObject;
  56. import org.openspcoop2.utils.sql.SQLObjectFactory;
  57. import org.openspcoop2.utils.sql.SQLQueryObjectException;
  58. import org.slf4j.Logger;

  59. /**
  60.  * Driver per il Monitoraggio di GovWay
  61.  *
  62.  * @author Poli Andrea (apoli@link.it)
  63.  * @author $Author$
  64.  * @version $Rev$, $Date$
  65.  */

  66. public class DriverMonitoraggio implements IDriverMonitoraggio{

  67.     /**
  68.      * DataSource
  69.      */
  70.     private DataSource datasource = null;

  71.     // Connection passata al momento della creazione dell'oggetto
  72.     private Connection globalConnection = null;
  73.     /**
  74.      * SQLQueryObject
  75.      */
  76.     private String tipoDatabase = null;


  77.     /** Logger utilizzato per info. */
  78.     private Logger log = null;
  79.     private void logError(String msg, Exception e) {
  80.         if(this.log!=null) {
  81.             this.log.error(msg, e);
  82.         }
  83.     }
  84.     private void logDebug(String msg) {
  85.         if(this.log!=null) {
  86.             this.log.debug(msg);
  87.         }
  88.     }

  89.     /**
  90.      * Properties
  91.      */
  92.     private List<String> properties;
  93.     public void setProperties(List<String> properties) {
  94.         this.properties = properties;
  95.     }

  96.     public DriverMonitoraggio(String nomeDataSource, String tipoDatabase, Properties prop) throws DriverMonitoraggioException {
  97.         this(nomeDataSource,tipoDatabase,prop,null);
  98.     }

  99.     public DriverMonitoraggio(String nomeDataSource, String tipoDatabase, Properties prop,Logger log) throws DriverMonitoraggioException {
  100.         // Logger
  101.         try {
  102.             if(log==null)
  103.                 this.log = LoggerWrapperFactory.getLogger(CostantiMonitoraggio.MONITORAGGIO_DRIVER_DB_LOGGER);
  104.             else
  105.                 this.log = log;
  106.         } catch (Exception e) {
  107.             throw new DriverMonitoraggioException("Errore durante l'inizializzazione del logger...",e);
  108.         }

  109.         // Datasource
  110.         try {
  111.             this.log.info("Inizializzo DriverMonitoraggioDB...");
  112.             InitialContext initCtx = new InitialContext(prop);
  113.             this.datasource = (DataSource) initCtx.lookup(nomeDataSource);
  114.             if (this.datasource == null)
  115.                 throw new DriverMonitoraggioException ("datasource is null");

  116.             initCtx.close();
  117.             this.log.info("Inizializzo DriverMonitoraggioDB terminata.");
  118.         } catch (Exception e) {
  119.             this.logError("Errore durante la ricerca del datasource...",e);
  120.             throw new DriverMonitoraggioException("Errore durante la ricerca del datasource...",e);
  121.         }

  122.         // ISQLQueryObject SQLObjectFactory
  123.         try {
  124.             this.log.info("Inizializzo ISQLQueryObject ...");
  125.             if (TipiDatabase.isAMember(tipoDatabase)) {
  126.                 this.tipoDatabase = tipoDatabase;              
  127.             } else {
  128.                 throw new DriverMonitoraggioException("Tipo database non gestito");
  129.             }

  130.             this.log.info("Inizializzo ISQLQueryObject terminata.");

  131.         } catch (Exception e) {
  132.             this.logError("Errore durante la ricerca del SQLQueryObject...",e);
  133.             throw new DriverMonitoraggioException("Errore durante la ricerca del SQLQueryObject("+tipoDatabase+")...",e);
  134.         }
  135.     }



  136.     public DriverMonitoraggio(String connectionUrl, String driverJDBC,
  137.             String username, String password, String tipoDatabase)
  138.                     throws DriverMonitoraggioException {
  139.         this(connectionUrl, driverJDBC, username, password, tipoDatabase, null);
  140.     }

  141.     public DriverMonitoraggio(String connectionUrl, String driverJDBC,
  142.             String username, String password, String tipoDatabase,Logger log)
  143.                     throws DriverMonitoraggioException {
  144.         // Logger
  145.         try {
  146.             if(log==null)
  147.                 this.log = LoggerWrapperFactory.getLogger(CostantiMonitoraggio.MONITORAGGIO_DRIVER_DB_LOGGER);
  148.             else
  149.                 this.log = log;
  150.         } catch (Exception e) {
  151.             throw new DriverMonitoraggioException("Errore durante l'inizializzazione del logger...",e);
  152.         }

  153.         // Connection
  154.         try{
  155.             this.log.info("Inizializzo DriverMonitoraggioDB...");
  156.             ClassLoaderUtilities.newInstance(driverJDBC);
  157.             this.globalConnection = initConnection(connectionUrl, username, password);
  158.             checkConnection(this.globalConnection);
  159.             this.log.info("Inizializzo DriverMonitoraggioDB terminata.");
  160.         } catch (Exception e) {
  161.             this.logError("Errore durante l'inizializzazione della connessione...",e);
  162.             throw new DriverMonitoraggioException("Errore durante l'inizializzazione della connessione...",e);
  163.         }

  164.         // ISQLQueryObject SQLObjectFactory
  165.         try {
  166.             this.log.info("Inizializzo ISQLQueryObject ...");
  167.             if (TipiDatabase.isAMember(tipoDatabase)) {
  168.                 this.tipoDatabase = tipoDatabase;              
  169.             } else {
  170.                 throw new DriverMonitoraggioException("Tipo database non gestito");
  171.             }

  172.             this.log.info("Inizializzo ISQLQueryObject terminata.");

  173.         } catch (Exception e) {
  174.             this.logError("Errore durante la ricerca del SQLQueryObject...",e);
  175.             throw new DriverMonitoraggioException("Errore durante la ricerca del SQLQueryObject("+tipoDatabase+")...",e);
  176.         }
  177.     }


  178.     private static Connection initConnection(String connectionUrl, String username, String password) throws SQLException {
  179.         if(username!=null){
  180.             return DriverManager.getConnection(connectionUrl,username,password);
  181.         }else{
  182.             return DriverManager.getConnection(connectionUrl);
  183.         }
  184.     }
  185.     private static void checkConnection(Connection con) throws DriverMonitoraggioException {
  186.         if(con == null){
  187.             throw new DriverMonitoraggioException("Connection is null");
  188.         }
  189.     }
  190.    
  191.     private Connection getConnection() throws SQLException {
  192.         if (this.datasource!=null)
  193.             return this.datasource.getConnection();
  194.         else
  195.             return this.globalConnection;
  196.     }
  197.     private void releaseConnection(Connection con) {
  198.         try{
  199.             if(this.datasource!=null && con!=null) {
  200.                 JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), con, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  201.             }
  202.         }catch(Exception e){
  203.             // close
  204.         }
  205.     }

  206.     /**
  207.      * Ritorna lo stato delle richieste pendenti che matchano il criterio di filtro.
  208.      *
  209.      * @param search criterio di filtro
  210.      * @return stato delle richieste pendenti
  211.      * @throws DriverMonitoraggioException
  212.      */
  213.     @Override
  214.     public StatoPdd getStatoRichiestePendenti(FilterSearch search) throws DriverMonitoraggioException{
  215.         Connection con = null;
  216.         PreparedStatement pstmt = null;
  217.         ResultSet rs = null;
  218.         ISQLQueryObject sqlQueryObject = null;
  219.         try{

  220.             // Ottengo connessione
  221.             con = getConnection();
  222.             if(con==null)
  223.                 throw new DriverMonitoraggioException("Connection non ottenuta dal datasource["+this.datasource+"]");

  224.             StatoPdd statoPdD = new StatoPdd();
  225.             java.sql.Timestamp now = DateManager.getTimestamp();
  226.             java.sql.Timestamp dataRegistrazioneLimite = null;
  227.             //  FILTRO d) Soglia (ora_registrazione piu' vecchia di NOW-search.getSoglia()) Soglia in Minuti
  228.             if(search.getSoglia()!=-1){
  229.                 dataRegistrazioneLimite = new java.sql.Timestamp(DateManager.getTimeMillis()-(search.getSoglia()*1000*60));
  230.             }


  231.             // TotaleMessaggi
  232.             long totaleMessaggi = 0;
  233.             long totaleMessaggiDuplicati = -1;
  234.             sqlQueryObject = this.newSQLQueryObjectStatoRichiestePendenti(search);
  235.             pstmt = con.prepareStatement(sqlQueryObject.createSQLQuery());
  236.             int paramIndex = 0;
  237.             if(search.getSoglia()!=-1)
  238.                 pstmt.setTimestamp(++paramIndex, dataRegistrazioneLimite);
  239.             List<BustaSoggetto> filtroSoggetti = search.getSoggettoList();
  240.             if(filtroSoggetti!=null){          
  241.                 for(int k=0; k<filtroSoggetti.size(); k++){

  242.                     // fruitore
  243.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  244.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());

  245.                     // OR

  246.                     // erogatore
  247.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  248.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());
  249.                 }
  250.             }
  251.             rs = pstmt.executeQuery();
  252.             if(rs.next()){
  253.                 totaleMessaggi = rs.getLong("totMessaggi");
  254.                 if(totaleMessaggi>0){
  255.                     statoPdD.setTotMessaggi(totaleMessaggi);
  256.                     statoPdD.setTempoMedioAttesa((now.getTime()-rs.getLong("ora_registrazione_media"))/1000);
  257.                     statoPdD.setTempoMaxAttesa((now.getTime()-rs.getLong("ora_registrazione_old"))/1000);
  258.                 }
  259.             }
  260.             rs.close();
  261.             pstmt.close();
  262.             this.logDebug("query["+sqlQueryObject+"] totaleMessaggi:"+totaleMessaggi);
  263.             this.logDebug("Soglia ["+search.getSoglia()+"] ["+dataRegistrazioneLimite+"] totaleMessaggi");

  264.             if(totaleMessaggi>0){

  265.                 // Messaggi in Consegna
  266.                 if( (search.getStato()==null) || ("".equals(search.getStato().getValue())) || (StatoMessaggio.CONSEGNA.equals(search.getStato())) ){
  267.                     sqlQueryObject = this.newSQLQueryObjectStatoRichiestePendenti(search);
  268.                     if((search.getStato()==null) || ("".equals(search.getStato().getValue()))){
  269.                         sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".PROPRIETARIO='"+ConsegnaContenutiApplicativi.ID_MODULO+"'");
  270.                     }
  271.                     pstmt = con.prepareStatement(sqlQueryObject.createSQLQuery());
  272.                     paramIndex = 0;
  273.                     if(search.getSoglia()!=-1)
  274.                         pstmt.setTimestamp(++paramIndex, dataRegistrazioneLimite);
  275.                     if(filtroSoggetti!=null){
  276.                         for(int k=0; k<filtroSoggetti.size(); k++){

  277.                             // fruitore
  278.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  279.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());

  280.                             // OR

  281.                             // erogatore
  282.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  283.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());
  284.                         }
  285.                     }
  286.                     rs = pstmt.executeQuery();
  287.                     if(rs.next()){
  288.                         long tot = rs.getLong("totMessaggi");
  289.                         if(tot>0){
  290.                             statoPdD.setNumMsgInConsegna(tot);
  291.                             statoPdD.setTempoMedioAttesaInConsegna((now.getTime()-rs.getLong("ora_registrazione_media"))/1000);
  292.                             statoPdD.setTempoMaxAttesaInConsegna((now.getTime()-rs.getLong("ora_registrazione_old"))/1000);
  293.                         }
  294.                     }
  295.                     rs.close();
  296.                     pstmt.close();
  297.                     this.logDebug("query["+sqlQueryObject+"] totaleMessaggiInConsegna:"+statoPdD.getNumMsgInConsegna());
  298.                     this.logDebug("Soglia ["+search.getSoglia()+"] ["+dataRegistrazioneLimite+"] totaleMessaggiInConsegna");
  299.                 }

  300.                 // Messaggi in Spedizione
  301.                 if( (search.getStato()==null) || ("".equals(search.getStato().getValue())) || (StatoMessaggio.SPEDIZIONE.equals(search.getStato())) ){
  302.                     sqlQueryObject = this.newSQLQueryObjectStatoRichiestePendenti(search);
  303.                     if( (search.getStato()==null) || ("".equals(search.getStato().getValue())) ){
  304.                         sqlQueryObject.addWhereCondition(false,GestoreMessaggi.MESSAGGI+".PROPRIETARIO='InoltroBuste'",
  305.                                 GestoreMessaggi.MESSAGGI+".PROPRIETARIO='InoltroRisposte'");
  306.                     }
  307.                     pstmt = con.prepareStatement(sqlQueryObject.createSQLQuery());
  308.                     paramIndex = 0;
  309.                     if(search.getSoglia()!=-1)
  310.                         pstmt.setTimestamp(++paramIndex, dataRegistrazioneLimite);
  311.                     if(filtroSoggetti!=null){
  312.                         for(int k=0; k<filtroSoggetti.size(); k++){

  313.                             // fruitore
  314.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  315.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());

  316.                             // OR

  317.                             // erogatore
  318.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  319.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());
  320.                         }
  321.                     }
  322.                     rs = pstmt.executeQuery();
  323.                     if(rs.next()){
  324.                         long tot = rs.getLong("totMessaggi");
  325.                         if(tot>0){
  326.                             statoPdD.setNumMsgInSpedizione(tot);
  327.                             statoPdD.setTempoMedioAttesaInSpedizione((now.getTime()-rs.getLong("ora_registrazione_media"))/1000);
  328.                             statoPdD.setTempoMaxAttesaInSpedizione((now.getTime()-rs.getLong("ora_registrazione_old"))/1000);
  329.                         }
  330.                     }
  331.                     rs.close();
  332.                     pstmt.close();
  333.                     this.logDebug("query["+sqlQueryObject+"] totaleMessaggiInSpedizione:"+statoPdD.getNumMsgInSpedizione());
  334.                     this.logDebug("Soglia ["+search.getSoglia()+"] ["+dataRegistrazioneLimite+"] totaleMessaggiInSpedizione");
  335.                 }

  336.                 // Messaggi ne in Spedizione, ne in Consegna (PROCESSAMENTO)
  337.                 if( (search.getStato()==null) || ("".equals(search.getStato().getValue())) || (StatoMessaggio.PROCESSAMENTO.equals(search.getStato())) ){
  338.                     sqlQueryObject = this.newSQLQueryObjectStatoRichiestePendenti(search);
  339.                     if( (search.getStato()==null) || ("".equals(search.getStato().getValue())) ){
  340.                         sqlQueryObject.addWhereCondition(true, GestoreMessaggi.MESSAGGI+".PROPRIETARIO<>'InoltroBuste'",
  341.                                 GestoreMessaggi.MESSAGGI+".PROPRIETARIO<>'InoltroRisposte'",
  342.                                 GestoreMessaggi.MESSAGGI+".PROPRIETARIO<>'"+ConsegnaContenutiApplicativi.ID_MODULO+"'");
  343.                     }
  344.                     pstmt = con.prepareStatement(sqlQueryObject.createSQLQuery());
  345.                     paramIndex = 0;
  346.                     if(search.getSoglia()!=-1)
  347.                         pstmt.setTimestamp(++paramIndex, dataRegistrazioneLimite);
  348.                     if(filtroSoggetti!=null){
  349.                         for(int k=0; k<filtroSoggetti.size(); k++){

  350.                             // fruitore
  351.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  352.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());

  353.                             // OR

  354.                             // erogatore
  355.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  356.                             pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());
  357.                         }
  358.                     }
  359.                     rs = pstmt.executeQuery();
  360.                     if(rs.next()){
  361.                         long tot = rs.getLong("totMessaggi");
  362.                         if(tot>0){
  363.                             statoPdD.setNumMsgInProcessamento(tot);
  364.                             statoPdD.setTempoMedioAttesaInProcessamento((now.getTime()-rs.getLong("ora_registrazione_media"))/1000);
  365.                             statoPdD.setTempoMaxAttesaInProcessamento((now.getTime()-rs.getLong("ora_registrazione_old"))/1000);
  366.                         }
  367.                     }
  368.                     rs.close();
  369.                     pstmt.close();
  370.                     this.logDebug("query["+sqlQueryObject+"] totaleMessaggiInProcessamento:"+statoPdD.getNumMsgInProcessamento());
  371.                     this.logDebug("Soglia ["+search.getSoglia()+"] ["+dataRegistrazioneLimite+"] totaleMessaggiInProcessamento");
  372.                 }

  373.             }

  374.             // MessaggiDuplicati
  375.             this.logDebug("Calcolo numero pacchetti duplicati...");
  376.             sqlQueryObject = this.newSQLQueryPacchettiDuplicati(search);
  377.             pstmt = con.prepareStatement(sqlQueryObject.createSQLQuery());
  378.             if(search.getSoglia()!=-1)
  379.                 pstmt.setTimestamp(1, dataRegistrazioneLimite);
  380.             rs = pstmt.executeQuery();
  381.             if(rs.next()){
  382.                 totaleMessaggiDuplicati = rs.getLong("numduplicati");
  383.                 statoPdD.setTotMessaggiDuplicati(totaleMessaggiDuplicati);
  384.             }
  385.             rs.close();
  386.             pstmt.close();
  387.             this.logDebug("query["+sqlQueryObject.toString()+"] totaleMessaggiDuplicati:"+totaleMessaggiDuplicati);
  388.             this.logDebug("Soglia ["+search.getSoglia()+"] ["+dataRegistrazioneLimite+"] totaleMessaggiDuplicati");


  389.             return statoPdD;

  390.         }catch(Exception e){
  391.             if(sqlQueryObject!=null){
  392.                 this.logError("getStatoRichiestePendenti error SQL["+sqlQueryObject.toString()+"]",e);
  393.                 throw new DriverMonitoraggioException("getStatoRichiestePendenti error SQL["+sqlQueryObject.toString()+"]: "+e.getMessage(),e);
  394.             }else{
  395.                 this.logError("getStatoRichiestePendenti error",e);
  396.                 throw new DriverMonitoraggioException("getStatoRichiestePendenti error: "+e.getMessage(),e);
  397.             }

  398.         }finally{
  399.             JDBCUtilities.closeResources(rs, pstmt);
  400.             releaseConnection(con);
  401.         }
  402.     }

  403.     /**
  404.      * Ritorna semplicemente il numero di messaggi in gestione
  405.      *
  406.      * @return il numero di messaggi in gestione
  407.      * @throws DriverMonitoraggioException
  408.      */
  409.     public long getTotaleMessaggiInGestione() throws DriverMonitoraggioException{
  410.         Connection con = null;
  411.         PreparedStatement pstmt = null;
  412.         ResultSet rs = null;
  413.         try{

  414.             // Ottengo connessione
  415.             con = getConnection();
  416.             if(con==null)
  417.                 throw new DriverMonitoraggioException("Connection non ottenuta dal datasource["+this.datasource+"]");

  418.             // TotaleMessaggi
  419.             long totaleMessaggi = 0;
  420.             String query = "SELECT count(*) as totMessaggi FROM "+GestoreMessaggi.MESSAGGI+" WHERE "+GestoreMessaggi.MESSAGGI+".PROPRIETARIO<>'"+TimerGestoreMessaggi.ID_MODULO+"'";
  421.             pstmt = con.prepareStatement(query);
  422.             rs = pstmt.executeQuery();
  423.             if(rs.next()){
  424.                 totaleMessaggi = rs.getLong("totMessaggi");
  425.             }
  426.             rs.close();
  427.             pstmt.close();
  428.             this.logDebug("query["+query+"] totaleMessaggi:"+totaleMessaggi);

  429.             return totaleMessaggi;

  430.         }catch(Exception e){
  431.             this.logError("getTotaleMessaggiInGestione error",e);
  432.             throw new DriverMonitoraggioException("getStatoRichiestePendenti error: "+e.getMessage(),e);
  433.         }finally{
  434.             try{
  435.                 if(rs!=null)
  436.                     rs.close();
  437.             }catch(Exception e){
  438.                 // close
  439.             }
  440.             try{
  441.                 if(pstmt!=null)
  442.                     pstmt.close();
  443.             }catch(Exception e){
  444.                 // close
  445.             }
  446.             releaseConnection(con);
  447.         }
  448.     }

  449.     /**
  450.      * Ritorna il numero delle richieste pendenti che matchano il criterio di filtro.
  451.      *
  452.      * @param search criterio di filtro
  453.      * @return numero di richieste pendenti
  454.      * @throws DriverMonitoraggioException
  455.      */
  456.     @Override
  457.     public long countListaRichiestePendenti(FilterSearch search) throws DriverMonitoraggioException{
  458.         Connection con = null;
  459.         PreparedStatement pstmt = null;
  460.         ResultSet rs = null;
  461.         ISQLQueryObject sqlQueryObject = null;
  462.         // Congelamento di offset e limit (per la count non deve essere utilizzato)
  463.         long oldLimit = search.getLimit();
  464.         long oldOffset = search.getOffset();
  465.         try{
  466.             // Ottengo connessione
  467.             con = getConnection();
  468.             if(con==null)
  469.                 throw new DriverMonitoraggioException("Connection non ottenuta dal datasource["+this.datasource+"]");

  470.             java.sql.Timestamp dataRegistrazioneLimite = null;
  471.             //  FILTRO d) Soglia (ora_registrazione piu' vecchia di NOW-search.getSoglia()) Soglia in Minuti
  472.             if(search.getSoglia()!=-1){
  473.                 dataRegistrazioneLimite = new java.sql.Timestamp(DateManager.getTimeMillis()-(search.getSoglia()*1000*60));
  474.             }

  475.             // TotaleMessaggi: Il totale dei messaggi non deve subire influenze di offset/limit
  476.             long totaleMessaggi = 0;
  477.             search.setLimit(-1);
  478.             search.setOffset(-1);
  479.             sqlQueryObject = this.newSQLQueryObjectStatoRichiestePendenti(search);
  480.             pstmt = con.prepareStatement(sqlQueryObject.createSQLQuery());
  481.             int paramIndex = 0;
  482.             if(search.getSoglia()!=-1)
  483.                 pstmt.setTimestamp(++paramIndex, dataRegistrazioneLimite);
  484.             List<BustaSoggetto> filtroSoggetti = search.getSoggettoList();
  485.             if(filtroSoggetti!=null){
  486.                 for(int k=0; k<filtroSoggetti.size(); k++){

  487.                     // fruitore
  488.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  489.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());

  490.                     // OR

  491.                     // erogatore
  492.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  493.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());
  494.                 }
  495.             }
  496.             rs = pstmt.executeQuery();
  497.             if(rs.next()){
  498.                 totaleMessaggi = rs.getLong("totMessaggi");
  499.             }
  500.             rs.close();
  501.             pstmt.close();
  502.             this.logDebug("query["+sqlQueryObject+"] totaleMessaggi:"+totaleMessaggi);
  503.             this.logDebug("Soglia ["+search.getSoglia()+"] ["+dataRegistrazioneLimite+"] totaleMessaggi");

  504.             return totaleMessaggi;

  505.         }catch(Exception e){
  506.             if(sqlQueryObject!=null){
  507.                 this.logError("getListaRichiestePendenti error SQL["+sqlQueryObject.toString()+"]",e);
  508.                 throw new DriverMonitoraggioException("getListaRichiestePendenti error SQL["+sqlQueryObject.toString()+"]: "+e.getMessage(),e);
  509.             }else{
  510.                 this.logError("getListaRichiestePendenti error",e);
  511.                 throw new DriverMonitoraggioException("getListaRichiestePendenti error: "+e.getMessage(),e);
  512.             }
  513.         }finally{
  514.             // ripristino valori offset/limit
  515.             search.setLimit(oldLimit);
  516.             search.setOffset(oldOffset);
  517.             JDBCUtilities.closeResources(rs, pstmt);
  518.             releaseConnection(con);
  519.         }
  520.     }

  521.     /**
  522.      * Ritorna I dettagli dei messaggi delle richieste pendenti che matchano il criterio di filtro.
  523.      *
  524.      * @param search criterio di filtro
  525.      * @return dettagli dei messaggi delle richieste pendenti
  526.      * @throws DriverMonitoraggioException
  527.      */
  528.     @Override
  529.     public List<Messaggio> getListaRichiestePendenti(FilterSearch search) throws DriverMonitoraggioException{
  530.         Connection con = null;
  531.         PreparedStatement pstmt = null;
  532.         ResultSet rs = null;
  533.         ISQLQueryObject sqlQueryObject = null;
  534.         try{
  535.             // Ottengo connessione
  536.             con = getConnection();
  537.             if(con==null)
  538.                 throw new DriverMonitoraggioException("Connection non ottenuta dal datasource["+this.datasource+"]");

  539.             java.sql.Timestamp dataRegistrazioneLimite = null;
  540.             //  FILTRO d) Soglia (ora_registrazione piu' vecchia di NOW-search.getSoglia()) Soglia in Minuti
  541.             if(search.getSoglia()!=-1){
  542.                 dataRegistrazioneLimite = new java.sql.Timestamp(DateManager.getTimeMillis()-(search.getSoglia()*1000*60));
  543.             }

  544.             List<BustaSoggetto> filtroSoggetti = search.getSoggettoList();

  545.             // Query
  546.             sqlQueryObject = this.newSQLQueryObjectListaRichiestePendenti(search);
  547.             pstmt = con.prepareStatement(sqlQueryObject.createSQLQuery());
  548.             int paramIndex = 0;
  549.             if(search.getSoglia()!=-1)
  550.                 pstmt.setTimestamp(++paramIndex, dataRegistrazioneLimite);
  551.             if(filtroSoggetti!=null){
  552.                 for(int k=0; k<filtroSoggetti.size(); k++){

  553.                     // fruitore
  554.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  555.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());

  556.                     // OR

  557.                     // erogatore
  558.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  559.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());
  560.                 }
  561.             }
  562.             rs = pstmt.executeQuery();
  563.             List<Messaggio> msgs = new ArrayList<>();

  564.             this.logDebug("query["+sqlQueryObject+"] listaMessaggi");
  565.             this.logDebug("Soglia ["+search.getSoglia()+"] ["+dataRegistrazioneLimite+"] listaMessaggi");
  566.            
  567.             while(rs.next()){
  568.                 Messaggio m = new Messaggio();
  569.                 // id
  570.                 m.setIdMessaggio(rs.getString("id_messaggio"));
  571.                 // Dettaglio
  572.                 Dettaglio dettaglio = new Dettaglio();
  573.                 dettaglio.setIdModulo(rs.getString("PROPRIETARIO"));
  574.                 dettaglio.setTipo(rs.getString("tipo"));
  575.                 dettaglio.setErroreProcessamento(rs.getString("ERRORE_PROCESSAMENTO"));
  576.                 dettaglio.setIdCorrelazioneApplicativa(rs.getString("CORRELAZIONE_APPLICATIVA"));
  577.                 if(this.properties!=null){
  578.                     for (int i = 0; i < this.properties.size(); i++) {
  579.                         String key = this.properties.get(i);
  580.                         Proprieta proprieta = new Proprieta();
  581.                         proprieta.setNome(key);
  582.                         proprieta.setValore(rs.getString(key));
  583.                         dettaglio.addProprieta(proprieta);
  584.                     }
  585.                 }
  586.                 m.setDettaglio(dettaglio);
  587.                 // Ora Registrazione
  588.                 if(rs.getTimestamp("ORA_REGISTRAZIONE")!=null){
  589.                     m.setOraRegistrazione(rs.getTimestamp("ORA_REGISTRAZIONE"));
  590.                 }
  591.                 // Ora Attuale
  592.                 m.setOraAttuale(DateManager.getDate());
  593.                 // Stato
  594.                 if(ConsegnaContenutiApplicativi.ID_MODULO.equals(rs.getString("PROPRIETARIO"))){
  595.                     m.setStato(StatoMessaggio.CONSEGNA);
  596.                 }else if(InoltroBuste.ID_MODULO.equals(rs.getString("PROPRIETARIO"))){
  597.                     m.setStato(StatoMessaggio.SPEDIZIONE);
  598.                 }else if(InoltroRisposte.ID_MODULO.equals(rs.getString("PROPRIETARIO"))){
  599.                     m.setStato(StatoMessaggio.SPEDIZIONE);
  600.                 }else {
  601.                     m.setStato(StatoMessaggio.PROCESSAMENTO);
  602.                 }

  603.                 // Info
  604.                 if(search.getBusta()!=null){
  605.                     Busta bustaInfo = new Busta();
  606.                     // Mittente
  607.                     BustaSoggetto mittente = new BustaSoggetto();
  608.                     mittente.setNome(rs.getString("MITTENTE"));
  609.                     mittente.setTipo(rs.getString("TIPO_MITTENTE"));
  610.                     bustaInfo.setMittente(mittente);
  611.                     // Destinatario
  612.                     BustaSoggetto destinatario = new BustaSoggetto();
  613.                     destinatario.setNome(rs.getString("DESTINATARIO"));
  614.                     destinatario.setTipo(rs.getString("TIPO_DESTINATARIO"));
  615.                     bustaInfo.setDestinatario(destinatario);
  616.                     // Servizio
  617.                     BustaServizio servizio = new BustaServizio();
  618.                     servizio.setTipo(rs.getString("TIPO_SERVIZIO"));
  619.                     servizio.setNome(rs.getString("SERVIZIO"));
  620.                     try {
  621.                         servizio.setVersione(Integer.valueOf(rs.getString("VERSIONE_SERVIZIO")));
  622.                     }catch(Exception e) {
  623.                         // ignore
  624.                     }
  625.                     bustaInfo.setServizio(servizio);
  626.                     // Azione
  627.                     bustaInfo.setAzione(rs.getString("AZIONE"));
  628.                     // Profilo di Collaborazione
  629.                     bustaInfo.setProfiloCollaborazione(rs.getString("PROFILO_DI_COLLABORAZIONE"));
  630.                     // RiferimentoMessaggio
  631.                     bustaInfo.setRiferimentoMessaggio(rs.getString("RIFERIMENTO_MESSAGGIO"));
  632.                     //  Collaborazione
  633.                     bustaInfo.setCollaborazione(rs.getString("COLLABORAZIONE"));
  634.                     m.setBustaInfo(bustaInfo);
  635.                 }
  636.                 msgs.add(m);
  637.             }
  638.             rs.close();
  639.             pstmt.close();

  640.             for(int i=0; i<msgs.size(); i++){

  641.                 //  Prendo Dettaglio servizio applicativo per messaggi in consegna
  642.                 boolean checkSA = false;
  643.                 if(msgs.get(i)!=null &&
  644.                         StatoMessaggio.CONSEGNA.equals(msgs.get(i).getStato()) &&
  645.                         msgs.get(i).getDettaglio()!=null){
  646.                     checkSA = true;
  647.                 }else if(msgs.get(i)!=null &&  msgs.get(i).getDettaglio()!=null &&
  648.                         msgs.get(i).getDettaglio().getIdModulo()!=null &&
  649.                         msgs.get(i).getDettaglio().getIdModulo().startsWith("RicezioneContenutiApplicativi")){
  650.                     checkSA = true;
  651.                 }                  
  652.                 if(checkSA){
  653.                     this.logDebug("Raccolgo informazioni dei servizi applicativi...");
  654.                     String sqlQuerySA = "SELECT * FROM "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI +
  655.                             " WHERE ID_MESSAGGIO=?";
  656.                     pstmt = con.prepareStatement(sqlQuerySA);
  657.                     pstmt.setString(1, msgs.get(i).getIdMessaggio());
  658.                     rs = pstmt.executeQuery();
  659.                     List<ServizioApplicativoConsegna> sconsegna = new ArrayList<>();
  660.                     while(rs.next()){
  661.                         ServizioApplicativoConsegna datiConsegna = new ServizioApplicativoConsegna();
  662.                         if(rs.getInt("SBUSTAMENTO_SOAP")==1)
  663.                             datiConsegna.setSbustamentoSoap(true);
  664.                         else
  665.                             datiConsegna.setSbustamentoSoap(false);
  666.                         if(rs.getInt("SBUSTAMENTO_INFO_PROTOCOL")==1)
  667.                             datiConsegna.setSbustamentoInformazioniProtocollo(true);
  668.                         else
  669.                             datiConsegna.setSbustamentoInformazioniProtocollo(false);
  670.                         if(rs.getInt("INTEGRATION_MANAGER")==1)
  671.                             datiConsegna.setAutorizzazioneIntegrationManager(true);
  672.                         else
  673.                             datiConsegna.setAutorizzazioneIntegrationManager(false);
  674.                         datiConsegna.setNome(rs.getString("SERVIZIO_APPLICATIVO"));
  675.                         datiConsegna.setTipoConsegna(rs.getString("TIPO_CONSEGNA"));
  676.                         datiConsegna.setErroreProcessamento(rs.getString("ERRORE_PROCESSAMENTO"));
  677.                         if(rs.getTimestamp("RISPEDIZIONE")!=null){
  678.                             datiConsegna.setDataRispedizione(rs.getTimestamp("RISPEDIZIONE"));
  679.                         }
  680.                         datiConsegna.setNomePorta(rs.getString("NOME_PORTA"));
  681.                         datiConsegna.setCoda(rs.getString("CODA"));
  682.                         datiConsegna.setPriorita(rs.getString("PRIORITA"));
  683.                         if(rs.getInt("ATTESA_ESITO")==1)
  684.                             datiConsegna.setAttesaEsito(true);
  685.                         else
  686.                             datiConsegna.setAttesaEsito(false);
  687.                         sconsegna.add(datiConsegna);
  688.                     }
  689.                     rs.close();
  690.                     pstmt.close();

  691.                     if(!sconsegna.isEmpty()){
  692.                         msgs.get(i).getDettaglio().setServizioApplicativoConsegnaList(sconsegna);
  693.                     }

  694.                 }

  695.                 if(msgs.get(i)!=null &&  msgs.get(i).getBustaInfo()!=null &&
  696.                         StatoMessaggio.SPEDIZIONE.equals(msgs.get(i).getStato())){
  697.                     // Prendo dettaglio AttesaRiscontro
  698.                     if(search.getBusta()!=null && search.getBusta().isAttesaRiscontro()){
  699.                         msgs.get(i).getBustaInfo().setAttesaRiscontro(true);
  700.                     }else{
  701.                         this.logDebug("Raccolgo informazioni per attesa riscontro...");
  702.                         String sqlQueryRiscontro = "SELECT * FROM "+Costanti.RISCONTRI_DA_RICEVERE +
  703.                                 " WHERE ID_MESSAGGIO=?";
  704.                         pstmt = con.prepareStatement(sqlQueryRiscontro);
  705.                         pstmt.setString(1, msgs.get(i).getIdMessaggio());
  706.                         rs = pstmt.executeQuery();
  707.                         msgs.get(i).getBustaInfo().setAttesaRiscontro(rs.next());
  708.                         rs.close();
  709.                         pstmt.close();
  710.                     }
  711.                 }
  712.             }


  713.             return msgs;

  714.         }catch(Exception e){
  715.             if(sqlQueryObject!=null){
  716.                 this.logError("getListaRichiestePendenti error SQL["+sqlQueryObject.toString()+"]",e);
  717.                 throw new DriverMonitoraggioException("getListaRichiestePendenti error SQL["+sqlQueryObject.toString()+"]: "+e.getMessage(),e);
  718.             }else{
  719.                 this.logError("getListaRichiestePendenti error",e);
  720.                 throw new DriverMonitoraggioException("getListaRichiestePendenti error: "+e.getMessage(),e);
  721.             }
  722.         }finally{
  723.             JDBCUtilities.closeResources(rs, pstmt);
  724.             releaseConnection(con);
  725.         }
  726.     }


  727.     /**
  728.      * Elimina puntualmente il messaggio indicato dall'id.
  729.      *
  730.      * @param idMessaggio messaggio da eliminare
  731.      * @throws DriverMonitoraggioException
  732.      */
  733.     private boolean deleteMessaggio(String idMessaggio,String tipo) throws DriverMonitoraggioException{
  734.         Connection con = null;
  735.         PreparedStatement pstmt = null;
  736.         try{

  737.             // Ottengo connessione
  738.             con = getConnection();
  739.             if(con==null)
  740.                 throw new DriverMonitoraggioException("Connection non ottenuta dal datasource["+this.datasource+"]");

  741.             // Raccolta valori chiave
  742.             // TIPO
  743.             String tipoMessaggio = tipo;
  744.             // Ricerco tipoMessaggio se non presenti
  745.             if(tipoMessaggio==null){
  746.                 this.logDebug("Ricerco tipo messaggio...");
  747.                 FilterSearch filtro = new FilterSearch();
  748.                 filtro.setIdMessaggio(idMessaggio);
  749.                 List<Messaggio> lista = this.getListaRichiestePendenti(filtro);
  750.                 if(lista==null || lista.isEmpty()){
  751.                     return false; // messaggio non presente
  752.                 }
  753.                 if(lista.get(0).getDettaglio()==null ||
  754.                         lista.get(0).getDettaglio().getTipo()==null){
  755.                     throw new DriverMonitoraggioException("Tipo messaggio non identificato per l'id: "+idMessaggio);
  756.                 }
  757.                 tipoMessaggio = lista.get(0).getDettaglio().getTipo();
  758.             }
  759.             this.logDebug("Messaggio con id("+idMessaggio+") da eliminare possiede tipo: "+tipoMessaggio);

  760.             if(Costanti.OUTBOX.equals(tipoMessaggio)){
  761.                 // Elimino eventuali riscontri
  762.                 String sqlQuery = "DELETE FROM "+Costanti.RISCONTRI_DA_RICEVERE + " WHERE ID_MESSAGGIO=?";
  763.                 pstmt = con.prepareStatement(sqlQuery);
  764.                 pstmt.setString(1, idMessaggio);
  765.                 int operation = pstmt.executeUpdate();
  766.                 if(operation>0){
  767.                     this.logDebug("Attesa riscontro per "+idMessaggio+" eliminato");
  768.                 }else{
  769.                     this.logDebug("Attesa riscontro per "+idMessaggio+" non esistente");
  770.                 }
  771.                 pstmt.close();

  772.                 // Elimino eventuali asincroni
  773.                 sqlQuery = "DELETE FROM "+Costanti.PROFILO_ASINCRONO + " WHERE ID_MESSAGGIO=? AND TIPO=?";
  774.                 pstmt = con.prepareStatement(sqlQuery);
  775.                 pstmt.setString(1, idMessaggio);
  776.                 pstmt.setString(2, tipoMessaggio);
  777.                 operation = pstmt.executeUpdate();
  778.                 if(operation>0){
  779.                     this.logDebug("ProfiloAsincrono per "+idMessaggio+" eliminato");
  780.                 }else{
  781.                     this.logDebug("ProfiloAsincrono per "+idMessaggio+" non esistente");
  782.                 }
  783.                 pstmt.close();
  784.             }


  785.             // Elimino messaggio
  786.             String sqlQuery = "UPDATE "+GestoreMessaggi.MESSAGGI + " SET PROPRIETARIO='"+TimerGestoreMessaggi.ID_MODULO+"' WHERE PROPRIETARIO<>'"+TimerGestoreMessaggi.ID_MODULO+"' AND ID_MESSAGGIO=?  AND tipo=?";
  787.             pstmt = con.prepareStatement(sqlQuery);
  788.             pstmt.setString(1, idMessaggio);
  789.             pstmt.setString(2, tipoMessaggio);
  790.             int operation = pstmt.executeUpdate();
  791.             boolean result = false;
  792.             if(operation>0){
  793.                 result = true;
  794.                 this.logDebug("Messaggio "+idMessaggio+" eliminato");
  795.             }else{
  796.                 this.logDebug("Messaggio "+idMessaggio+" non esistente");
  797.             }
  798.             pstmt.close();
  799.             return result;

  800.         }catch(Exception e){
  801.             this.logError("deleteMessaggio error",e);
  802.             throw new DriverMonitoraggioException("deleteMessaggio error: "+e.getMessage());
  803.         }finally{
  804.             JDBCUtilities.closeResources(pstmt);
  805.             releaseConnection(con);
  806.         }
  807.     }
  808.    
  809.     private boolean aggiornaDataRispedizioneMessaggio(String idMessaggio,String tipo,Timestamp data) throws DriverMonitoraggioException{
  810.         Connection con = null;
  811.         PreparedStatement pstmt = null;
  812.         try{

  813.             // Ottengo connessione
  814.             con = getConnection();
  815.             if(con==null)
  816.                 throw new DriverMonitoraggioException("Connection non ottenuta dal datasource["+this.datasource+"]");

  817.             // Raccolta valori chiave
  818.             // TIPO
  819.             String tipoMessaggio = tipo;
  820.             // Ricerco tipoMessaggio se non presenti
  821.             if(tipoMessaggio==null){
  822.                 this.logDebug("Ricerco tipo messaggio...");
  823.                 FilterSearch filtro = new FilterSearch();
  824.                 filtro.setIdMessaggio(idMessaggio);
  825.                 List<Messaggio> lista = this.getListaRichiestePendenti(filtro);
  826.                 if(lista==null || lista.isEmpty()){
  827.                     return false; // messaggio non presente
  828.                 }
  829.                 if(lista.get(0).getDettaglio()==null ||
  830.                         lista.get(0).getDettaglio().getTipo()==null){
  831.                     throw new DriverMonitoraggioException("Tipo messaggio non identificato per l'id: "+idMessaggio);
  832.                 }
  833.                 tipoMessaggio = lista.get(0).getDettaglio().getTipo();
  834.             }
  835.             this.logDebug("Messaggio con id("+idMessaggio+") da eliminare possiede tipo: "+tipoMessaggio);

  836.             if(Costanti.OUTBOX.equals(tipoMessaggio)){
  837.                 // Aggiorno messaggio
  838.                 String sqlQuery = "UPDATE "+GestoreMessaggi.MESSAGGI + " SET RISPEDIZIONE=? WHERE ID_MESSAGGIO=?  AND TIPO=?";
  839.                 pstmt = con.prepareStatement(sqlQuery);
  840.                 pstmt.setTimestamp(1, data);
  841.                 pstmt.setString(2, idMessaggio);
  842.                 pstmt.setString(3, tipoMessaggio);
  843.                 int operation = pstmt.executeUpdate();
  844.                 boolean result = false;
  845.                 if(operation>0){
  846.                     result = true;
  847.                     this.logDebug("Messaggio "+idMessaggio+" aggiornato");
  848.                 }else{
  849.                     this.logDebug("Messaggio "+idMessaggio+" non aggiornato");
  850.                 }
  851.                 pstmt.close();
  852.                 return result;  
  853.             }
  854.             else {
  855.                 // Aggiorno messaggio
  856.                 String sqlQuery = "UPDATE "+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI + " SET RISPEDIZIONE=? WHERE ID_MESSAGGIO=?  AND TIPO=?";
  857.                 pstmt = con.prepareStatement(sqlQuery);
  858.                 pstmt.setTimestamp(1, data);
  859.                 pstmt.setString(2, idMessaggio);
  860.                 pstmt.setString(3, tipoMessaggio);
  861.                 int operation = pstmt.executeUpdate();
  862.                 boolean result = false;
  863.                 if(operation>0){
  864.                     result = true;
  865.                     this.logDebug("Messaggio "+idMessaggio+" aggiornato");
  866.                 }else{
  867.                     this.logDebug("Messaggio "+idMessaggio+" non aggiornato");
  868.                 }
  869.                 pstmt.close();
  870.                 return result;  
  871.             }

  872.         }catch(Exception e){
  873.             this.logError("deleteMessaggio error",e);
  874.             throw new DriverMonitoraggioException("deleteMessaggio error: "+e.getMessage());
  875.         }finally{
  876.             try{
  877.                 if(pstmt!=null)
  878.                     pstmt.close();
  879.             }catch(Exception e){
  880.                 // close
  881.             }
  882.             releaseConnection(con);
  883.         }
  884.     }



  885.     /**
  886.      * Ritorna e cancella i dettagli dei messaggi delle richieste pendenti che matchano il criterio di filtro.
  887.      *
  888.      * @param search criterio di filtro
  889.      * @return dettagli dei messaggi delle richieste pendenti
  890.      * @throws DriverMonitoraggioException
  891.      */
  892.     @Override
  893.     public long deleteRichiestePendenti(FilterSearch search) throws DriverMonitoraggioException{
  894.         return richiestePendentiEngine(search, true);
  895.     }
  896.    
  897.     /**
  898.      * Aggiorna la data di rispedizione delle richieste pendenti che matchano il criterio di filtro.
  899.      *
  900.      * @param search criterio di filtro
  901.      * @return numero dei messaggi delle richieste pendenti
  902.      * @throws DriverMonitoraggioException
  903.      */
  904.     @Override
  905.     public long aggiornaDataRispedizioneRichiestePendenti(FilterSearch search) throws DriverMonitoraggioException{
  906.         return richiestePendentiEngine(search, false);
  907.     }
  908.    
  909.     private long richiestePendentiEngine(FilterSearch search, boolean delete) throws DriverMonitoraggioException{
  910.        
  911.         String nomeMetodo = delete? "deleteRichiestePendenti":"aggiornaDataRispedizioneRichiestePendenti";
  912.        
  913.         Connection con = null;
  914.         PreparedStatement pstmt = null;
  915.         ResultSet rs = null;
  916.         ISQLQueryObject sqlQueryObject = null;
  917.         try{
  918.             // Ottengo connessione
  919.             con = getConnection();
  920.             if(con==null)
  921.                 throw new DriverMonitoraggioException("Connection non ottenuta dal datasource["+this.datasource+"]");

  922.             java.sql.Timestamp dataRegistrazioneLimite = null;
  923.             //  FILTRO d) Soglia (ora_registrazione piu' vecchia di NOW-search.getSoglia()) Soglia in Minuti
  924.             if(search.getSoglia()!=-1){
  925.                 dataRegistrazioneLimite = new java.sql.Timestamp(DateManager.getTimeMillis()-(search.getSoglia()*1000*60));
  926.             }
  927.             // Query
  928.             sqlQueryObject = this.newSQLQueryObjectListaRichiestePendenti(search);
  929.             pstmt = con.prepareStatement(sqlQueryObject.createSQLQuery());
  930.             int paramIndex = 0;
  931.             if(search.getSoglia()!=-1)
  932.                 pstmt.setTimestamp(++paramIndex, dataRegistrazioneLimite);
  933.             List<BustaSoggetto> filtroSoggetti = search.getSoggettoList();
  934.             if(filtroSoggetti!=null){
  935.                 for(int k=0; k<filtroSoggetti.size(); k++){

  936.                     // fruitore
  937.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  938.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());

  939.                     // OR

  940.                     // erogatore
  941.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getTipo());
  942.                     pstmt.setString(++paramIndex, filtroSoggetti.get(k).getNome());
  943.                 }
  944.             }
  945.             rs = pstmt.executeQuery();
  946.             List<Messaggio> msgs = new ArrayList<>();

  947.             this.logDebug("query["+sqlQueryObject+"] listaMessaggi");
  948.             this.logDebug("Soglia ["+search.getSoglia()+"] ["+dataRegistrazioneLimite+"] listaMessaggi");

  949.             while(rs.next()){
  950.                 Messaggio m = new Messaggio();
  951.                 // id
  952.                 m.setIdMessaggio(rs.getString("ID_MESSAGGIO"));
  953.                 // Dettaglio
  954.                 Dettaglio dettaglio = new Dettaglio();
  955.                 dettaglio.setTipo(rs.getString("tipo"));
  956.                 m.setDettaglio(dettaglio);
  957.                 msgs.add(m);
  958.             }
  959.             rs.close();
  960.             pstmt.close();

  961.             Timestamp now = DateManager.getTimestamp();
  962.            
  963.             long numeroMsg = 0;
  964.             while(!msgs.isEmpty()){
  965.                 Messaggio msgForDelete = msgs.remove(0);
  966.                 if(delete) {
  967.                     if(this.deleteMessaggio(msgForDelete.getIdMessaggio(), msgForDelete.getDettaglio().getTipo())) {
  968.                         numeroMsg++;
  969.                     }
  970.                 }
  971.                 else {
  972.                     if(this.aggiornaDataRispedizioneMessaggio(msgForDelete.getIdMessaggio(), msgForDelete.getDettaglio().getTipo(), now)) {
  973.                         numeroMsg++;
  974.                     }
  975.                 }
  976.             }
  977.             if(delete) {
  978.                 this.logDebug("eliminati "+numeroMsg+" messaggi");
  979.             }
  980.             else {
  981.                 this.logDebug("aggiornati "+numeroMsg+" messaggi");
  982.             }

  983.             return numeroMsg;

  984.         }catch(Exception e){
  985.             if(sqlQueryObject!=null){
  986.                 this.logError(nomeMetodo+" error SQL["+sqlQueryObject.toString()+"]",e);
  987.                 throw new DriverMonitoraggioException(nomeMetodo+" error SQL["+sqlQueryObject.toString()+"]: "+e.getMessage(),e);
  988.             }else{
  989.                 this.logError(nomeMetodo+" error",e);
  990.                 throw new DriverMonitoraggioException(nomeMetodo+" error: "+e.getMessage(),e);
  991.             }
  992.         }finally{
  993.             JDBCUtilities.closeResources(rs, pstmt);
  994.             releaseConnection(con);
  995.         }
  996.     }


  997.     @Override
  998.     public StatoConsegneAsincrone getStatoConsegneAsincrone(FiltroStatoConsegnaAsincrona filtro) throws DriverMonitoraggioException{
  999.        
  1000.         String nomeMetodo = "getStatoConsegneAsincrone";
  1001.        
  1002.         Connection con = null;
  1003.         PreparedStatement pstmt = null;
  1004.         ResultSet rs = null;
  1005.         String sqlQuery = null;
  1006.         try{
  1007.             // Ottengo connessione
  1008.             con = getConnection();
  1009.             if(con==null)
  1010.                 throw new DriverMonitoraggioException("Connection non ottenuta dal datasource["+this.datasource+"]");

  1011.             // Query
  1012.             sqlQuery = this.newSQLQueryStatoConsegneAsincrone(filtro);
  1013.             /**System.out.println("QUERY: "+sqlQuery);*/
  1014.             pstmt = con.prepareStatement(sqlQuery);
  1015.             rs = pstmt.executeQuery();
  1016.             StatoConsegneAsincrone stati = new StatoConsegneAsincrone();

  1017.             this.logDebug("query["+sqlQuery+"] getStatoConsegneAsincrone");
  1018.            
  1019.             while(rs.next()){
  1020.                 StatoConsegnaAsincrona stato = new StatoConsegnaAsincrona();
  1021.                
  1022.                 // dati generali
  1023.                 stato.setNow(rs.getTimestamp(StatoConsegnaAsincrona.ALIAS_NOW));
  1024.                 stato.setServizioApplicativo(rs.getString(StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO));
  1025.                
  1026.                 // InCoda
  1027.                 stato.setInCoda(rs.getLong(StatoConsegnaAsincrona.ALIAS_IN_CODA));
  1028.                 stato.setVecchioInCoda(rs.getTimestamp(StatoConsegnaAsincrona.ALIAS_IN_CODA_VECCHIO));
  1029.                 stato.setRecenteInCoda(rs.getTimestamp(StatoConsegnaAsincrona.ALIAS_IN_CODA_RECENTE));
  1030.                
  1031.                 // InRiconsegna
  1032.                 stato.setInRiconsegna(rs.getLong(StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA));
  1033.                 stato.setVecchioInRiconsegna(rs.getTimestamp(StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_VECCHIO));
  1034.                 stato.setRecenteInRiconsegna(rs.getTimestamp(StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_RECENTE));
  1035.                
  1036.                 // InMessageBox
  1037.                 stato.setInMessageBox(rs.getLong(StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX));
  1038.                 stato.setVecchioInMessageBox(rs.getTimestamp(StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_VECCHIO));
  1039.                 stato.setRecenteInMessageBox(rs.getTimestamp(StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_RECENTE));
  1040.                
  1041.                 stati.addStato(stato);
  1042.             }
  1043.             rs.close();
  1044.             pstmt.close();

  1045.             this.logDebug("trovati "+stati.size()+" stati");
  1046.    
  1047.             return stati;

  1048.         }catch(Exception e){
  1049.             if(sqlQuery!=null){
  1050.                 this.logError(nomeMetodo+" error SQL["+sqlQuery+"]",e);
  1051.                 throw new DriverMonitoraggioException(nomeMetodo+" error SQL["+sqlQuery+"]: "+e.getMessage(),e);
  1052.             }else{
  1053.                 this.logError(nomeMetodo+" error",e);
  1054.                 throw new DriverMonitoraggioException(nomeMetodo+" error: "+e.getMessage(),e);
  1055.             }
  1056.         }finally{
  1057.             JDBCUtilities.closeResources(rs, pstmt);
  1058.             releaseConnection(con);
  1059.         }
  1060.        
  1061.     }
  1062.    
  1063.    




  1064.     private ISQLQueryObject newSQLQueryObjectStatoRichiestePendenti(FilterSearch search) throws SQLQueryObjectException{
  1065.         return newSQLQueryObjectRichiestePendenti(true,search);
  1066.     }
  1067.     private ISQLQueryObject newSQLQueryObjectListaRichiestePendenti(FilterSearch search) throws SQLQueryObjectException{
  1068.         return newSQLQueryObjectRichiestePendenti(false,search);
  1069.     }

  1070.     private ISQLQueryObject newSQLQueryObjectRichiestePendenti(boolean statoRichieste,FilterSearch search) throws SQLQueryObjectException{

  1071.         ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.tipoDatabase);

  1072.         // FROM TABLE
  1073.         sqlQueryObject.addFromTable(GestoreMessaggi.MESSAGGI);
  1074.         if( (search.getMessagePattern()!=null) && (!"".equals(search.getMessagePattern())) ){
  1075.             sqlQueryObject.addFromTable(GestoreMessaggi.DEFINIZIONE_MESSAGGI);
  1076.         }
  1077.         if( (search.getBusta()!=null) ){
  1078.             sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  1079.             if(search.getBusta().isAttesaRiscontro()){
  1080.                 sqlQueryObject.addFromTable(Costanti.RISCONTRI_DA_RICEVERE);
  1081.             }
  1082.         }else if(search.getSoggettoList()!=null && !search.getSoggettoList().isEmpty()){
  1083.             sqlQueryObject.addFromTable(Costanti.REPOSITORY);
  1084.         }

  1085.         // Condizione per legare le tabelle
  1086.         String legameTabelleSQLMsgId = GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+GestoreMessaggi.DEFINIZIONE_MESSAGGI+".ID_MESSAGGIO";
  1087.         String legameTabelleSQLMsgTipo = GestoreMessaggi.MESSAGGI+".TIPO="+GestoreMessaggi.DEFINIZIONE_MESSAGGI+".TIPO";
  1088.         String legameTabelleSQLBustaId = GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+Costanti.REPOSITORY+".ID_MESSAGGIO";
  1089.         String legameTabelleSQLBustaTipo = GestoreMessaggi.MESSAGGI+".TIPO="+Costanti.REPOSITORY+".TIPO";
  1090.         String legameTabelleSQLRiscontro = GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO="+Costanti.RISCONTRI_DA_RICEVERE+".ID_MESSAGGIO";
  1091.         if( (search.getMessagePattern()!=null) && (!"".equals(search.getMessagePattern())) ){
  1092.             sqlQueryObject.addWhereCondition(true,legameTabelleSQLMsgId,legameTabelleSQLMsgTipo);
  1093.         }
  1094.         if(search.getBusta()!=null){
  1095.             sqlQueryObject.addWhereCondition(true,legameTabelleSQLBustaId,legameTabelleSQLBustaTipo);
  1096.         }else if(search.getSoggettoList()!=null && !search.getSoggettoList().isEmpty()){
  1097.             sqlQueryObject.addWhereCondition(true,legameTabelleSQLBustaId,legameTabelleSQLBustaTipo);
  1098.         }
  1099.         if(search.getBusta()!=null && search.getBusta().isAttesaRiscontro()){
  1100.             sqlQueryObject.addWhereCondition(legameTabelleSQLRiscontro);
  1101.         }



  1102.         if(statoRichieste){
  1103.             // SELECT PER STATO

  1104.             // Count
  1105.             sqlQueryObject.addSelectCountField(GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO", "totMessaggi", true);

  1106.             // Tempo Medio
  1107.             sqlQueryObject.addSelectAvgTimestampField(GestoreMessaggi.MESSAGGI+".ora_registrazione", "ora_registrazione_media");

  1108.             // Tempo Massimo
  1109.             sqlQueryObject.addSelectMinTimestampField(GestoreMessaggi.MESSAGGI+".ora_registrazione", "ora_registrazione_old");

  1110.         }else {

  1111.             // SELECT FIELD PER LISTA

  1112.             // Tabella OpenSPCoop.sql.Messaggi
  1113.             sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,"ID_MESSAGGIO");
  1114.             sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,"TIPO");
  1115.             sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,"PROPRIETARIO");
  1116.             sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,"ORA_REGISTRAZIONE");
  1117.             sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,"ERRORE_PROCESSAMENTO");    
  1118.             sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,"CORRELAZIONE_APPLICATIVA");
  1119.             if(this.properties!=null){
  1120.                 for (int i = 0; i < this.properties.size(); i++) {
  1121.                     String key = this.properties.get(i);
  1122.                     sqlQueryObject.addSelectField(GestoreMessaggi.MESSAGGI,key);
  1123.                 }
  1124.             }
  1125.             if( (search.getMessagePattern()!=null) && (!"".equals(search.getMessagePattern())) ){
  1126.                 // Tabella OpenSPCoop.sql.DefinizioneMessaggi
  1127. // Queste due colonne non servono: altrimenti si ottiene un errore column ambiguously defined.
  1128. // se in futuro serviranno, utilizzare degli alias
  1129.                 /**sqlQueryObject.addSelectField(GestoreMessaggi.DEFINIZIONE_MESSAGGI,"ID_MESSAGGIO");
  1130.                 sqlQueryObject.addSelectField(GestoreMessaggi.DEFINIZIONE_MESSAGGI,"TIPO");*/
  1131.                 sqlQueryObject.addSelectField(GestoreMessaggi.DEFINIZIONE_MESSAGGI,"MSG_BYTES");
  1132.             }  
  1133.             if(search.getBusta()!=null){
  1134.                 // Tabella Libreria.sql.Repository
  1135. // Queste due colonne non servono: altrimenti si ottiene un errore column ambiguously defined.
  1136. // se in futuro serviranno, utilizzare degli alias
  1137.                 /**sqlQueryObject.addSelectField(Costanti.REPOSITORY,"ID_MESSAGGIO");
  1138.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"TIPO");*/
  1139.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"TIPO_MITTENTE");
  1140.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"MITTENTE");
  1141.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"TIPO_DESTINATARIO");
  1142.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"DESTINATARIO");
  1143.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"TIPO_SERVIZIO");
  1144.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"SERVIZIO");
  1145.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"AZIONE");
  1146.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"PROFILO_DI_COLLABORAZIONE");
  1147.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"RIFERIMENTO_MESSAGGIO");
  1148.                 sqlQueryObject.addSelectField(Costanti.REPOSITORY,"COLLABORAZIONE");
  1149.             }  
  1150.             if(search.getBusta()!=null && search.getBusta().isAttesaRiscontro()){
  1151.                 // Tabella Libreria.sql.RiscontriDaRicevere
  1152. // Queste due colonne non servono: altrimenti si ottiene un errore column ambiguously defined.
  1153. // se in futuro serviranno, utilizzare degli alias
  1154.                 /**sqlQueryObject.addSelectField(Costanti.RISCONTRI_DA_RICEVERE,"ID_MESSAGGIO");*/
  1155.             }

  1156.         }

  1157.         // Where Logico Operator
  1158.         sqlQueryObject.setANDLogicOperator(true);

  1159.         // Order By OraRegistrazione
  1160.         if(!statoRichieste){
  1161.             sqlQueryObject.addOrderBy(GestoreMessaggi.MESSAGGI+".ORA_REGISTRAZIONE");
  1162.             sqlQueryObject.setSortType(false); // DESC
  1163.         }

  1164.         // Proprietario non deve essere GestoreMessaggi, a meno che il filtro non richieda proprio questo
  1165.         if( (search.getStato()==null) || ("".equals(search.getStato().getValue())) || (!StatoMessaggio.CANCELLATO.equals(search.getStato())) )
  1166.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".PROPRIETARIO<>'"+TimerGestoreMessaggi.ID_MODULO+"'");

  1167.         // Filtri:

  1168.         // a) StatoMessaggio
  1169.         if( (search.getStato()!=null) && (!"".equals(search.getStato().getValue())) ){
  1170.             if(StatoMessaggio.CONSEGNA.equals(search.getStato())){
  1171.                 sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".PROPRIETARIO='"+ConsegnaContenutiApplicativi.ID_MODULO+"'");
  1172.             }else if(StatoMessaggio.SPEDIZIONE.equals(search.getStato())){
  1173.                 sqlQueryObject.addWhereCondition(false,
  1174.                         GestoreMessaggi.MESSAGGI+".PROPRIETARIO='"+InoltroBuste.ID_MODULO+"'",
  1175.                         GestoreMessaggi.MESSAGGI+".PROPRIETARIO='"+InoltroRisposte.ID_MODULO+"'");
  1176.             }else if(StatoMessaggio.CANCELLATO.equals(search.getStato())){
  1177.                 sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".PROPRIETARIO='"+TimerGestoreMessaggi.ID_MODULO+"'");
  1178.             }else if(StatoMessaggio.PROCESSAMENTO.equals(search.getStato())){
  1179.                 sqlQueryObject.addWhereCondition(true, GestoreMessaggi.MESSAGGI+".PROPRIETARIO<>'"+InoltroBuste.ID_MODULO+"'",
  1180.                         GestoreMessaggi.MESSAGGI+".PROPRIETARIO<>'"+InoltroRisposte.ID_MODULO+"'",
  1181.                         GestoreMessaggi.MESSAGGI+".PROPRIETARIO<>'"+ConsegnaContenutiApplicativi.ID_MODULO+"'");
  1182.             }else{
  1183.                 throw new SQLQueryObjectException("Stato per filtro non conosciuto: "+search.getStato());
  1184.             }
  1185.         }

  1186.         // b) idMessaggio e propertiesRicerca
  1187.         if( (search.getIdMessaggio()!=null) && (!"".equals(search.getIdMessaggio())) ){
  1188.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".ID_MESSAGGIO='"+search.getIdMessaggio()+"'");
  1189.         }
  1190.         if( (search.getProprietaList()!=null) && (!search.getProprietaList().isEmpty()) ){
  1191.             List<Proprieta> proprietaList = search.getProprietaList();
  1192.             for (Proprieta proprieta : proprietaList) {
  1193.                 sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+"."+proprieta.getNome()+"='"+proprieta.getValore()+"'");  
  1194.             }
  1195.         }

  1196.         // c) MessagePattern e CorrelazioneApplicativa
  1197.         if( (search.getMessagePattern()!=null) && (!"".equals(search.getMessagePattern())) ){
  1198.             sqlQueryObject.addWhereLikeCondition(GestoreMessaggi.DEFINIZIONE_MESSAGGI+".MSG_BYTES",search.getMessagePattern(),true,true);
  1199.         }
  1200.         if( (search.getCorrelazioneApplicativa()!=null) && (!"".equals(search.getCorrelazioneApplicativa())) ){
  1201.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".CORRELAZIONE_APPLICATIVA='"+search.getCorrelazioneApplicativa()+"'");
  1202.         }

  1203.         // d) Soglia (ora_registrazione piu' vecchia di NOW-search.getSoglia())
  1204.         if(search.getSoglia()!=-1){
  1205.             sqlQueryObject.addWhereCondition(GestoreMessaggi.MESSAGGI+".ora_registrazione<=?");
  1206.         }

  1207.         if(!statoRichieste){
  1208.             // e) limit
  1209.             if(search.getLimit()!=-1){
  1210.                 sqlQueryObject.setLimit((int)search.getLimit());
  1211.             }
  1212.             // f) offset
  1213.             if(search.getOffset()!=-1){
  1214.                 sqlQueryObject.setOffset((int)search.getOffset());
  1215.             }
  1216.         }

  1217.         if(search.getBusta()!=null){

  1218.             // Busta filter

  1219.             // mittente
  1220.             if(search.getBusta().getMittente()!=null){
  1221.                 if( (search.getBusta().getMittente().getTipo()!=null) && (!"".equals(search.getBusta().getMittente().getTipo())) ){
  1222.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".TIPO_MITTENTE='"+search.getBusta().getMittente().getTipo()+"'");
  1223.                 }
  1224.                 if( (search.getBusta().getMittente().getNome()!=null) && (!"".equals(search.getBusta().getMittente().getNome())) ){
  1225.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".MITTENTE='"+search.getBusta().getMittente().getNome()+"'");
  1226.                 }
  1227.             }

  1228.             // destinatario
  1229.             if(search.getBusta().getDestinatario()!=null){
  1230.                 if( (search.getBusta().getDestinatario().getTipo()!=null) && (!"".equals(search.getBusta().getDestinatario().getTipo())) ){
  1231.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".TIPO_DESTINATARIO='"+search.getBusta().getDestinatario().getTipo()+"'");
  1232.                 }
  1233.                 if( (search.getBusta().getDestinatario().getNome()!=null) && (!"".equals(search.getBusta().getDestinatario().getNome())) ){
  1234.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".DESTINATARIO='"+search.getBusta().getDestinatario().getNome()+"'");
  1235.                 }
  1236.             }

  1237.             // servizio
  1238.             if(search.getBusta().getServizio()!=null){
  1239.                 if( (search.getBusta().getServizio().getTipo()!=null) && (!"".equals(search.getBusta().getServizio().getTipo())) ){
  1240.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".TIPO_SERVIZIO='"+search.getBusta().getServizio().getTipo()+"'");
  1241.                 }
  1242.                 if( (search.getBusta().getServizio().getNome()!=null) && (!"".equals(search.getBusta().getServizio().getNome())) ){
  1243.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".SERVIZIO='"+search.getBusta().getServizio().getNome()+"'");
  1244.                 }
  1245.                 if( (search.getBusta().getServizio().getVersione()!=null) && (search.getBusta().getServizio().getVersione().intValue()>0) ){
  1246.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".VERSIONE_SERVIZIO='"+search.getBusta().getServizio().getVersione().intValue()+"'");
  1247.                 }
  1248.             }

  1249.             // azione
  1250.             if( (search.getBusta().getAzione()!=null) && (!"".equals(search.getBusta().getAzione())) ){
  1251.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".AZIONE='"+search.getBusta().getAzione()+"'");
  1252.             }

  1253.             // profiloCollaborazione
  1254.             if( (search.getBusta().getProfiloCollaborazione()!=null) && (!"".equals(search.getBusta().getProfiloCollaborazione())) ){
  1255.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".PROFILO_DI_COLLABORAZIONE='"+search.getBusta().getProfiloCollaborazione()+"'");
  1256.             }

  1257.             // riferimentoMessaggio
  1258.             if( (search.getBusta().getRiferimentoMessaggio()!=null) && (!"".equals(search.getBusta().getRiferimentoMessaggio())) ){
  1259.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".RIFERIMENTO_MESSAGGIO='"+search.getBusta().getRiferimentoMessaggio()+"'");
  1260.             }

  1261.             // Collaborazione
  1262.             if( (search.getBusta().getCollaborazione()!=null) && (!"".equals(search.getBusta().getCollaborazione())) ){
  1263.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".COLLABORAZIONE='"+search.getBusta().getCollaborazione()+"'");
  1264.             }

  1265.         }

  1266.         if(search.getSoggettoList()!=null && !search.getSoggettoList().isEmpty()){

  1267.             List<BustaSoggetto> filtroSoggetti = search.getSoggettoList();
  1268.             StringBuilder query = new StringBuilder();
  1269.             for(int k=0; k<filtroSoggetti.size(); k++){
  1270.                 if(k>0)
  1271.                     query.append(" OR ");
  1272.                 query.append("( ");
  1273.                 query.append("("+Costanti.REPOSITORY+".TIPO_MITTENTE = ? AND "+Costanti.REPOSITORY+".MITTENTE = ?)");
  1274.                 query.append(" OR ");
  1275.                 query.append("("+Costanti.REPOSITORY+".TIPO_DESTINATARIO = ? AND "+Costanti.REPOSITORY+".DESTINATARIO = ?)");
  1276.                 query.append(" )");
  1277.             }
  1278.             sqlQueryObject.addWhereCondition(query.toString());
  1279.         }

  1280.         return sqlQueryObject;
  1281.     }










  1282.     private ISQLQueryObject newSQLQueryPacchettiDuplicati(FilterSearch search) throws SQLQueryObjectException{

  1283.         ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.tipoDatabase);

  1284.         // FROM TABLE
  1285.         sqlQueryObject.addFromTable(Costanti.REPOSITORY);

  1286.         // SELECT FIELD
  1287.         sqlQueryObject.addSelectField("sum(DUPLICATI) as numduplicati");

  1288.         // Where Logico Operator
  1289.         sqlQueryObject.setANDLogicOperator(true);


  1290.         // Filtri:

  1291.         // a) idMessaggio
  1292.         if( (search.getIdMessaggio()!=null) && (!"".equals(search.getIdMessaggio())) ){
  1293.             sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".ID_MESSAGGIO='"+search.getIdMessaggio()+"'");
  1294.         }

  1295.         // b) Soglia (ora_registrazione piu' vecchia di NOW-search.getSoglia())
  1296.         if(search.getSoglia()!=-1){
  1297.             sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".ora_registrazione<=?");
  1298.         }

  1299.         if(search.getBusta()!=null){

  1300.             // Busta filter

  1301.             // mittente
  1302.             if(search.getBusta().getMittente()!=null){
  1303.                 if( (search.getBusta().getMittente().getTipo()!=null) && (!"".equals(search.getBusta().getMittente().getTipo())) ){
  1304.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".TIPO_MITTENTE='"+search.getBusta().getMittente().getTipo()+"'");
  1305.                 }
  1306.                 if( (search.getBusta().getMittente().getNome()!=null) && (!"".equals(search.getBusta().getMittente().getNome())) ){
  1307.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".MITTENTE='"+search.getBusta().getMittente().getNome()+"'");
  1308.                 }
  1309.             }

  1310.             // destinatario
  1311.             if(search.getBusta().getDestinatario()!=null){
  1312.                 if( (search.getBusta().getDestinatario().getTipo()!=null) && (!"".equals(search.getBusta().getDestinatario().getTipo())) ){
  1313.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".TIPO_DESTINATARIO='"+search.getBusta().getDestinatario().getTipo()+"'");
  1314.                 }
  1315.                 if( (search.getBusta().getDestinatario().getNome()!=null) && (!"".equals(search.getBusta().getDestinatario().getNome())) ){
  1316.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".DESTINATARIO='"+search.getBusta().getDestinatario().getNome()+"'");
  1317.                 }
  1318.             }

  1319.             // servizio
  1320.             if(search.getBusta().getServizio()!=null){
  1321.                 if( (search.getBusta().getServizio().getTipo()!=null) && (!"".equals(search.getBusta().getServizio().getTipo())) ){
  1322.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".TIPO_SERVIZIO='"+search.getBusta().getServizio().getTipo()+"'");
  1323.                 }
  1324.                 if( (search.getBusta().getServizio().getNome()!=null) && (!"".equals(search.getBusta().getServizio().getNome())) ){
  1325.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".SERVIZIO='"+search.getBusta().getServizio().getNome()+"'");
  1326.                 }
  1327.                 if( (search.getBusta().getServizio().getVersione()!=null) && (search.getBusta().getServizio().getVersione().intValue()>0) ){
  1328.                     sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".VERSIONE_SERVIZIO='"+search.getBusta().getServizio().getVersione().intValue()+"'");
  1329.                 }
  1330.             }

  1331.             // azione
  1332.             if( (search.getBusta().getAzione()!=null) && (!"".equals(search.getBusta().getAzione())) ){
  1333.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".AZIONE='"+search.getBusta().getAzione()+"'");
  1334.             }

  1335.             // profiloCollaborazione
  1336.             if( (search.getBusta().getProfiloCollaborazione()!=null) && (!"".equals(search.getBusta().getProfiloCollaborazione())) ){
  1337.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".PROFILO_DI_COLLABORAZIONE='"+search.getBusta().getProfiloCollaborazione()+"'");
  1338.             }

  1339.             // riferimentoMessaggio
  1340.             if( (search.getBusta().getRiferimentoMessaggio()!=null) && (!"".equals(search.getBusta().getRiferimentoMessaggio())) ){
  1341.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".RIFERIMENTO_MESSAGGIO='"+search.getBusta().getRiferimentoMessaggio()+"'");
  1342.             }

  1343.             // Collaborazione
  1344.             if( (search.getBusta().getCollaborazione()!=null) && (!"".equals(search.getBusta().getCollaborazione())) ){
  1345.                 sqlQueryObject.addWhereCondition(Costanti.REPOSITORY+".COLLABORAZIONE='"+search.getBusta().getCollaborazione()+"'");
  1346.             }

  1347.         }

  1348.         return sqlQueryObject;
  1349.     }
  1350.    
  1351.    
  1352.     private String newSQLQueryStatoConsegneAsincrone(FiltroStatoConsegnaAsincrona filtro) throws SQLQueryObjectException{

  1353.         String aliasTableServiziApplicativi = "sa";
  1354.         String aliasTableMessaggi = "m";
  1355.        
  1356.         // ** InCoda **
  1357.        
  1358.         /*
  1359.          *  select 0 as inRiconsegna, count(*) as inCoda,
  1360.          *  null::timestamp as vecchioInRiconsegna, null::timestamp as recenteInRiconsegna,
  1361.          *  min(sa.ora_registrazione) as vecchioInCoda, max(sa.ora_registrazione) as recenteInCoda,
  1362.          *  0 as inCaricoIM, null::timestamp as vecchioInCaricoIM, null::timestamp as recenteInCaricoIM,
  1363.          *  sa.SERVIZIO_APPLICATIVO  
  1364.          *  from msg_servizi_applicativi sa,messaggi m
  1365.          *  where
  1366.          *  sa.attesa_esito=0 AND
  1367.          *  (sa.errore_processamento_compact='TimerConsegnaContenutiApplicativi') AND
  1368.          *  sa.tipo_consegna='Connettore' AND
  1369.          *  m.id_messaggio=sa.id_messaggio AND
  1370.          *  m.proprietario<>'GestoreMessaggi'
  1371.          *  group by sa.servizio_applicativo
  1372.          **/
  1373.        
  1374.         ISQLQueryObject sqlQueryObjectCoda = SQLObjectFactory.createSQLQueryObject(this.tipoDatabase);
  1375.        
  1376.         sqlQueryObjectCoda.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,aliasTableServiziApplicativi);
  1377.         sqlQueryObjectCoda.addFromTable(GestoreMessaggi.MESSAGGI,aliasTableMessaggi);
  1378.        
  1379.         sqlQueryObjectCoda.addSelectAliasField(getIntZeroValue(),StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA);
  1380.         sqlQueryObjectCoda.addSelectCountField(StatoConsegnaAsincrona.ALIAS_IN_CODA);
  1381.         sqlQueryObjectCoda.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_VECCHIO);
  1382.         sqlQueryObjectCoda.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_RECENTE);
  1383.         sqlQueryObjectCoda.addSelectMinField(aliasTableServiziApplicativi, GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ORA_REGISTRAZIONE, StatoConsegnaAsincrona.ALIAS_IN_CODA_VECCHIO);
  1384.         sqlQueryObjectCoda.addSelectMaxField(aliasTableServiziApplicativi, GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ORA_REGISTRAZIONE, StatoConsegnaAsincrona.ALIAS_IN_CODA_RECENTE);
  1385.         sqlQueryObjectCoda.addSelectAliasField(getIntZeroValue(),StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX);
  1386.         sqlQueryObjectCoda.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_VECCHIO);
  1387.         sqlQueryObjectCoda.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_RECENTE);
  1388.         sqlQueryObjectCoda.addSelectAliasField(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_SERVIZIO_APPLICATIVO,StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO);
  1389.        
  1390.         sqlQueryObjectCoda.setANDLogicOperator(true);
  1391.         sqlQueryObjectCoda.addWhereCondition(aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ATTESA_ESITO+"=0");
  1392.         sqlQueryObjectCoda.addWhereCondition(aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ERRORE_PROCESSAMENTO_COMPACT+"='"+TimerConsegnaContenutiApplicativiThread.ID_MODULO+"'");
  1393.         sqlQueryObjectCoda.addWhereCondition(aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_TIPO_CONSEGNA+"='"+GestoreMessaggi.CONSEGNA_TRAMITE_CONNETTORE+"'");
  1394.         sqlQueryObjectCoda.addWhereCondition(aliasTableMessaggi+"."+GestoreMessaggi.MESSAGGI_COLUMN_ID_MESSAGGIO+"="+aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ID_MESSAGGIO);
  1395.         sqlQueryObjectCoda.addWhereCondition(aliasTableMessaggi+"."+GestoreMessaggi.MESSAGGI_COLUMN_PROPRIETARIO+"<>'"+TimerGestoreMessaggi.ID_MODULO+"'");
  1396.        
  1397.         sqlQueryObjectCoda.addGroupBy(StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO);
  1398.        
  1399.        
  1400.         // ** InRiconsegna **
  1401.        
  1402.         /*
  1403.          *  select count(*) as inRiconsegna, 0 as inCoda,
  1404.          *  min(sa.ora_registrazione) as vecchioInRiconsegna, max(sa.ora_registrazione) as recenteInRiconsegna,  
  1405.          *  null::timestamp as vecchioInCoda, null::timestamp as recenteInCoda,
  1406.          *  0 as inCaricoIM, null::timestamp as vecchioInCaricoIM, null::timestamp as recenteInCaricoIM,
  1407.          *  sa.SERVIZIO_APPLICATIVO
  1408.          *  from msg_servizi_applicativi sa,messaggi m
  1409.          *  where
  1410.          *  sa.attesa_esito=0 AND
  1411.          *  (sa.errore_processamento_compact<>'TimerConsegnaContenutiApplicativi') AND
  1412.          *  sa.tipo_consegna='Connettore' AND
  1413.          *  m.id_messaggio=sa.id_messaggio AND
  1414.          *  m.proprietario<>'GestoreMessaggi'
  1415.          *  group by sa.servizio_applicativo
  1416.          **/
  1417.        
  1418.         ISQLQueryObject sqlQueryObjectRiconsegna = SQLObjectFactory.createSQLQueryObject(this.tipoDatabase);
  1419.        
  1420.         sqlQueryObjectRiconsegna.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,aliasTableServiziApplicativi);
  1421.         sqlQueryObjectRiconsegna.addFromTable(GestoreMessaggi.MESSAGGI,aliasTableMessaggi);
  1422.        
  1423.         sqlQueryObjectRiconsegna.addSelectCountField(StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA);
  1424.         sqlQueryObjectRiconsegna.addSelectAliasField(getIntZeroValue(),StatoConsegnaAsincrona.ALIAS_IN_CODA);
  1425.         sqlQueryObjectRiconsegna.addSelectMinField(aliasTableServiziApplicativi, GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ORA_REGISTRAZIONE, StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_VECCHIO);
  1426.         sqlQueryObjectRiconsegna.addSelectMaxField(aliasTableServiziApplicativi, GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ORA_REGISTRAZIONE, StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_RECENTE);
  1427.         sqlQueryObjectRiconsegna.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_CODA_VECCHIO);
  1428.         sqlQueryObjectRiconsegna.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_CODA_RECENTE);
  1429.         sqlQueryObjectRiconsegna.addSelectAliasField(getIntZeroValue(),StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX);
  1430.         sqlQueryObjectRiconsegna.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_VECCHIO);
  1431.         sqlQueryObjectRiconsegna.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_RECENTE);
  1432.         sqlQueryObjectRiconsegna.addSelectAliasField(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_SERVIZIO_APPLICATIVO,StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO);
  1433.        
  1434.         sqlQueryObjectRiconsegna.setANDLogicOperator(true);
  1435.         sqlQueryObjectRiconsegna.addWhereCondition(aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ATTESA_ESITO+"=0");
  1436.         sqlQueryObjectRiconsegna.addWhereCondition(aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ERRORE_PROCESSAMENTO_COMPACT+"<>'"+TimerConsegnaContenutiApplicativiThread.ID_MODULO+"'");
  1437.         sqlQueryObjectRiconsegna.addWhereCondition(aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_TIPO_CONSEGNA+"='"+GestoreMessaggi.CONSEGNA_TRAMITE_CONNETTORE+"'");
  1438.         sqlQueryObjectRiconsegna.addWhereCondition(aliasTableMessaggi+"."+GestoreMessaggi.MESSAGGI_COLUMN_ID_MESSAGGIO+"="+aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ID_MESSAGGIO);
  1439.         sqlQueryObjectRiconsegna.addWhereCondition(aliasTableMessaggi+"."+GestoreMessaggi.MESSAGGI_COLUMN_PROPRIETARIO+"<>'"+TimerGestoreMessaggi.ID_MODULO+"'");
  1440.        
  1441.         sqlQueryObjectRiconsegna.addGroupBy(StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO);
  1442.        
  1443.        
  1444.         // ** InMessageBox **
  1445.        
  1446.         /*
  1447.          *  select 0 as inRiconsegna, 0 as inCoda,
  1448.          *  null::timestamp as vecchioInRiconsegna, null::timestamp as recenteInRiconsegna,  
  1449.          *  null::timestamp as vecchioInCoda, null::timestamp as recenteInCoda,
  1450.          *  count(*) as inCaricoIM, min(sa.ora_registrazione) as vecchioInCaricoIM, max(sa.ora_registrazione) as recenteInCaricoIM,
  1451.          *  sa.SERVIZIO_APPLICATIVO
  1452.          *  from msg_servizi_applicativi sa,messaggi m
  1453.          *  where
  1454.          *  sa.tipo_consegna='IntegrationManager' AND
  1455.          *  m.id_messaggio=sa.id_messaggio AND
  1456.          *  m.proprietario<>'GestoreMessaggi'
  1457.          *  group by sa.servizio_applicativo
  1458.          **/
  1459.        
  1460.         ISQLQueryObject sqlQueryObjectMessageBox = SQLObjectFactory.createSQLQueryObject(this.tipoDatabase);
  1461.        
  1462.         sqlQueryObjectMessageBox.addFromTable(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI,aliasTableServiziApplicativi);
  1463.         sqlQueryObjectMessageBox.addFromTable(GestoreMessaggi.MESSAGGI,aliasTableMessaggi);
  1464.        
  1465.         sqlQueryObjectMessageBox.addSelectAliasField(getIntZeroValue(),StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA);
  1466.         sqlQueryObjectMessageBox.addSelectAliasField(getIntZeroValue(),StatoConsegnaAsincrona.ALIAS_IN_CODA);
  1467.         sqlQueryObjectMessageBox.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_VECCHIO);
  1468.         sqlQueryObjectMessageBox.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_RECENTE);
  1469.         sqlQueryObjectMessageBox.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_CODA_VECCHIO);
  1470.         sqlQueryObjectMessageBox.addSelectAliasField(getNullTimestampValue(),StatoConsegnaAsincrona.ALIAS_IN_CODA_RECENTE);
  1471.         sqlQueryObjectMessageBox.addSelectCountField(StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX);
  1472.         sqlQueryObjectMessageBox.addSelectMinField(aliasTableServiziApplicativi, GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ORA_REGISTRAZIONE, StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_VECCHIO);
  1473.         sqlQueryObjectMessageBox.addSelectMaxField(aliasTableServiziApplicativi, GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ORA_REGISTRAZIONE, StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_RECENTE);
  1474.         sqlQueryObjectMessageBox.addSelectAliasField(GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_SERVIZIO_APPLICATIVO,StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO);
  1475.        
  1476.         sqlQueryObjectMessageBox.setANDLogicOperator(true);
  1477.         sqlQueryObjectMessageBox.addWhereCondition(aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_TIPO_CONSEGNA+"='"+GestoreMessaggi.CONSEGNA_TRAMITE_INTEGRATION_MANAGER+"'");
  1478.         sqlQueryObjectMessageBox.addWhereCondition(aliasTableMessaggi+"."+GestoreMessaggi.MESSAGGI_COLUMN_ID_MESSAGGIO+"="+aliasTableServiziApplicativi+"."+GestoreMessaggi.MSG_SERVIZI_APPLICATIVI_COLUMN_ID_MESSAGGIO);
  1479.         sqlQueryObjectMessageBox.addWhereCondition(aliasTableMessaggi+"."+GestoreMessaggi.MESSAGGI_COLUMN_PROPRIETARIO+"<>'"+TimerGestoreMessaggi.ID_MODULO+"'");
  1480.        
  1481.         sqlQueryObjectMessageBox.addGroupBy(StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO);

  1482.        
  1483.         // ** UNION **
  1484.        
  1485.         /**
  1486.          * select CURRENT_TIMESTAMP as now,
  1487.          * max(inRiconsegna) as inRiconsegna, max(inCoda) as inCoda,
  1488.          * min(vecchioInRiconsegna) as vecchioInRiconsegna, max(recenteInRiconsegna) as recenteInRiconsegna,
  1489.          * min(vecchioInCoda) as vecchioInCoda, max(recenteInCoda) as recenteInCoda,
  1490.          * max(inCaricoIM) as inCaricoIM, min(vecchioInCaricoIM) as vecchioInCaricoIM, max(recenteInCaricoIM) as recenteInCaricoIM,  
  1491.          * servizio_applicativo from (
  1492.                 QUERY_IN_CODA
  1493.             UNION ALL
  1494.                 QUERY_IN_RICONSEGNA
  1495.             UNION ALL
  1496.                 QUERY_MESSAGE_BOX
  1497.            ) as query group by servizio_applicativo;
  1498.          */
  1499.        
  1500.         ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.tipoDatabase);
  1501.        
  1502.         sqlQueryObject.addSelectAliasField("CURRENT_TIMESTAMP", StatoConsegnaAsincrona.ALIAS_NOW);
  1503.         sqlQueryObject.addSelectMaxField(StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA, StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA);
  1504.         sqlQueryObject.addSelectMaxField(StatoConsegnaAsincrona.ALIAS_IN_CODA, StatoConsegnaAsincrona.ALIAS_IN_CODA);
  1505.         sqlQueryObject.addSelectMinField(StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_VECCHIO, StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_VECCHIO);
  1506.         sqlQueryObject.addSelectMaxField(StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_RECENTE, StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA_RECENTE);
  1507.         sqlQueryObject.addSelectMinField(StatoConsegnaAsincrona.ALIAS_IN_CODA_VECCHIO, StatoConsegnaAsincrona.ALIAS_IN_CODA_VECCHIO);
  1508.         sqlQueryObject.addSelectMaxField(StatoConsegnaAsincrona.ALIAS_IN_CODA_RECENTE, StatoConsegnaAsincrona.ALIAS_IN_CODA_RECENTE);
  1509.         sqlQueryObject.addSelectMaxField(StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX, StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX);
  1510.         sqlQueryObject.addSelectMinField(StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_VECCHIO, StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_VECCHIO);
  1511.         sqlQueryObject.addSelectMaxField(StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_RECENTE, StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX_RECENTE);    
  1512.         sqlQueryObject.addSelectAliasField(StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO, StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO);
  1513.        
  1514.         sqlQueryObject.addGroupBy(StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO);
  1515.        
  1516.         if(filtro!=null) {
  1517.             if(filtro.isOrderByInCoda()) {
  1518.                 sqlQueryObject.addOrderBy(StatoConsegnaAsincrona.ALIAS_IN_CODA, false);
  1519.             }
  1520.             if(filtro.isOrderByInRiconsegna()) {
  1521.                 sqlQueryObject.addOrderBy(StatoConsegnaAsincrona.ALIAS_IN_RICONSEGNA, false);
  1522.             }
  1523.             if(filtro.isOrderByInMessageBox()) {
  1524.                 sqlQueryObject.addOrderBy(StatoConsegnaAsincrona.ALIAS_IN_MESSAGE_BOX, false);
  1525.             }
  1526.         }
  1527.         sqlQueryObject.addOrderBy(StatoConsegnaAsincrona.ALIAS_SERVIZIO_APPLICATIVO, true);
  1528.            
  1529.         return sqlQueryObject.createSQLUnion(true, sqlQueryObjectRiconsegna, sqlQueryObjectCoda, sqlQueryObjectMessageBox);
  1530.     }
  1531.    
  1532.     private String getNullTimestampValue() {
  1533.         if(TipiDatabase.POSTGRESQL.equals(this.tipoDatabase)) {
  1534.             return "null::timestamp";
  1535.         }
  1536.         else {
  1537.             return "null";
  1538.         }
  1539.     }
  1540.     private String getIntZeroValue() {
  1541.         return "0";
  1542.     }
  1543. }