AbstractStatistiche.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.monitor.engine.statistic;

  21. import java.util.ArrayList;
  22. import java.util.Calendar;
  23. import java.util.Date;
  24. import java.util.HashMap;
  25. import java.util.List;
  26. import java.util.Map;

  27. import org.openspcoop2.core.commons.dao.DAOFactoryProperties;
  28. import org.openspcoop2.core.constants.CostantiDB;
  29. import org.openspcoop2.core.constants.TipoPdD;
  30. import org.openspcoop2.core.id.IDServizio;
  31. import org.openspcoop2.core.registry.driver.IDServizioFactory;
  32. import org.openspcoop2.core.statistiche.Statistica;
  33. import org.openspcoop2.core.statistiche.StatisticaContenuti;
  34. import org.openspcoop2.core.statistiche.constants.TipoIntervalloStatistico;
  35. import org.openspcoop2.core.statistiche.dao.IServiceManager;
  36. import org.openspcoop2.core.statistiche.dao.IStatisticaInfoService;
  37. import org.openspcoop2.core.statistiche.dao.IStatisticaInfoServiceSearch;
  38. import org.openspcoop2.core.statistiche.model.StatisticaModel;
  39. import org.openspcoop2.core.transazioni.constants.PddRuolo;
  40. import org.openspcoop2.core.transazioni.dao.ITransazioneServiceSearch;
  41. import org.openspcoop2.generic_project.beans.ConstantField;
  42. import org.openspcoop2.generic_project.beans.FunctionField;
  43. import org.openspcoop2.generic_project.beans.Union;
  44. import org.openspcoop2.generic_project.beans.UnionExpression;
  45. import org.openspcoop2.generic_project.dao.IDBServiceUtilities;
  46. import org.openspcoop2.generic_project.dao.IServiceSearchWithoutId;
  47. import org.openspcoop2.generic_project.dao.IServiceWithoutId;
  48. import org.openspcoop2.generic_project.exception.ExpressionException;
  49. import org.openspcoop2.generic_project.exception.ExpressionNotImplementedException;
  50. import org.openspcoop2.generic_project.exception.MultipleResultException;
  51. import org.openspcoop2.generic_project.exception.NotFoundException;
  52. import org.openspcoop2.generic_project.exception.NotImplementedException;
  53. import org.openspcoop2.generic_project.exception.ServiceException;
  54. import org.openspcoop2.generic_project.expression.IExpression;
  55. import org.openspcoop2.generic_project.expression.Index;
  56. import org.openspcoop2.generic_project.expression.impl.sql.ISQLFieldConverter;
  57. import org.openspcoop2.monitor.engine.condition.EsitoUtils;
  58. import org.openspcoop2.monitor.engine.condition.FilterImpl;
  59. import org.openspcoop2.monitor.engine.config.BasicServiceLibrary;
  60. import org.openspcoop2.monitor.engine.config.BasicServiceLibraryReader;
  61. import org.openspcoop2.monitor.engine.config.StatisticsServiceLibrary;
  62. import org.openspcoop2.monitor.engine.config.StatisticsServiceLibraryReader;
  63. import org.openspcoop2.monitor.engine.config.TransactionServiceLibrary;
  64. import org.openspcoop2.monitor.engine.config.TransactionServiceLibraryReader;
  65. import org.openspcoop2.monitor.engine.config.statistiche.ConfigurazioneStatistica;
  66. import org.openspcoop2.monitor.engine.config.statistiche.dao.IConfigurazioneStatisticaService;
  67. import org.openspcoop2.monitor.engine.constants.Costanti;
  68. import org.openspcoop2.monitor.engine.dynamic.DynamicFactory;
  69. import org.openspcoop2.monitor.engine.dynamic.IDynamicLoader;
  70. import org.openspcoop2.monitor.sdk.constants.StatisticType;
  71. import org.openspcoop2.monitor.sdk.exceptions.StatisticException;
  72. import org.openspcoop2.monitor.sdk.plugins.IStatisticProcessing;
  73. import org.openspcoop2.monitor.sdk.statistic.StatisticResourceFilter;
  74. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  75. import org.openspcoop2.protocol.sdk.constants.EsitoTransazioneName;
  76. import org.openspcoop2.protocol.utils.EsitiProperties;
  77. import org.openspcoop2.utils.BooleanNullable;
  78. import org.openspcoop2.utils.LoggerWrapperFactory;
  79. import org.openspcoop2.utils.TipiDatabase;
  80. import org.openspcoop2.utils.date.DateManager;
  81. import org.openspcoop2.utils.sql.Case;
  82. import org.openspcoop2.utils.sql.CastColumnType;
  83. import org.openspcoop2.utils.sql.ISQLQueryObject;
  84. import org.openspcoop2.utils.sql.SQLObjectFactory;
  85. import org.slf4j.Logger;



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

  94.     protected Logger logger = LoggerWrapperFactory.getLogger(AbstractStatistiche.class);
  95.     private void logDebug(String msg) {
  96.         if(this.logger!=null) {
  97.             this.logger.debug(msg);
  98.         }
  99.     }
  100.     private void logDebug(String msg, Throwable e) {
  101.         if(this.logger!=null) {
  102.             this.logger.debug(msg,e);
  103.         }
  104.     }
  105.     private void logError(String msg, Throwable e) {
  106.         if(this.logger!=null) {
  107.             this.logger.error(msg,e);
  108.         }
  109.     }
  110.     protected boolean debug = false;
  111.     protected boolean useUnionForLatency = true;
  112.     protected boolean generazioneStatisticheCustom = false;
  113.     protected boolean analisiTransazioniCustom = false;
  114.     protected IServiceManager statisticheSM = null;
  115.     protected IServiceWithoutId<?> statisticaServiceDAO = null;
  116.     protected IServiceSearchWithoutId<?> statisticaServiceSearchDAO = null;
  117.     protected StatisticaModel model = null;
  118.     private IStatisticaInfoServiceSearch statisticaInfoSearchDAO = null;
  119.     private IStatisticaInfoService statisticaInfoDAO = null;
  120.     private org.openspcoop2.core.transazioni.dao.IServiceManager transazioniSM = null;
  121.     private ITransazioneServiceSearch transazioneSearchDAO = null;
  122.     private org.openspcoop2.monitor.engine.config.statistiche.dao.IServiceManager pluginsStatisticheSM = null;
  123.     private org.openspcoop2.core.plugins.dao.IServiceManager pluginsBaseSM = null;
  124.     private org.openspcoop2.core.commons.search.dao.IServiceManager utilsSM = null;
  125.     private org.openspcoop2.monitor.engine.config.transazioni.dao.IServiceManager pluginsTransazioniSM;
  126.     @SuppressWarnings("unused")
  127.     private IConfigurazioneStatisticaService confStatisticaDAO =null;
  128.     private TipiDatabase databaseType;
  129.     private StatisticsForceIndexConfig forceIndexConfig;

  130.     private static final String SUFFIX_NON_INIZIALIZZATO = "] non inizializzato";

  131.     private boolean initialized = false;
  132.    
  133.     AbstractStatistiche(){
  134.        
  135.     }
  136.     protected AbstractStatistiche(Logger logger,boolean debug,boolean useUnionForLatency,
  137.             boolean generazioneStatisticheCustom, boolean analisiTransazioniCustom,
  138.             StatisticsForceIndexConfig forceIndexConfig,
  139.             org.openspcoop2.core.statistiche.dao.IServiceManager statisticheSM,
  140.             org.openspcoop2.core.transazioni.dao.IServiceManager transazioniSM,
  141.             org.openspcoop2.monitor.engine.config.statistiche.dao.IServiceManager pluginsStatisticheSM,
  142.             org.openspcoop2.core.plugins.dao.IServiceManager pluginsBaseSM,
  143.             org.openspcoop2.core.commons.search.dao.IServiceManager utilsSM,
  144.             org.openspcoop2.monitor.engine.config.transazioni.dao.IServiceManager pluginsTransazioniSM){
  145.         if(logger!=null){
  146.             this.logger = logger;
  147.         }
  148.         this.debug = debug;
  149.         this.useUnionForLatency = useUnionForLatency;
  150.         this.generazioneStatisticheCustom = generazioneStatisticheCustom;
  151.         this.analisiTransazioniCustom = analisiTransazioniCustom;
  152.        
  153.         try {
  154.             if(statisticheSM==null){
  155.                 throw new ServiceException("StatisticheServiceManager ["+org.openspcoop2.core.statistiche.dao.IServiceManager.class.getName()+SUFFIX_NON_INIZIALIZZATO);
  156.             }
  157.             if(transazioniSM==null){
  158.                 throw new ServiceException("TransazioniServiceManager ["+org.openspcoop2.core.transazioni.dao.IServiceManager.class.getName()+SUFFIX_NON_INIZIALIZZATO);
  159.             }
  160.            
  161.             this.statisticheSM = statisticheSM;
  162.             this.statisticaInfoSearchDAO = this.statisticheSM.getStatisticaInfoServiceSearch();
  163.             this.statisticaInfoDAO = this.statisticheSM.getStatisticaInfoService();

  164.             this.databaseType = DAOFactoryProperties.getInstance(this.logger).getTipoDatabaseEnum(org.openspcoop2.core.statistiche.utils.ProjectInfo.getInstance());
  165.            
  166.             this.transazioniSM = transazioniSM;
  167.             this.transazioneSearchDAO = this.transazioniSM.getTransazioneServiceSearch();

  168.             if(this.generazioneStatisticheCustom){
  169.                
  170.                 if(pluginsStatisticheSM==null){
  171.                     throw new ServiceException("PluginStatisticheServiceManager ["+org.openspcoop2.monitor.engine.config.statistiche.dao.IServiceManager.class.getName()+SUFFIX_NON_INIZIALIZZATO);
  172.                 }
  173.                 this.pluginsStatisticheSM = pluginsStatisticheSM;
  174.                 this.confStatisticaDAO  = this. pluginsStatisticheSM.getConfigurazioneStatisticaService();
  175.                
  176.                 if(utilsSM==null){
  177.                     throw new ServiceException("UtilsServiceManager ["+org.openspcoop2.core.commons.search.dao.IServiceManager.class.getName()+SUFFIX_NON_INIZIALIZZATO);
  178.                 }
  179.                 this.utilsSM = utilsSM;
  180.                
  181.                 if(pluginsBaseSM==null){
  182.                     throw new ServiceException("PluginBaseServiceManager ["+org.openspcoop2.core.plugins.dao.IServiceManager.class.getName()+SUFFIX_NON_INIZIALIZZATO);
  183.                 }
  184.                 this.pluginsBaseSM = pluginsBaseSM;
  185.                
  186.                 if(this.analisiTransazioniCustom){
  187.                     if(pluginsTransazioniSM==null){
  188.                         throw new ServiceException("PluginTransazioniServiceManager ["+org.openspcoop2.monitor.engine.config.transazioni.dao.IServiceManager.class.getName()+SUFFIX_NON_INIZIALIZZATO);
  189.                     }
  190.                     this.pluginsTransazioniSM = pluginsTransazioniSM;
  191.                 }
  192.             }
  193.            
  194.             this.forceIndexConfig = forceIndexConfig;
  195.            
  196.             this.initialized = true;
  197.            
  198.         } catch (Exception e) {
  199.             this.logError(e.getMessage(),e);
  200.         }
  201.     }

  202.     public boolean isDebug() {
  203.         return this.debug;
  204.     }
  205.    
  206.     protected TipiDatabase getDatabaseType() {
  207.         return this.databaseType;
  208.     }
  209.    
  210.     public void printDate(Date d){
  211.         Calendar c = Calendar.getInstance();
  212.         c.setTime(d);
  213.         printCalendar(c);
  214.     }

  215.     public void printCalendar(Calendar c){
  216.         StringBuilder bf = new StringBuilder();
  217.         bf.append("DATA ["+c.getTime().toString()+"]");
  218.         bf.append(" DATA in millisecondi: "+c.getTime().getTime());
  219.         bf.append(" YEAR:"+c.get(Calendar.YEAR));
  220.         bf.append(" MONTH:"+(c.get(Calendar.MONTH)+1));
  221.         bf.append(" DAY_OF_MONTH:"+c.get(Calendar.DAY_OF_MONTH));
  222.         bf.append(" HOUR_OF_DAY:"+c.get(Calendar.HOUR_OF_DAY));
  223.         bf.append(" MINUTE:"+c.get(Calendar.MINUTE));
  224.         bf.append(" SECOND:"+c.get(Calendar.SECOND));
  225.         bf.append(" MILLISECOND:"+c.get(Calendar.MILLISECOND));
  226.         this.logDebug(bf.toString());
  227.     }

  228.     // METODI ASTRATTI
  229.     public abstract Date truncDate(Date date,boolean print);

  230.     public abstract Date incrementDate(Date date,boolean print);

  231.     public abstract Date decrementDate(Date date,boolean print);

  232.     public Date decrementDate1Millisecond(Date date){
  233.         Calendar cTmp = Calendar.getInstance();
  234.         cTmp.setTime(date);
  235.         cTmp.add(Calendar.MILLISECOND, -1);
  236.         return cTmp.getTime();
  237.     }

  238.     public abstract String getIntervalloStatistica(Date date,boolean print);

  239.     private String getIntervalloStatistica(Date date){
  240.         Date d = this.incrementDate(date, false);
  241.         return this.getIntervalloStatistica(d, false);
  242.     }

  243.     public abstract TipoIntervalloStatistico getTipoStatistiche();

  244.     public abstract void callStatisticPluginMethod(IStatisticProcessing statProcessing, StatisticBean stat) throws StatisticException;

  245.     public abstract String getStatisticPluginMethodName() throws StatisticException;


  246.     public void generaStatistiche( boolean gestioneUltimoIntervallo, long waitMsBeforeNextInterval, boolean waitStatiInConsegna) throws Exception{

  247.         if(!this.initialized){
  248.             throw new ServiceException("Inizializzazione fallita (verificare errori precedenti)");
  249.         }

  250.         try{
  251.             if(this.debug)
  252.                 this.logDebug("********************************************* "+this.getTipoStatistiche()+" *******************************************************");

  253.             // Ottengo data in cui e' stato fatto girare l'ultima volta la procedura di popolamento
  254.             // Tale data viene troncata in funzione della statistica che sto eseguendo
  255.             // (La prima insert potrebbe contenere informazioni maggiori di quelle che servono: es. in statistiche giornaliere ci potrebbero essere ora,minuti e secondi)
  256.             Date dataUltimaGenerazioneStatistiche = StatisticsInfoUtils.readDataUltimaGenerazioneStatistiche(this.statisticaInfoSearchDAO, this.getTipoStatistiche(), this.logger);
  257.             dataUltimaGenerazioneStatistiche = truncDate(dataUltimaGenerazioneStatistiche, false);
  258.             // Decremento la data di 1 millisecondo in modo da generare poi il SQL nella forma
  259.             // statistiche per transazioni emessi in data > dataUltimaGenerazioneStatistiche
  260.             dataUltimaGenerazioneStatistiche = this.decrementDate1Millisecond(dataUltimaGenerazioneStatistiche);

  261.             Date dataAvvioBatch = DateManager.getDate();

  262.             // Now
  263.             // Tale data viene troncata in funzione della statistica che sto eseguendo
  264.             Date now = new Date();
  265.             now = truncDate(now,false);
  266.             now = this.decrementDate1Millisecond(now);
  267.             Date nowMenoUno = decrementDate(now, false);

  268.            
  269.             // Incremento la data sul database solamente se non sono avvenuti errori durante la generazione, altrimenti dovro' ricalcolarle tutti gli intervalli da quanto e' successo l'errore
  270.             boolean saveDataStatistica = true;
  271.            
  272.            
  273.             // Genero statistiche per transazioni emessi in data > dataUltimaGenerazioneStatistiche AND data <= now
  274.             while(dataUltimaGenerazioneStatistiche.compareTo(nowMenoUno) <= 0){

  275.                 // genera
  276.                 boolean generazioneCompletataConSuccesso = generaStatistica(dataUltimaGenerazioneStatistiche,
  277.                         dataAvvioBatch, waitMsBeforeNextInterval,
  278.                         waitStatiInConsegna);
  279.                 if(!generazioneCompletataConSuccesso) {
  280.                     saveDataStatistica = false;
  281.                 }
  282.                                                
  283.                 // increment
  284.                 dataUltimaGenerazioneStatistiche = incrementDate(dataUltimaGenerazioneStatistiche, false);
  285.                 if(this.debug)
  286.                     this.logDebug("-----------------------");

  287.                 // Salvo nuova data di ultima generazione statistiche (entro nel prossimo intervallo)
  288.                 if(saveDataStatistica) {
  289.                     Date next = this.truncDate(this.incrementDate(dataUltimaGenerazioneStatistiche, false),false);
  290.                     if(this.debug)
  291.                         this.logDebug("Save data ultima generazione statistiche: "+next.toString());
  292.                     StatisticsInfoUtils.updateDataUltimaGenerazioneStatistiche(this.statisticaInfoSearchDAO, this.statisticaInfoDAO,
  293.                             this.getTipoStatistiche(), this.logger, next);
  294.                 }
  295.                
  296.             }


  297.             // Genero statistiche parziali della data di oggi
  298.             if(gestioneUltimoIntervallo){

  299.                 Date dataUltimoIntervallo = dataUltimaGenerazioneStatistiche;

  300.                 // genera
  301.                 generaStatistica(dataUltimoIntervallo,
  302.                         dataAvvioBatch, -1,
  303.                         false);
  304.                
  305.             }

  306.         }catch(Exception e){
  307.             this.logError(e.getMessage(), e);
  308.             throw e;
  309.         }
  310.     }

  311.     private boolean generaStatistica(Date dataUltimaGenerazioneStatistiche,
  312.             Date dataAvvioBatch, long waitMsBeforeNextInterval,
  313.             boolean waitStatiInConsegna) {
  314.        
  315.         // Algoritmo
  316.         // Per la data in fase di aggiornamento:
  317.         // - 1) si elimina eventuali record rimasti "sporchi" (stato_record <1)
  318.         // - 2) i record esistenti nell'intervallo vengono portati al valore stato_record=2
  319.         // - 3) i nuovi record aggiunti vengono creati con stato_record=0
  320.         // - 4) si fa un unico comando di update nell'intervallo con CASE WHEN stato_record==2 THEN -2 WHEN stato_record==0 THEN 1
  321.         // - 5) si eliminano i record nell'intervallo con stato_record=-2
  322.        
  323.         /**if(dataUltimaGenerazioneStatistiche.compareTo(nowMenoUno) == 0){*/
  324.         // L'IF sopra non lo devo fare, se spengo la macchina, e la riaccendo dopo due ore, l'eliminazione delle statistiche gia' generate riguarda nowMenoDue
  325.         // Se ho la stessa data devo eliminare l'intervallo, posso gia' averlo generato
  326.         // Eliminazione (Fase 1)
  327.         if(this.debug)
  328.             this.logDebug("----------- pulizia Fase1 (DataUguale) ------------");
  329.         boolean esito = this.deleteFisicoStatistiche( TipoPdD.DELEGATA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_VALIDO, false);
  330.         if(!esito) {
  331.             return false;
  332.         }
  333.         if(this.debug)
  334.             this.logDebug("------------ pulizia Fase1 (DataUguale) -----------");
  335.         esito = this.deleteFisicoStatistiche( TipoPdD.APPLICATIVA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_VALIDO, false);
  336.         if(!esito) {
  337.             return false;
  338.         }
  339.         //}

  340.         // Aggiornamento (Fase 2)
  341.         if(this.debug)
  342.             this.logDebug("----------- aggiornamento Fase2 (DataUguale) ------------");
  343.         esito = this.updateStatoRecordStatistiche(TipoPdD.DELEGATA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_ANCORA_VALIDO_IN_FASE_DI_AGGIORNAMENTO);
  344.         if(!esito) {
  345.             return false;
  346.         }
  347.         if(this.debug)
  348.             this.logDebug("------------ aggiornamento Fase2 (DataUguale) -----------");
  349.         esito = this.updateStatoRecordStatistiche( TipoPdD.APPLICATIVA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_ANCORA_VALIDO_IN_FASE_DI_AGGIORNAMENTO);
  350.         if(!esito) {
  351.             return false;
  352.         }
  353.        
  354.         // Generazione (Fase 3)
  355.         BooleanNullable delegataStatiInCorso = BooleanNullable.NULL();
  356.         if(this.debug)
  357.             this.logDebug("----------- generazione Fase3 (DataUguale) ------------");
  358.         if(this.useUnionForLatency) {
  359.             esito = this.generaStatisticheUnion( TipoPdD.DELEGATA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_IN_AGGIORNAMENTO, delegataStatiInCorso );
  360.         }
  361.         else {
  362.             esito = this.generaStatistiche( TipoPdD.DELEGATA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_IN_AGGIORNAMENTO, delegataStatiInCorso );
  363.         }
  364.         if(!esito) {
  365.             return false;
  366.         }
  367.         BooleanNullable applicativaStatiInCorso = BooleanNullable.NULL();      
  368.         if(this.debug)
  369.             this.logDebug("------------ generazione Fase3 (DataUguale) -----------");
  370.         if(this.useUnionForLatency) {
  371.             esito = this.generaStatisticheUnion( TipoPdD.APPLICATIVA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_IN_AGGIORNAMENTO, applicativaStatiInCorso );
  372.         }
  373.         else {
  374.             esito = this.generaStatistiche( TipoPdD.APPLICATIVA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_IN_AGGIORNAMENTO, applicativaStatiInCorso );
  375.         }
  376.         if(!esito) {
  377.             return false;
  378.         }

  379.         // Promozione Record (Fase4)
  380.         boolean unicaPromozione = true; // deve essere un unico comando sql
  381.         if(unicaPromozione) {
  382.             if(this.debug)
  383.                 this.logDebug("----------- promozione Fase4 (DataUguale) ------------");
  384.             esito = this.updateStatoRecordStatistiche( null, dataUltimaGenerazioneStatistiche,
  385.                     CostantiDB.STATISTICHE_STATO_RECORD_ANCORA_VALIDO_IN_FASE_DI_AGGIORNAMENTO, CostantiDB.STATISTICHE_STATO_RECORD_ELIMINATO,
  386.                     CostantiDB.STATISTICHE_STATO_RECORD_IN_AGGIORNAMENTO, CostantiDB.STATISTICHE_STATO_RECORD_VALIDO);
  387.             if(!esito) {
  388.                 return false;
  389.             }
  390.         }
  391.         else {
  392.             if(this.debug)
  393.                 this.logDebug("----------- promozione Fase4 (DataUguale) ------------");
  394.             esito = this.updateStatoRecordStatistiche( TipoPdD.DELEGATA, dataUltimaGenerazioneStatistiche,
  395.                     CostantiDB.STATISTICHE_STATO_RECORD_ANCORA_VALIDO_IN_FASE_DI_AGGIORNAMENTO, CostantiDB.STATISTICHE_STATO_RECORD_ELIMINATO,
  396.                     CostantiDB.STATISTICHE_STATO_RECORD_IN_AGGIORNAMENTO, CostantiDB.STATISTICHE_STATO_RECORD_VALIDO);
  397.             if(!esito) {
  398.                 return false;
  399.             }
  400.             if(this.debug)
  401.                 this.logDebug("------------ promozione Fase4 (DataUguale) -----------");
  402.             esito = this.updateStatoRecordStatistiche( TipoPdD.APPLICATIVA, dataUltimaGenerazioneStatistiche,
  403.                     CostantiDB.STATISTICHE_STATO_RECORD_ANCORA_VALIDO_IN_FASE_DI_AGGIORNAMENTO, CostantiDB.STATISTICHE_STATO_RECORD_ELIMINATO,
  404.                     CostantiDB.STATISTICHE_STATO_RECORD_IN_AGGIORNAMENTO, CostantiDB.STATISTICHE_STATO_RECORD_VALIDO);
  405.             if(!esito) {
  406.                 return false;
  407.             }
  408.         }

  409.         // Eliminazione (Fase 5)
  410.         boolean pulituraOk = true;
  411.         if(this.debug)
  412.             this.logDebug("----------- eliminazione Fase5 (DataUguale) ------------");
  413.         esito = this.deleteFisicoStatistiche( TipoPdD.DELEGATA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_ELIMINATO, true);
  414.         if(!esito) {
  415.             pulituraOk=false;
  416.         }
  417.         if(this.debug)
  418.             this.logDebug("------------ eliminazione Fase5 (DataUguale) -----------");
  419.         esito = this.deleteFisicoStatistiche( TipoPdD.APPLICATIVA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_ELIMINATO, true);
  420.         if(!esito) {
  421.             pulituraOk=false;
  422.         }
  423.        
  424.         // Verifica data attuale e record incontrati
  425.         /**System.out.println("CHECK ms'"+waitMsBeforeNextInterval+"' stati:"+waitStatiInConsegna+"");*/
  426.         if(waitMsBeforeNextInterval>0) {
  427.             Date dateNext = incrementDate(dataUltimaGenerazioneStatistiche, false);
  428.             Date valid = new Date( dataAvvioBatch.getTime() - waitMsBeforeNextInterval );
  429.             boolean block = !dateNext.before(valid);
  430.             /**System.out.println("CHECK STAT NOW["+org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(DateManager.getDate())+"] VALID["+
  431.                     org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(valid)+"] < ["+
  432.                     org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(dateNext)+"]: "+block);*/
  433.             if(block) {
  434.                 if(this.debug)
  435.                     this.logDebug("Tradeoff '"+waitMsBeforeNextInterval+"'; next interval update disabled");
  436.                 return false;
  437.             }
  438.         }
  439.         if(waitStatiInConsegna) {
  440.             if(delegataStatiInCorso!=null && delegataStatiInCorso.getValue()!=null && delegataStatiInCorso.getValue().booleanValue()) {
  441.                 if(this.debug)
  442.                     this.logDebug("Trovate transazioni di fruizioni ancora in consegna; next interval update disabled");
  443.                 return false;
  444.             }
  445.             if(applicativaStatiInCorso!=null && applicativaStatiInCorso.getValue()!=null && applicativaStatiInCorso.getValue().booleanValue()) {
  446.                 if(this.debug)
  447.                     this.logDebug("Trovate transazioni di erogazioni ancora in consegna; next interval update disabled");
  448.                 return false;
  449.             }
  450.         }
  451.        
  452.         return pulituraOk;
  453.     }

  454.    
  455.    
  456.    
  457.     // ---- GENERAZIONE STATISTICHE BASE ----
  458.    
  459.     private boolean generaStatisticheUnion(TipoPdD tipoPdD, Date data, int statoRecord, BooleanNullable statiInCorso) {

  460.         boolean generazioneOk = true;
  461.        
  462.         if(this.debug){
  463.             this.logDebug("Generazione statistiche (union) ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") ...");
  464.         }
  465.         try{
  466.             ISQLFieldConverter fieldConverter = ((IDBServiceUtilities<?>)this.transazioneSearchDAO).getFieldConverter();
  467.            
  468.             // ** Select field **
  469.             List<FunctionField> selectList = new ArrayList<>();
  470.             StatisticsUtils.addSelectFieldCountTransaction(selectList);
  471.             StatisticsUtils.addSelectFieldSizeTransaction(tipoPdD, selectList);
  472.            
  473.             List<FunctionField> selectListConLatenze = new ArrayList<>();
  474.             selectListConLatenze.addAll(selectList);
  475.             StatisticsUtils.addSelectFunctionFieldLatencyTransaction(tipoPdD, fieldConverter, selectListConLatenze);
  476.            
  477.             List<FunctionField> selectListSenzaLatenze = new ArrayList<>();
  478.             selectListSenzaLatenze.addAll(selectList);
  479.             List<ConstantField> selectListCostantiLatenze = new ArrayList<>();
  480.             StatisticsUtils.addSelectConstantFieldLatencyTransaction(tipoPdD, fieldConverter, selectListCostantiLatenze);

  481.             // ** Where **
  482.             // Creo intervallo
  483.             Date dateNext = incrementDate(data, false);
  484.            
  485.             IExpression exprConLatenze = this.transazioneSearchDAO.newExpression();
  486.             StatisticsUtils.setExpressionNotNullDate(this.transazioneSearchDAO, exprConLatenze, data, dateNext, tipoPdD, null, fieldConverter);
  487.            
  488.             IExpression exprSenzaLatenze = this.transazioneSearchDAO.newExpression();
  489.             StatisticsUtils.setExpressionNullDate(this.transazioneSearchDAO, exprSenzaLatenze, data, dateNext, tipoPdD, null, fieldConverter);

  490.             if(this.debug){
  491.                 this.logDebug("Genero statistiche ["+this.getTipoStatistiche()+"] Intervallo date: ["+data.toString()+" - "+dateNext.toString()+"]");
  492.                 this.logDebug("Valori query (ms) tr.data_ingresso_richiesta>["+data.getTime()+"] AND tr.data_ingresso_richiesta<=["+dateNext.getTime()+"]");
  493.             }

  494.             if(this.forceIndexConfig!=null){
  495.                 if(this.forceIndexConfig.getTransazioniForceIndexGroupByNumeroDimensione()!=null){
  496.                     List<Index> listForceIndexes = this.forceIndexConfig.getTransazioniForceIndexGroupByNumeroDimensione();
  497.                     if(!listForceIndexes.isEmpty()){
  498.                         for (Index index : listForceIndexes) {
  499.                             exprConLatenze.addForceIndex(index);
  500.                             exprSenzaLatenze.addForceIndex(index);
  501.                         }
  502.                     }
  503.                 }
  504.             }
  505.            
  506.             // ** Union **
  507.            
  508.             UnionExpression latenzeUnionExpr = new UnionExpression(exprConLatenze);
  509.             for (FunctionField functionField : selectListConLatenze) {
  510.                 latenzeUnionExpr.addSelectFunctionField(functionField);
  511.             }
  512.             StatisticsUtils.addSelectUnionField(latenzeUnionExpr, fieldConverter);
  513.            
  514.             UnionExpression senzaLatenzeUnionExpr = new UnionExpression(exprSenzaLatenze);
  515.             for (FunctionField functionField : selectListSenzaLatenze) {
  516.                 senzaLatenzeUnionExpr.addSelectFunctionField(functionField);
  517.             }
  518.             for (ConstantField constantField : selectListCostantiLatenze) {
  519.                 senzaLatenzeUnionExpr.addSelectField(constantField, constantField.getAlias());
  520.             }
  521.             StatisticsUtils.addSelectUnionField(senzaLatenzeUnionExpr, fieldConverter);
  522.            
  523.             Union union = new Union();
  524.             union.setUnionAll(true);
  525.             for (String alias : latenzeUnionExpr.getReturnFieldAliases()) {
  526.                 union.addField(alias);
  527.             }
  528.            
  529.             List<Map<String, Object>> list = this.transazioneSearchDAO.union(union, latenzeUnionExpr, senzaLatenzeUnionExpr);
  530.            
  531.             for (Map<String, Object> row : list) {
  532.                
  533.                 StatisticBean stat = null;
  534.                 try {
  535.                
  536.                     // Leggo informazioni di base dalla statistica
  537.                     stat = this.readStatisticBean(data, row, fieldConverter, true);
  538.                    
  539.                     // Aggiungo informazioni sul numero di transazioni e size delle transazioni
  540.                     StatisticsUtils.updateStatisticBeanCountTransactionInfo(stat, row);
  541.                     StatisticsUtils.updateStatisticBeanSizeTransactionInfo(stat, row);
  542.                     StatisticsUtils.updateStatisticsBeanLatencyTransactionInfo(stat, row);
  543.            
  544.                     // Check stati in corso
  545.                     if(EsitoUtils.isFaseIntermedia(stat.getEsitoContesto())) {
  546.                         statiInCorso.setValue(true);
  547.                     }
  548.                    
  549.                     // Inserisco statistica
  550.                     insertStatistica(stat, statoRecord);
  551.    
  552.                     if(this.generazioneStatisticheCustom){
  553.                         createCustomStatistic(stat);
  554.                     }
  555.                    
  556.                 }catch(Throwable eSingoloRecord) {
  557.                     String r = "";
  558.                     if(stat!=null) {
  559.                         try {
  560.                             r ="\nRecord: "+stat.toString();
  561.                         }catch(Throwable tPrint) {}
  562.                     }
  563.                     this.logError("Rilevato errore durante la registrazione del singolo record di informazione statistica: "+eSingoloRecord.getMessage()+r,eSingoloRecord);
  564.                     generazioneOk = false;
  565.                 }
  566.             }


  567.         } catch (ServiceException e){
  568.             this.logError(e.getMessage(),e);
  569.             generazioneOk = false;
  570.         } catch (NotImplementedException e) {
  571.             this.logError(e.getMessage(),e);
  572.             generazioneOk = false;
  573.         } catch (ExpressionNotImplementedException e) {
  574.             this.logError(e.getMessage(),e);
  575.             generazioneOk = false;
  576.         } catch (ExpressionException e) {
  577.             this.logError(e.getMessage(),e);
  578.             generazioneOk = false;
  579.         } catch (NotFoundException e) {
  580.             if(this.debug){
  581.                 this.logDebug(e.getMessage(),e);
  582.             }
  583.         }catch (Throwable e) {
  584.             this.logError(e.getMessage(),e);
  585.             generazioneOk = false;
  586.         }  

  587.         if(this.debug){
  588.             this.logDebug("Generazione statistiche ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  589.         }
  590.                
  591.         return generazioneOk;
  592.     }
  593.    
  594.     private boolean generaStatistiche(  TipoPdD tipoPdD, Date data, int statoRecord, BooleanNullable statiInCorso) {

  595.         boolean generazioneOk = true;
  596.        
  597.         if(this.debug){
  598.             this.logDebug("Generazione statistiche ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") ...");
  599.         }
  600.         try{
  601.             IExpression expr = this.transazioneSearchDAO.newExpression();

  602.             ISQLFieldConverter fieldConverter = ((IDBServiceUtilities<?>)this.transazioneSearchDAO).getFieldConverter();
  603.            
  604.             // ** Select field **
  605.             List<FunctionField> selectList = new ArrayList<>();
  606.             StatisticsUtils.addSelectFieldCountTransaction(selectList);
  607.             StatisticsUtils.addSelectFieldSizeTransaction(tipoPdD, selectList);
  608.            
  609.             // ** Where **
  610.             // Creo intervallo
  611.             Date dateNext = incrementDate(data, false);
  612.             StatisticsUtils.setExpression(this.transazioneSearchDAO, expr, data, dateNext, tipoPdD, false, null, fieldConverter);

  613.             if(this.debug){
  614.                 this.logDebug("Genero statistiche ["+this.getTipoStatistiche()+"] Intervallo date: ["+data.toString()+" - "+dateNext.toString()+"]");
  615.                 this.logDebug("Valori query (ms) tr.data_ingresso_richiesta>["+data.getTime()+"] AND tr.data_ingresso_richiesta<=["+dateNext.getTime()+"]");
  616.             }

  617.             if(this.forceIndexConfig!=null){
  618.                 if(this.forceIndexConfig.getTransazioniForceIndexGroupByNumeroDimensione()!=null){
  619.                     List<Index> listForceIndexes = this.forceIndexConfig.getTransazioniForceIndexGroupByNumeroDimensione();
  620.                     if(!listForceIndexes.isEmpty()){
  621.                         for (Index index : listForceIndexes) {
  622.                             expr.addForceIndex(index);
  623.                         }
  624.                     }
  625.                 }
  626.             }
  627.            
  628.             List<Map<String, Object>> list = this.transazioneSearchDAO.groupBy(expr, selectList.toArray(new FunctionField[1]));

  629.             for (Map<String, Object> row : list) {
  630.                
  631.                 StatisticBean stat = null;
  632.                 try {
  633.                
  634.                     // Leggo informazioni di base dalla statistica
  635.                     stat = this.readStatisticBean(data, row, null, false);
  636.                    
  637.                     // Aggiungo informazioni sul numero di transazioni e size delle transazioni
  638.                     StatisticsUtils.updateStatisticBeanCountTransactionInfo(stat, row);
  639.                     StatisticsUtils.updateStatisticBeanSizeTransactionInfo(stat, row);
  640.    
  641.                     // Aggiungo informazioni che richiedono ulteriori condizioni di where (es. date not null)
  642.                     try {
  643.                         this.addLatenze(data, dateNext, tipoPdD, stat, fieldConverter);
  644.                     }catch(Throwable eSingoloRecordAddLatenze) {
  645.                         this.logError("Rilevato errore durante la lettura delle latenze di un singolo record di informazione statistica: "+eSingoloRecordAddLatenze.getMessage()+
  646.                                 "\nRecord: "+stat.toString(),eSingoloRecordAddLatenze);
  647.                         generazioneOk = false;
  648.                     }
  649.                                    
  650.                     // Check stati in corso
  651.                     if(EsitoUtils.isFaseIntermedia(stat.getEsitoContesto())) {
  652.                         statiInCorso.setValue(true);
  653.                     }
  654.                    
  655.                     // Inserisco statistica
  656.                     insertStatistica(stat, statoRecord);
  657.    
  658.                     if(this.generazioneStatisticheCustom){
  659.                         createCustomStatistic(stat);
  660.                     }
  661.                    
  662.                 }catch(Throwable eSingoloRecord) {
  663.                     String r = "";
  664.                     if(stat!=null) {
  665.                         try {
  666.                             r ="\nRecord: "+stat.toString();
  667.                         }catch(Throwable tPrint) {}
  668.                     }
  669.                     this.logError("Rilevato errore durante la registrazione del singolo record di informazione statistica: "+eSingoloRecord.getMessage()+r,eSingoloRecord);
  670.                     generazioneOk = false;
  671.                 }
  672.             }


  673.         } catch (ServiceException e){
  674.             this.logError(e.getMessage(),e);
  675.             generazioneOk = false;
  676.         } catch (NotImplementedException e) {
  677.             this.logError(e.getMessage(),e);
  678.             generazioneOk = false;
  679.         } catch (ExpressionNotImplementedException e) {
  680.             this.logError(e.getMessage(),e);
  681.             generazioneOk = false;
  682.         } catch (ExpressionException e) {
  683.             this.logError(e.getMessage(),e);
  684.             generazioneOk = false;
  685.         } catch (NotFoundException e) {
  686.             if(this.debug){
  687.                 this.logDebug(e.getMessage(),e);
  688.             }
  689.         }catch (Throwable e) {
  690.             this.logError(e.getMessage(),e);
  691.             generazioneOk = false;
  692.         }  

  693.         if(this.debug){
  694.             this.logDebug("Generazione statistiche ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  695.         }
  696.                
  697.         return generazioneOk;
  698.     }
  699.    
  700.     private StatisticBean readStatisticBean(Date data,Map<String, Object> row, ISQLFieldConverter fieldConverter, boolean useFieldConverter) throws ExpressionException{
  701.         StatisticBean stat = new StatisticBean();

  702.         stat.setDateIntervalLeft(data);
  703.         stat.setDateIntervalRight(this.incrementDate(data, false));
  704.         Date next = this.truncDate(this.incrementDate(data, false),false);
  705.         stat.setData(next);
  706.         if(this.debug)
  707.             this.logDebug("Salvo statistica con data ["+next+"]");
  708.    
  709.         return StatisticsUtils.readStatisticBean(stat, row, fieldConverter, useFieldConverter);
  710.     }
  711.    
  712.     private void addLatenze(Date data, Date dateNext, TipoPdD tipoPdD, StatisticBean stat, ISQLFieldConverter fieldConverter) throws Exception{
  713.        
  714.         IExpression exprDateNotNull = this.transazioneSearchDAO.newExpression();
  715.         StatisticsUtils.setExpression(this.transazioneSearchDAO, exprDateNotNull, data, dateNext, tipoPdD, true, stat, fieldConverter);
  716.        
  717.         List<FunctionField> selectListDateNotNull = new ArrayList<>();
  718.        
  719.         StatisticsUtils.addSelectFunctionFieldLatencyTransaction(tipoPdD, fieldConverter, selectListDateNotNull);
  720.        
  721.         if(this.debug){
  722.             this.logDebug("Leggo ulteriormente statistiche con campi data not null ["+this.getTipoStatistiche()+"] Intervallo date: ["+data.toString()+" - "+dateNext.toString()+"]");
  723.             this.logDebug("Valori query (ms) tr.data_ingresso_richiesta>["+data.getTime()+"] AND tr.data_ingresso_richiesta<=["+dateNext.getTime()+"]");
  724.         }

  725.         try{
  726.             if(this.forceIndexConfig!=null){
  727.                 if(this.forceIndexConfig.getTransazioniForceIndexGroupByLatenze()!=null){
  728.                     List<Index> listForceIndexes = this.forceIndexConfig.getTransazioniForceIndexGroupByLatenze();
  729.                     if(!listForceIndexes.isEmpty()){
  730.                         for (Index index : listForceIndexes) {
  731.                             exprDateNotNull.addForceIndex(index);
  732.                         }
  733.                     }
  734.                 }
  735.             }
  736.            
  737.             List<Map<String, Object>> listDateNotNull = this.transazioneSearchDAO.groupBy(exprDateNotNull, selectListDateNotNull.toArray(new FunctionField[1]));
  738.            
  739.             if(listDateNotNull.size()>1){
  740.                 throw new MultipleResultException("Attesa un solo gruppo, ritornati "+listDateNotNull.size()+" gruppi");
  741.             }
  742.             Map<String, Object> row = listDateNotNull.get(0);
  743.            
  744.             StatisticsUtils.updateStatisticsBeanLatencyTransactionInfo(stat, row);
  745.            
  746.         }catch(NotFoundException notFound){
  747.             // possono non esistere
  748.             if(this.debug){
  749.                 this.logDebug(notFound.getMessage(),notFound);
  750.             }
  751.             stat.setLatenzaPorta(Costanti.INFORMAZIONE_LATENZA_NON_DISPONIBILE);
  752.             stat.setLatenzaServizio(Costanti.INFORMAZIONE_LATENZA_NON_DISPONIBILE);
  753.             stat.setLatenzaTotale(Costanti.INFORMAZIONE_LATENZA_NON_DISPONIBILE);
  754.         }
  755.     }
  756.    
  757.    
  758.    
  759.    
  760.    
  761.    
  762.     // ---- RICERCA STATISTICHE PERSONALIZZATE ----
  763.    
  764.     private void createCustomStatistic(StatisticBean stat)   {

  765.         /**IExpression expr;*/
  766.         try {
  767. /**         expr = this.confStatisticaDAO.newExpression();
  768. //          expr.and();
  769. //
  770. //          expr.equals(ConfigurazioneStatistica.model().ID_CONFIGURAZIONE_SERVIZIO_AZIONE.ID_CONFIGURAZIONE_SERVIZIO.SERVIZIO, stat.getServizio());
  771. //
  772. //          if ("*".equals(stat.getAzione())) {
  773. //              expr.and().equals(ConfigurazioneStatistica.model().ID_CONFIGURAZIONE_SERVIZIO_AZIONE.AZIONE, "*");
  774. //          } else {
  775. //              IExpression orExpr = this.confStatisticaDAO.newExpression();
  776. //              orExpr.or();
  777. //              orExpr.equals(ConfigurazioneStatistica.model().ID_CONFIGURAZIONE_SERVIZIO_AZIONE.AZIONE, "*");
  778. //              orExpr.equals(ConfigurazioneStatistica.model().ID_CONFIGURAZIONE_SERVIZIO_AZIONE.AZIONE, stat.getAzione());
  779. //
  780. //              expr.and(orExpr);
  781. //          }
  782. //          
  783. //          expr.equals(ConfigurazioneStatistica.model().ENABLED, true);
  784. //
  785. //          IPaginatedExpression pagExpr = this.confStatisticaDAO.toPaginatedExpression(expr);
  786. //          List<ConfigurazioneStatistica> list = this.confStatisticaDAO.findAll(pagExpr);*/

  787.             if(stat.getDestinatario()==null || stat.getDestinatario().getTipo()==null || stat.getDestinatario().getNome()==null){
  788.                 if(this.debug){
  789.                     this.logDebug("Statistiche personalizzate non ricercate: destinatario non presente");
  790.                 }
  791.                 return;
  792.             }
  793.             if(stat.getTipoServizio()==null || stat.getServizio()==null){
  794.                 if(this.debug){
  795.                     this.logDebug("Statistiche personalizzate non ricercate: servizio non presente");
  796.                 }
  797.                 return;
  798.             }
  799.            
  800.             IDServizio idServizio = IDServizioFactory.getInstance().
  801.                     getIDServizioFromValues(stat.getTipoServizio(), stat.getServizio(),
  802.                             stat.getDestinatario(),
  803.                             stat.getVersioneServizio());
  804.             if (!("*".equals(stat.getAzione()))) {
  805.                 idServizio.setAzione(stat.getAzione());
  806.             }
  807.            
  808.             BasicServiceLibraryReader reader = new BasicServiceLibraryReader(this.pluginsBaseSM, this.utilsSM, this.debug);
  809.             BasicServiceLibrary basicLibrary = null;
  810.             try{
  811.                 basicLibrary = reader.read(idServizio, this.logger);
  812.                 if(basicLibrary==null){
  813.                     throw new NotFoundException("Null instance return");
  814.                 }
  815.             }catch(NotFoundException notFound){
  816.                 if(this.debug){
  817.                     this.logDebug("Statistiche personalizzate non ricercate: nessuna configurazione base presente per l'IDServizio: "+idServizio,notFound);
  818.                 }
  819.                 return;
  820.             }

  821.             TransactionServiceLibrary transactionLibrary = null;
  822.             if(this.analisiTransazioniCustom){
  823.                 TransactionServiceLibraryReader transactionReader = new TransactionServiceLibraryReader(this.pluginsTransazioniSM, this.debug);
  824.                 transactionLibrary = transactionReader.readConfigurazioneTransazione(basicLibrary, this.logger);
  825.             }
  826.            
  827.             StatisticsServiceLibraryReader statReader = new StatisticsServiceLibraryReader(this.pluginsStatisticheSM, this.debug);
  828.             StatisticsServiceLibrary statLibrary = null;
  829.             try{
  830.                 statLibrary = statReader.readConfigurazioneStatistiche(basicLibrary, transactionLibrary, this.logger);
  831.                 if(statLibrary==null){
  832.                     throw new NotFoundException("Null instance return");
  833.                 }
  834.             }catch(NotFoundException notFound){
  835.                 if(this.debug){
  836.                     this.logDebug("Statistiche personalizzate non ricercate: nessuna configurazione specifica per le statistiche presente per l'IDServizio: "+idServizio,notFound);
  837.                 }
  838.                 return;
  839.             }
  840.                        
  841.             List<ConfigurazioneStatistica> list = statLibrary.mergeServiceActionSearchLibrary(false,true); // si vuole registrare nei log che un plugin è disabilitato
  842.            
  843.             for (ConfigurazioneStatistica confStat : list) {

  844.                 String classNameStatisticaPersonalizzata = confStat.getPlugin().getClassName();
  845.                 String labelStatisticaPersonalizzata = confStat.getLabel();
  846.                 if(this.debug){
  847.                     this.logDebug("*** Inizio Gestione Statistica personalizzata ("+classNameStatisticaPersonalizzata+" ["+labelStatisticaPersonalizzata+"]) ****");
  848.                 }
  849.                 stat.setIdStatistica(confStat.getIdConfigurazioneStatistica());
  850.                 stat.setPluginClassname(classNameStatisticaPersonalizzata);
  851.                 IDynamicLoader cStatPersonalizzata = DynamicFactory.getInstance().newDynamicLoader(confStat.getPlugin().getTipoPlugin(), confStat.getPlugin().getTipo(),
  852.                         classNameStatisticaPersonalizzata, this.logger);
  853.                 IStatisticProcessing statProcessing = (IStatisticProcessing) cStatPersonalizzata.newInstance();
  854.                 if(this.isEnabledStatisticTypeCustom(statProcessing)){
  855.                     if(this.debug){
  856.                         this.logDebug("---- Invocazione ["+cStatPersonalizzata.getClassName()+"."+this.getStatisticPluginMethodName()+"()] ...");
  857.                     }
  858.                     try {
  859.                         this.callStatisticPluginMethod(statProcessing, stat);
  860.                         if(this.debug){
  861.                             this.logDebug("---- Invocazione ["+cStatPersonalizzata.getClassName()+"."+this.getStatisticPluginMethodName()+"()] terminata");
  862.                         }
  863.                     } catch (Exception e) {
  864.                         this.logError("---- Invocazione ["+cStatPersonalizzata.getClassName()+"."+this.getStatisticPluginMethodName()+"()] terminata con errori: "+e.getMessage(), e);
  865.                     }
  866.                 }
  867.                 else{
  868.                     if(this.debug){
  869.                         this.logDebug("Tipo di statistica ["+this.getTipoStatistiche()+"] non abilitata nel plugin");
  870.                     }
  871.                 }
  872.                 if(this.debug){
  873.                     this.logDebug("*** Fine Gestione Statistica personalizzata ("+classNameStatisticaPersonalizzata+" ["+labelStatisticaPersonalizzata+"]) ****");
  874.                 }
  875.                
  876.             }

  877.         } catch (Exception e) {
  878.             this.logError(e.getMessage(), e);
  879.         }

  880.     }
  881.    
  882.     private boolean isEnabledStatisticTypeCustom(IStatisticProcessing statProcessing){
  883.         List<StatisticType> listEnabled = statProcessing.getEnabledStatisticType();
  884.         switch (this.getTipoStatistiche()) {
  885.             case STATISTICHE_ORARIE:
  886.                 for (StatisticType statisticType : listEnabled) {
  887.                     if(StatisticType.ORARIA.equals(statisticType)){
  888.                         return true;
  889.                     }
  890.                 }
  891.                 break;
  892.             case STATISTICHE_GIORNALIERE:
  893.                 for (StatisticType statisticType : listEnabled) {
  894.                     if(StatisticType.GIORNALIERA.equals(statisticType)){
  895.                         return true;
  896.                     }
  897.                 }
  898.                 break;
  899.             case STATISTICHE_SETTIMANALI:
  900.                 for (StatisticType statisticType : listEnabled) {
  901.                     if(StatisticType.SETTIMANALE.equals(statisticType)){
  902.                         return true;
  903.                     }
  904.                 }
  905.                 break;
  906.             case STATISTICHE_MENSILI:
  907.                 for (StatisticType statisticType : listEnabled) {
  908.                     if(StatisticType.MENSILE.equals(statisticType)){
  909.                         return true;
  910.                     }
  911.                 }
  912.                 break;
  913.         }
  914.         return false;
  915.     }
  916.    
  917.    
  918.    
  919.    
  920.     // ---- GENERAZIONE STATISTICHE PERSONALIZZATE ----
  921.     protected void generaStatisticaPersonalizzataByStato(StatisticBean stat) {
  922.         this.generaStatisticaPersonalizzata(stat, true, null, null);
  923.     }
  924.     protected void generaStatisticaPersonalizzata(StatisticBean stat,
  925.             RisorsaSemplice risorsaSemplice) {
  926.         this.generaStatisticaPersonalizzata(stat, false, risorsaSemplice, null);
  927.     }
  928.     protected void generaStatisticaPersonalizzata(StatisticBean stat,
  929.             RisorsaAggregata risorsaAggregata) {
  930.         this.generaStatisticaPersonalizzata(stat, false, null, risorsaAggregata);
  931.     }
  932.     private void generaStatisticaPersonalizzata(StatisticBean stat,
  933.             boolean gropuByStato,
  934.             RisorsaSemplice risorsaSemplice, RisorsaAggregata risorsaAggregata) {

  935.         TipoPdD tipoPdD = null;
  936.         String idStatisticaPersonalizzata = null;
  937.         Date dateStatistics = null;
  938.         try{
  939.             tipoPdD = stat.getTipoPorta();
  940.             Date dateLeft = stat.getDateIntervalLeft();
  941.             Date dateRight = stat.getDateIntervalRight();
  942.             dateStatistics = stat.getData();
  943.             idStatisticaPersonalizzata = stat.getIdStatistica();
  944.            
  945.             if(this.debug){
  946.                 this.logDebug("Generazione statistica personalizzata ["+idStatisticaPersonalizzata+"] ["+this.getTipoStatistiche()+"] ["+tipoPdD+
  947.                         "]("+this.getIntervalloStatistica(dateStatistics,false)+") ...");
  948.             }
  949.            
  950.             ISQLFieldConverter fieldConverter = ((IDBServiceUtilities<?>)this.transazioneSearchDAO).getFieldConverter();
  951.            
  952.             Map<String, StatisticaContenuti> statisticheContenuti = new HashMap<String, StatisticaContenuti>();
  953.            
  954.            
  955.             String idRisorsa = null;
  956.             StatisticResourceFilter [] risorseFiltri = null;
  957.             if(risorsaSemplice!=null){
  958.                 idRisorsa = risorsaSemplice.getIdRisorsa();
  959.                 if(risorsaSemplice.getFiltri()!=null && !risorsaSemplice.getFiltri().isEmpty()){
  960.                     risorseFiltri = risorsaSemplice.getFiltri().toArray(new StatisticResourceFilter[1]);
  961.                 }
  962.             }
  963.            
  964.            
  965.            
  966.            
  967.            
  968.             // ** Informazioni di Base (numero transazioni e dimensione) **

  969.             IExpression expr = this.transazioneSearchDAO.newExpression();
  970.            
  971.             List<FunctionField> selectList = new ArrayList<>();
  972.             StatisticsUtils.addSelectFieldCountTransaction(selectList);
  973.             StatisticsUtils.addSelectFieldSizeTransaction(tipoPdD, selectList);
  974.            
  975.             // Creo espressione
  976.             List<AliasFilter> aliases = new ArrayList<>();
  977.             if(gropuByStato){
  978.                 StatisticsUtils.setExpressionByStato(this.transazioneSearchDAO, expr, dateLeft, dateRight, tipoPdD, false, stat, fieldConverter);
  979.             }else{
  980.                 StatisticsUtils.setExpressionStatsPersonalizzate(this.transazioneSearchDAO, expr, dateLeft, dateRight, tipoPdD, false, stat, fieldConverter,
  981.                         aliases, idRisorsa, risorseFiltri);
  982.             }

  983.             // aggiungo eventuale filtro personalizzato
  984.             if(risorsaAggregata!=null && (risorsaAggregata.getFiltro() instanceof FilterImpl)){
  985.                 FilterImpl f = (FilterImpl) risorsaAggregata.getFiltro();
  986.                 expr.and(f.getExpression());
  987.             }
  988.            
  989.             if(this.debug){
  990.                 this.logDebug("Analizzo dati di base statistica personalizzata ["+idStatisticaPersonalizzata+"]  ["+this.getTipoStatistiche()+
  991.                         "] Intervallo date: ["+dateLeft.toString()+" - "+dateRight.toString()+"]");
  992.                 this.logDebug("Valori query (ms) tr.data_ingresso_richiesta>["+dateLeft.getTime()+"] AND tr.data_ingresso_richiesta<=["+dateRight.getTime()+"]");
  993.                 this.logDebug("Expr: "+expr.toString());
  994.             }

  995.             if(this.forceIndexConfig!=null){
  996.                 if(this.forceIndexConfig.getTransazioniForceIndexGroupByCustomNumeroDimensione()!=null){
  997.                     List<Index> listForceIndexes = this.forceIndexConfig.getTransazioniForceIndexGroupByCustomNumeroDimensione();
  998.                     if(!listForceIndexes.isEmpty()){
  999.                         for (Index index : listForceIndexes) {
  1000.                             expr.addForceIndex(index);
  1001.                         }
  1002.                     }
  1003.                 }
  1004.             }
  1005.            
  1006.             List<Map<String, Object>> list = this.transazioneSearchDAO.groupBy(expr, selectList.toArray(new FunctionField[1]));

  1007.             for (Map<String, Object> row : list) {
  1008.                
  1009.                 if(list.size()>1 &&
  1010.                     risorsaAggregata!=null){
  1011.                     throw new ServiceException("Localizzata più di una entry?? Comportamento non atteso per una risorsa aggregata");
  1012.                 }
  1013.                
  1014.                 // Update della statistica per quanto concerne i valori
  1015.                 StatisticaContenuti statisticaContenuti = new  StatisticaContenuti();
  1016.                 if(gropuByStato){
  1017.                     StatisticsUtils.fillStatisticsContenutiByStato(idStatisticaPersonalizzata, statisticaContenuti, row);
  1018.                 }
  1019.                 else if(risorsaSemplice!=null){
  1020.                     StatisticsUtils.fillStatisticsContenuti(idStatisticaPersonalizzata, statisticaContenuti, row, aliases, risorsaSemplice);
  1021.                 }
  1022.                 else{
  1023.                     StatisticsUtils.fillStatisticsContenuti(idStatisticaPersonalizzata, statisticaContenuti, risorsaAggregata);
  1024.                 }
  1025.                
  1026.                 // Aggiungo informazioni sul numero di transazioni e size delle transazioni
  1027.                 StatisticBean tmp = new StatisticBean();
  1028.                 tmp.setTipoPorta(stat.getTipoPorta());
  1029.                 StatisticsUtils.updateStatisticBeanCountTransactionInfo(tmp, row);
  1030.                 StatisticsUtils.updateStatisticBeanSizeTransactionInfo(tmp, row);
  1031.                 statisticaContenuti.setNumeroTransazioni((int)tmp.getRichieste());
  1032.                 statisticaContenuti.setDimensioniBytesBandaComplessiva(tmp.getBytesBandaTotale());
  1033.                 statisticaContenuti.setDimensioniBytesBandaInterna(tmp.getBytesBandaInterna());
  1034.                 statisticaContenuti.setDimensioniBytesBandaEsterna(tmp.getBytesBandaEsterna());
  1035.                
  1036.                 // Aggiungo in cache
  1037.                 String key = StatisticsUtils.buildKey(statisticaContenuti);
  1038.                 statisticheContenuti.put(key, statisticaContenuti);
  1039.                
  1040.             }
  1041.            
  1042.            
  1043.            
  1044.            
  1045.             // ** Latenze **
  1046.             try{
  1047.                 expr = this.transazioneSearchDAO.newExpression();
  1048.                
  1049.                 selectList = new ArrayList<>();
  1050.                 StatisticsUtils.addSelectFunctionFieldLatencyTransaction(tipoPdD, fieldConverter, selectList);
  1051.                
  1052.                 // Creo espressione
  1053.                 aliases = new ArrayList<>();
  1054.                 if(gropuByStato){
  1055.                     StatisticsUtils.setExpressionByStato(this.transazioneSearchDAO, expr, dateLeft, dateRight, tipoPdD, false, stat, fieldConverter);
  1056.                 }else{
  1057.                     StatisticsUtils.setExpressionStatsPersonalizzate(this.transazioneSearchDAO, expr, dateLeft, dateRight, tipoPdD, true, stat, fieldConverter,
  1058.                             aliases, idRisorsa, risorseFiltri);
  1059.                 }

  1060.                 // aggiungo eventuale filtro personalizzato
  1061.                 if(risorsaAggregata!=null && (risorsaAggregata.getFiltro() instanceof FilterImpl)){
  1062.                     FilterImpl f = (FilterImpl) risorsaAggregata.getFiltro();
  1063.                     expr.and(f.getExpression());
  1064.                 }
  1065.    
  1066.                 if(this.debug){
  1067.                     this.logDebug("Analizzo dati sulla latenza per la statistica personalizzata ["+idStatisticaPersonalizzata+"]  ["+
  1068.                             this.getTipoStatistiche()+"] Intervallo date: ["+dateLeft.toString()+" - "+dateRight.toString()+"]");
  1069.                     this.logDebug("Valori query (ms) tr.data_ingresso_richiesta>["+dateLeft.getTime()+"] AND tr.data_ingresso_richiesta<=["+dateRight.getTime()+"]");
  1070.                 }
  1071.    
  1072.                 if(this.forceIndexConfig!=null
  1073.                     && this.forceIndexConfig.getTransazioniForceIndexGroupByCustomLatenze()!=null){
  1074.                     List<Index> listForceIndexes = this.forceIndexConfig.getTransazioniForceIndexGroupByCustomLatenze();
  1075.                     if(!listForceIndexes.isEmpty()){
  1076.                         for (Index index : listForceIndexes) {
  1077.                             expr.addForceIndex(index);
  1078.                         }
  1079.                     }
  1080.                 }
  1081.                
  1082.                 list = this.transazioneSearchDAO.groupBy(expr, selectList.toArray(new FunctionField[1]));
  1083.    
  1084.                 for (Map<String, Object> row : list) {
  1085.                    
  1086.                     if(list.size()>1){
  1087.                         if(risorsaAggregata!=null){
  1088.                             throw new Exception("Localizzata più di una entry?? Comportamento non atteso per una risorsa aggregata");
  1089.                         }
  1090.                     }
  1091.                    
  1092.                     // Update della statistica per quanto concerne i valori
  1093.                     StatisticaContenuti statisticaContenuti = new  StatisticaContenuti();
  1094.                     if(gropuByStato){
  1095.                         StatisticsUtils.fillStatisticsContenutiByStato(idStatisticaPersonalizzata, statisticaContenuti, row);
  1096.                     }
  1097.                     else if(risorsaSemplice!=null){
  1098.                         StatisticsUtils.fillStatisticsContenuti(idStatisticaPersonalizzata, statisticaContenuti, row, aliases, risorsaSemplice);
  1099.                     }
  1100.                     else{
  1101.                         StatisticsUtils.fillStatisticsContenuti(idStatisticaPersonalizzata, statisticaContenuti, risorsaAggregata);
  1102.                     }
  1103.                    
  1104.                     // Prelevo dalla cache (Deve esistere per forza)
  1105.                     String key = StatisticsUtils.buildKey(statisticaContenuti);
  1106.                     statisticaContenuti = statisticheContenuti.get(key);
  1107.                     if(statisticaContenuti==null){
  1108.                         throw new ServiceException("Statistica ["+key+"] non presente in cache??");
  1109.                     }
  1110.                    
  1111.                     // Aggiorno informazioni sulla latenza
  1112.                     StatisticBean tmp = new StatisticBean();
  1113.                     StatisticsUtils.updateStatisticsBeanLatencyTransactionInfo(tmp, row);
  1114.                     statisticaContenuti.setLatenzaPorta(tmp.getLatenzaPorta());
  1115.                     statisticaContenuti.setLatenzaServizio(tmp.getLatenzaServizio());
  1116.                     statisticaContenuti.setLatenzaTotale(tmp.getLatenzaTotale());
  1117.                    
  1118.                 }
  1119.             } catch (NotFoundException e) {
  1120.                 if(this.debug){
  1121.                     this.logDebug(e.getMessage(),e);
  1122.                 }
  1123.             }
  1124.            
  1125.            
  1126.            
  1127.            
  1128.             // ** Aggiorno statistiche **
  1129.             if(this.debug){
  1130.                 this.logDebug("Aggiorno ["+statisticheContenuti.size()+"] risultati statistiche personalizzate");
  1131.             }
  1132.             if(statisticheContenuti.size()>0){
  1133.                 this.updateStatistica(stat.getId(), statisticheContenuti.values().toArray(new StatisticaContenuti[1]));
  1134.             }


  1135.         } catch (ServiceException e){
  1136.             this.logError(e.getMessage(),e);
  1137.         } catch (NotImplementedException e) {
  1138.             this.logError(e.getMessage(),e);
  1139.         } catch (ExpressionNotImplementedException e) {
  1140.             this.logError(e.getMessage(),e);
  1141.         } catch (ExpressionException e) {
  1142.             this.logError(e.getMessage(),e);
  1143.         } catch (NotFoundException e) {
  1144.             if(this.debug){
  1145.                 this.logDebug(e.getMessage(),e);
  1146.             }
  1147.         }catch (Exception e) {
  1148.             this.logError(e.getMessage(),e);
  1149.         }  

  1150.         if(this.debug){
  1151.             this.logDebug("Generazione statistica personalizzata ["+idStatisticaPersonalizzata+"] ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+
  1152.                     this.getIntervalloStatistica(dateStatistics,false)+") terminata");
  1153.         }
  1154.     }


  1155.    
  1156.    
  1157.    
  1158.    
  1159.    
  1160.    
  1161.     // ---- CRUD ----


  1162.     private boolean updateStatoRecordStatistiche( TipoPdD tipoPdD, Date data, int stato) {

  1163.         if(this.debug){
  1164.             this.logDebug("Update record statistiche allo stato '"+stato+"' ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") ...");
  1165.         }

  1166.         try{

  1167.             ISQLFieldConverter fieldConverter = ((IDBServiceUtilities<?>)this.statisticaServiceDAO).getFieldConverter();
  1168.             TipiDatabase tipoDB = fieldConverter.getDatabaseType();
  1169.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDB);
  1170.             sqlQueryObject.addUpdateTable(fieldConverter.toTable(this.model));
  1171.             sqlQueryObject.addUpdateField(fieldConverter.toColumn(this.model.STATO_RECORD, false), "?");
  1172.             sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.DATA, false)+"=?");
  1173.             sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.TIPO_PORTA, false)+"=?");
  1174.             sqlQueryObject.setANDLogicOperator(true);
  1175.            
  1176.             Date next = this.truncDate(this.incrementDate(data, false),false);
  1177.             if(this.debug){
  1178.                 this.logDebug("Aggiorno statistiche ["+this.getTipoStatistiche()+"]");
  1179.                 this.logDebug("Valori update stato record = ("+stato+") tr.data_ingresso_richiesta=["+next.getTime()+"]");
  1180.             }
  1181.             int righeModificate = this.statisticaServiceDAO.nativeUpdate(sqlQueryObject.createSQLUpdate(),
  1182.                     stato,
  1183.                     next,
  1184.                     TipoPdD.DELEGATA.equals(tipoPdD)? PddRuolo.DELEGATA.getValue() : PddRuolo.APPLICATIVA.getValue());
  1185.            
  1186.             if(this.debug){
  1187.                 this.logDebug("Modificate ["+righeModificate+"] entry");
  1188.             }

  1189.             return true;

  1190.         }catch(Throwable e){
  1191.             this.logError(e.getMessage(), e);
  1192.            
  1193.             return false;
  1194.         }
  1195.         finally {
  1196.             if(this.debug){
  1197.                 this.logDebug("Update record statistiche allo stato '"+stato+"' ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  1198.             }
  1199.         }

  1200.     }
  1201.    
  1202.     private boolean updateStatoRecordStatistiche( TipoPdD tipoPdD, Date data,
  1203.             int case1WhenStato, int case1ThenStato,
  1204.             int case2WhenStato, int case2ThenStato) {

  1205.         if(this.debug){
  1206.             this.logDebug("Update record statistiche negli stati con CASE ("+case1WhenStato+"->"+case1ThenStato+") e ("+case2WhenStato+"->"+case2ThenStato+")  ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") ...");
  1207.         }

  1208.         try{
  1209.             ISQLFieldConverter fieldConverter = ((IDBServiceUtilities<?>)this.statisticaServiceDAO).getFieldConverter();
  1210.             TipiDatabase tipoDB = fieldConverter.getDatabaseType();
  1211.             String nomeColonna = fieldConverter.toColumn(this.model.STATO_RECORD, false);
  1212.            
  1213.             Case caseSql = new Case(CastColumnType.INT);
  1214.             caseSql.addCase(nomeColonna+"=?", "?");
  1215.             caseSql.addCase(nomeColonna+"=?", "?");
  1216.            
  1217.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDB);
  1218.             sqlQueryObject.addUpdateTable(fieldConverter.toTable(this.model));
  1219.             sqlQueryObject.addUpdateField(nomeColonna, caseSql);
  1220.             sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.DATA, false)+"=?");
  1221.             if(tipoPdD!=null) {
  1222.                 sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.TIPO_PORTA, false)+"=?");
  1223.             }
  1224.             sqlQueryObject.setANDLogicOperator(true);
  1225.            
  1226.             Date next = this.truncDate(this.incrementDate(data, false),false);
  1227.             if(this.debug){
  1228.                 this.logDebug("Aggiorno statistiche ["+this.getTipoStatistiche()+"]");
  1229.                 this.logDebug("Valori update stato record CASE ("+case1WhenStato+"->"+case1ThenStato+") e ("+case2WhenStato+"->"+case2ThenStato+") tr.data_ingresso_richiesta=["+next.getTime()+"]");
  1230.             }
  1231.             List<Object> l = new ArrayList<>();
  1232.             l.add(case1WhenStato); l.add(case1ThenStato);
  1233.             l.add(case2WhenStato); l.add(case2ThenStato);
  1234.             l.add(next);
  1235.             if(tipoPdD!=null) {
  1236.                 l.add(TipoPdD.DELEGATA.equals(tipoPdD)? PddRuolo.DELEGATA.getValue() : PddRuolo.APPLICATIVA.getValue());
  1237.             }
  1238.             int righeModificate = this.statisticaServiceDAO.nativeUpdate(sqlQueryObject.createSQLUpdate(),
  1239.                     l.toArray(new Object[1]));
  1240.            
  1241.             if(this.debug){
  1242.                 this.logDebug("Modificate ["+righeModificate+"] entry");
  1243.             }

  1244.             return true;

  1245.         }catch(Throwable e){
  1246.             this.logError(e.getMessage(), e);
  1247.            
  1248.             return false;
  1249.         }
  1250.         finally {
  1251.             if(this.debug){
  1252.                 this.logDebug("Update record statistiche negli stati con CASE ("+case1WhenStato+"->"+case1ThenStato+") e ("+case2WhenStato+"->"+case2ThenStato+") ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  1253.             }
  1254.         }

  1255.     }
  1256.    
  1257.     private boolean deleteFisicoStatistiche( TipoPdD tipoPdD, Date data , int statoRecord, boolean equalsStatoRecord) {

  1258.         if(this.debug){
  1259.             this.logDebug("Eliminazione statistiche con stato record '"+statoRecord+"' equals_stato_record:"+equalsStatoRecord+" ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") ...");
  1260.         }

  1261.         try{

  1262.             ISQLFieldConverter fieldConverter = ((IDBServiceUtilities<?>)this.statisticaServiceDAO).getFieldConverter();
  1263.             TipiDatabase tipoDB = fieldConverter.getDatabaseType();
  1264.            
  1265.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(tipoDB);
  1266.             sqlQueryObject.addDeleteTable(fieldConverter.toTable(this.model));
  1267.             sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.DATA, false)+"=?");
  1268.             if(equalsStatoRecord) {
  1269.                 sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.STATO_RECORD, false)+"=?");
  1270.             }
  1271.             else {
  1272.                 /**sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.STATO_RECORD, false)+"<>?");*/
  1273.                 sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.STATO_RECORD, false)+"<?"); // non devo eliminare ne quelli nello stato 1 ne quello nello stato 2
  1274.             }
  1275.             sqlQueryObject.addWhereCondition(fieldConverter.toColumn(this.model.TIPO_PORTA, false)+"=?");
  1276.             sqlQueryObject.setANDLogicOperator(true);
  1277.            
  1278.             Date next = this.truncDate(this.incrementDate(data, false),false);
  1279.             if(this.debug){
  1280.                 this.logDebug("Elimino statistiche ["+this.getTipoStatistiche()+"]");
  1281.                 this.logDebug("Valori eliminazione (ms) tr.data_ingresso_richiesta=["+next.getTime()+"]");
  1282.             }
  1283.            
  1284.             int righeEliminate = this.statisticaServiceDAO.nativeUpdate(sqlQueryObject.createSQLDelete(),
  1285.                     next,
  1286.                     statoRecord,
  1287.                     TipoPdD.DELEGATA.equals(tipoPdD)? PddRuolo.DELEGATA.getValue() : PddRuolo.APPLICATIVA.getValue());
  1288.            
  1289.             if(this.debug){
  1290.                 this.logDebug("Eliminate ["+righeEliminate+"] entry");
  1291.             }

  1292.             return true;
  1293.            
  1294.         }catch (Throwable e) {
  1295.             this.logError(e.getMessage(), e);
  1296.            
  1297.             return false;
  1298.         }
  1299.         finally {
  1300.             if(this.debug){
  1301.                 this.logDebug("Eliminazione statistiche con stato record '"+statoRecord+"' equals_stato_record:"+equalsStatoRecord+" ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  1302.             }
  1303.         }

  1304.     }

  1305.     protected abstract Long insertStatistica(Statistica statistica) throws StatisticException;
  1306.     protected abstract void updateStatistica(long idStatistica, StatisticaContenuti ... statisticaContenuti) throws StatisticException;


  1307.     private void insertStatistica(StatisticBean stat, int statoRecord) throws StatisticException  {

  1308.         if(this.debug){
  1309.             this.logDebug("Inserimento statistica ["+stat.toString()+"] in corso ...");
  1310.         }

  1311.         Statistica statisticaBase = new Statistica();

  1312.         statisticaBase.setData(stat.getData());
  1313.         statisticaBase.setStatoRecord(statoRecord);
  1314.        
  1315.         statisticaBase.setTipoPorta(org.openspcoop2.core.statistiche.constants.TipoPorta.toEnumConstant(stat.getTipoPorta().getTipo()));
  1316.         statisticaBase.setIdPorta(stat.getIdPorta());
  1317.        
  1318.         statisticaBase.setTipoMittente(stat.getMittente().getTipo());
  1319.         statisticaBase.setMittente(stat.getMittente().getNome());
  1320.        
  1321.         statisticaBase.setTipoDestinatario(stat.getDestinatario().getTipo());
  1322.         statisticaBase.setDestinatario(stat.getDestinatario().getNome());
  1323.        
  1324.         statisticaBase.setTipoServizio(stat.getTipoServizio());
  1325.         statisticaBase.setServizio(stat.getServizio());
  1326.         statisticaBase.setVersioneServizio(stat.getVersioneServizio());
  1327.        
  1328.         statisticaBase.setAzione(stat.getAzione());
  1329.        
  1330.         statisticaBase.setServizioApplicativo(stat.getServizioApplicativo());
  1331.        
  1332.         statisticaBase.setTrasportoMittente(stat.getTrasportoMittente());
  1333.        
  1334.         statisticaBase.setTokenIssuer(stat.getTokenIssuer());
  1335.         statisticaBase.setTokenClientId(stat.getTokenClientId());
  1336.         statisticaBase.setTokenSubject(stat.getTokenSubject());
  1337.         statisticaBase.setTokenUsername(stat.getTokenUsername());
  1338.         statisticaBase.setTokenMail(stat.getTokenMail());
  1339.        
  1340.         statisticaBase.setClientAddress(stat.getClientAddress());
  1341.        
  1342.         statisticaBase.setGruppi(stat.getGruppo());
  1343.        
  1344.         statisticaBase.setUriApi(stat.getApi());
  1345.        
  1346.         statisticaBase.setClusterId(stat.getClusterId());
  1347.        
  1348.         if(stat.getDestinatario()!=null && stat.getDestinatario().getTipo()!=null) {
  1349.             EsitiProperties esitiProperties = null;
  1350.             int esitoConsegnaMultipla = -1;
  1351.             int esitoConsegnaMultiplaInCorso = -1;
  1352.             int esitoConsegnaMultiplaFallita = -1;
  1353.             int esitoConsegnaMultiplaCompletata = -1;
  1354.             try {
  1355.                 String protocollo = null;
  1356.                 if(stat.getDestinatario()!=null &&
  1357.                         stat.getDestinatario().getTipo()!=null &&
  1358.                         !"".equals(stat.getDestinatario().getTipo()) &&
  1359.                         !Costanti.INFORMAZIONE_NON_DISPONIBILE.equals(stat.getDestinatario().getTipo())) {
  1360.                     protocollo = ProtocolFactoryManager.getInstance().getProtocolByOrganizationType(stat.getDestinatario().getTipo());
  1361.                 }
  1362.                 else if(stat.getMittente()!=null &&
  1363.                         stat.getMittente().getTipo()!=null &&
  1364.                         !"".equals(stat.getMittente().getTipo()) &&
  1365.                         !Costanti.INFORMAZIONE_NON_DISPONIBILE.equals(stat.getMittente().getTipo())) {
  1366.                     protocollo = ProtocolFactoryManager.getInstance().getProtocolByOrganizationType(stat.getMittente().getTipo());
  1367.                 }
  1368.                 else {
  1369.                     protocollo = ProtocolFactoryManager.getInstance().getDefaultProtocolFactory().getProtocol();
  1370.                 }
  1371.                 esitiProperties = EsitiProperties.getInstanceFromProtocolName(this.logger, protocollo);
  1372.                 esitoConsegnaMultipla = esitiProperties.convertoToCode(EsitoTransazioneName.CONSEGNA_MULTIPLA);
  1373.                 esitoConsegnaMultiplaInCorso = esitiProperties.convertoToCode(EsitoTransazioneName.CONSEGNA_MULTIPLA_IN_CORSO);
  1374.                 esitoConsegnaMultiplaFallita = esitiProperties.convertoToCode(EsitoTransazioneName.CONSEGNA_MULTIPLA_FALLITA);
  1375.                 esitoConsegnaMultiplaCompletata = esitiProperties.convertoToCode(EsitoTransazioneName.CONSEGNA_MULTIPLA_COMPLETATA);
  1376.                 if(stat.getEsito().intValue() == esitoConsegnaMultiplaInCorso ||
  1377.                         stat.getEsito().intValue() == esitoConsegnaMultiplaFallita ||
  1378.                         stat.getEsito().intValue() == esitoConsegnaMultiplaCompletata) {
  1379.                     statisticaBase.setEsito(esitoConsegnaMultipla);
  1380.                 }
  1381.                 else {
  1382.                     statisticaBase.setEsito(stat.getEsito());
  1383.                 }
  1384.             }catch(Exception er) {
  1385.                 throw new StatisticException(er.getMessage(),er);
  1386.             }
  1387.         }
  1388.         else {
  1389.             statisticaBase.setEsito(stat.getEsito());
  1390.         }
  1391.         statisticaBase.setEsitoContesto(stat.getEsitoContesto());
  1392.        
  1393.         statisticaBase.setNumeroTransazioni((int)stat.getRichieste());
  1394.        
  1395.         statisticaBase.setDimensioniBytesBandaComplessiva(stat.getBytesBandaTotale());
  1396.         statisticaBase.setDimensioniBytesBandaInterna(stat.getBytesBandaInterna());
  1397.         statisticaBase.setDimensioniBytesBandaEsterna(stat.getBytesBandaEsterna());
  1398.        
  1399.         if(stat.getLatenzaServizio()!=Costanti.INFORMAZIONE_LATENZA_NON_DISPONIBILE) {
  1400.             statisticaBase.setLatenzaServizio(stat.getLatenzaServizio());
  1401.         }
  1402.         if(stat.getLatenzaPorta()!=Costanti.INFORMAZIONE_LATENZA_NON_DISPONIBILE) {
  1403.             statisticaBase.setLatenzaPorta(stat.getLatenzaPorta());
  1404.         }
  1405.         if(stat.getLatenzaTotale()!=Costanti.INFORMAZIONE_LATENZA_NON_DISPONIBILE) {
  1406.             statisticaBase.setLatenzaTotale(stat.getLatenzaTotale());
  1407.         }
  1408.        
  1409.         Long id = insertStatistica(statisticaBase);
  1410.         if(id!=null && id >0){
  1411.             stat.setId(id);
  1412.         }  
  1413.         if(this.debug){
  1414.             this.logDebug("Inserimento statistica effettuato con successo");
  1415.         }

  1416.     }
  1417.    
  1418. }