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 implements IStatisticsEngine {

  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 long waitMsBeforeNextInterval = 0;
  115.     protected boolean waitStatiInConsegna = false;
  116.     protected boolean gestioneUltimoIntervallo = false;
  117.     protected IServiceManager statisticheSM = null;
  118.     protected IServiceWithoutId<?> statisticaServiceDAO = null;
  119.     protected IServiceSearchWithoutId<?> statisticaServiceSearchDAO = null;
  120.     protected StatisticaModel model = null;
  121.     private IStatisticaInfoServiceSearch statisticaInfoSearchDAO = null;
  122.     private IStatisticaInfoService statisticaInfoDAO = null;
  123.     private ITransazioneServiceSearch transazioneSearchDAO = null;
  124.     private org.openspcoop2.monitor.engine.config.statistiche.dao.IServiceManager pluginsStatisticheSM = null;
  125.     private org.openspcoop2.core.plugins.dao.IServiceManager pluginsBaseSM = null;
  126.     private org.openspcoop2.core.commons.search.dao.IServiceManager utilsSM = null;
  127.     private org.openspcoop2.monitor.engine.config.transazioni.dao.IServiceManager pluginsTransazioniSM;
  128.     @SuppressWarnings("unused")
  129.     private IConfigurazioneStatisticaService confStatisticaDAO =null;
  130.     private TipiDatabase databaseType;
  131.     private StatisticsForceIndexConfig forceIndexConfig;

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

  133.     private boolean initialized = false;
  134.    
  135.     AbstractStatistiche(){
  136.        
  137.     }

  138.     @Override
  139.     public void init(StatisticsConfig config,
  140.             org.openspcoop2.core.statistiche.dao.IServiceManager statisticheSM,
  141.             org.openspcoop2.core.transazioni.dao.IServiceManager transazioniSM,
  142.             org.openspcoop2.monitor.engine.config.statistiche.dao.IServiceManager pluginsStatisticheSM,
  143.             org.openspcoop2.core.plugins.dao.IServiceManager pluginsBaseSM,
  144.             org.openspcoop2.core.commons.search.dao.IServiceManager utilsSM,
  145.             org.openspcoop2.monitor.engine.config.transazioni.dao.IServiceManager pluginsTransazioniSM){
  146.         if(config.getLogCore()!=null){
  147.             this.logger = config.getLogCore();
  148.         }
  149.        
  150.         this.debug = config.isDebug();
  151.         this.useUnionForLatency = config.isUseUnionForLatency();
  152.         this.generazioneStatisticheCustom = config.isGenerazioneStatisticheCustom();
  153.         this.analisiTransazioniCustom = config.isAnalisiTransazioniCustom();
  154.         this.waitMsBeforeNextInterval = config.getWaitMsBeforeNextInterval();
  155.         this.waitStatiInConsegna = config.isWaitStatiInConsegna();
  156.         this.gestioneUltimoIntervallo = this.isGestioneUltimoIntervallo(config);
  157.        
  158.         try {
  159.             if(statisticheSM==null){
  160.                 throw new ServiceException("StatisticheServiceManager ["+org.openspcoop2.core.statistiche.dao.IServiceManager.class.getName()+SUFFIX_NON_INIZIALIZZATO);
  161.             }
  162.             if(transazioniSM==null){
  163.                 throw new ServiceException("TransazioniServiceManager ["+org.openspcoop2.core.transazioni.dao.IServiceManager.class.getName()+SUFFIX_NON_INIZIALIZZATO);
  164.             }
  165.            
  166.             this.statisticheSM = statisticheSM;
  167.             this.statisticaInfoSearchDAO = this.statisticheSM.getStatisticaInfoServiceSearch();
  168.             this.statisticaInfoDAO = this.statisticheSM.getStatisticaInfoService();

  169.             this.databaseType = DAOFactoryProperties.getInstance(this.logger).getTipoDatabaseEnum(org.openspcoop2.core.statistiche.utils.ProjectInfo.getInstance());
  170.            
  171.             this.transazioneSearchDAO = transazioniSM.getTransazioneServiceSearch();

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

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

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

  232.     // METODI ASTRATTI
  233.     public abstract Date truncDate(Date date,boolean print);

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

  235.     public abstract Date decrementDate(Date date,boolean print);
  236.    
  237.     protected abstract boolean isGestioneUltimoIntervallo(StatisticsConfig config);

  238.     public Date decrementDate1Millisecond(Date date){
  239.         Calendar cTmp = Calendar.getInstance();
  240.         cTmp.setTime(date);
  241.         cTmp.add(Calendar.MILLISECOND, -1);
  242.         return cTmp.getTime();
  243.     }

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

  245.     private String getIntervalloStatistica(Date date){
  246.         Date d = this.incrementDate(date, false);
  247.         return this.getIntervalloStatistica(d, false);
  248.     }

  249.     public abstract TipoIntervalloStatistico getTipoStatistiche();

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

  251.     public abstract String getStatisticPluginMethodName() throws StatisticException;


  252.     @Override
  253.     public void generate() throws StatisticsEngineException {

  254.         if(!this.initialized){
  255.             throw new StatisticsEngineException("Inizializzazione fallita (verificare errori precedenti)");
  256.         }

  257.         try{
  258.             if(this.debug)
  259.                 this.logDebug("********************************************* "+this.getTipoStatistiche()+" *******************************************************");

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

  268.             Date dataAvvioBatch = DateManager.getDate();

  269.             // Now
  270.             // Tale data viene troncata in funzione della statistica che sto eseguendo
  271.             Date now = new Date();
  272.             now = truncDate(now,false);
  273.             now = this.decrementDate1Millisecond(now);
  274.             Date nowMenoUno = decrementDate(now, false);

  275.            
  276.             // 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
  277.             boolean saveDataStatistica = true;
  278.            
  279.            
  280.             // Genero statistiche per transazioni emessi in data > dataUltimaGenerazioneStatistiche AND data <= now
  281.             while(dataUltimaGenerazioneStatistiche.compareTo(nowMenoUno) <= 0){

  282.                 // genera
  283.                 boolean generazioneCompletataConSuccesso = generaStatistica(dataUltimaGenerazioneStatistiche,
  284.                         dataAvvioBatch, this.waitMsBeforeNextInterval,
  285.                         this.waitStatiInConsegna);
  286.                 if(!generazioneCompletataConSuccesso) {
  287.                     saveDataStatistica = false;
  288.                 }
  289.                                                
  290.                 // increment
  291.                 dataUltimaGenerazioneStatistiche = incrementDate(dataUltimaGenerazioneStatistiche, false);
  292.                 if(this.debug)
  293.                     this.logDebug("-----------------------");

  294.                 // Salvo nuova data di ultima generazione statistiche (entro nel prossimo intervallo)
  295.                 if(saveDataStatistica) {
  296.                     Date next = this.truncDate(this.incrementDate(dataUltimaGenerazioneStatistiche, false),false);
  297.                     if(this.debug)
  298.                         this.logDebug("Save data ultima generazione statistiche: "+next.toString());
  299.                     StatisticsInfoUtils.updateDataUltimaGenerazioneStatistiche(this.statisticaInfoSearchDAO, this.statisticaInfoDAO,
  300.                             this.getTipoStatistiche(), this.logger, next);
  301.                 }
  302.                
  303.             }


  304.             // Genero statistiche parziali della data di oggi
  305.             if(this.gestioneUltimoIntervallo){

  306.                 Date dataUltimoIntervallo = dataUltimaGenerazioneStatistiche;

  307.                 // genera
  308.                 generaStatistica(dataUltimoIntervallo,
  309.                         dataAvvioBatch, -1,
  310.                         false);
  311.                
  312.             }

  313.         }catch(Exception e){
  314.             this.logError(e.getMessage(), e);
  315.             throw new StatisticsEngineException(e);
  316.         }
  317.     }

  318.     private boolean generaStatistica(Date dataUltimaGenerazioneStatistiche,
  319.             Date dataAvvioBatch, long waitMsBeforeNextInterval,
  320.             boolean waitStatiInConsegna) {
  321.        
  322.         // Algoritmo
  323.         // Per la data in fase di aggiornamento:
  324.         // - 1) si elimina eventuali record rimasti "sporchi" (stato_record <1)
  325.         // - 2) i record esistenti nell'intervallo vengono portati al valore stato_record=2
  326.         // - 3) i nuovi record aggiunti vengono creati con stato_record=0
  327.         // - 4) si fa un unico comando di update nell'intervallo con CASE WHEN stato_record==2 THEN -2 WHEN stato_record==0 THEN 1
  328.         // - 5) si eliminano i record nell'intervallo con stato_record=-2
  329.        
  330.         /**if(dataUltimaGenerazioneStatistiche.compareTo(nowMenoUno) == 0){*/
  331.         // 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
  332.         // Se ho la stessa data devo eliminare l'intervallo, posso gia' averlo generato
  333.         // Eliminazione (Fase 1)
  334.         if(this.debug)
  335.             this.logDebug("----------- pulizia Fase1 (DataUguale) ------------");
  336.         boolean esito = this.deleteFisicoStatistiche( TipoPdD.DELEGATA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_VALIDO, false);
  337.         if(!esito) {
  338.             return false;
  339.         }
  340.         if(this.debug)
  341.             this.logDebug("------------ pulizia Fase1 (DataUguale) -----------");
  342.         esito = this.deleteFisicoStatistiche( TipoPdD.APPLICATIVA, dataUltimaGenerazioneStatistiche, CostantiDB.STATISTICHE_STATO_RECORD_VALIDO, false);
  343.         if(!esito) {
  344.             return false;
  345.         }
  346.         //}

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

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

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

  461.    
  462.    
  463.    
  464.     // ---- GENERAZIONE STATISTICHE BASE ----
  465.    
  466.     private boolean generaStatisticheUnion(TipoPdD tipoPdD, Date data, int statoRecord, BooleanNullable statiInCorso) {

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

  488.             // ** Where **
  489.             // Creo intervallo
  490.             Date dateNext = incrementDate(data, false);
  491.            
  492.             IExpression exprConLatenze = this.transazioneSearchDAO.newExpression();
  493.             StatisticsUtils.setExpressionNotNullDate(this.transazioneSearchDAO, exprConLatenze, data, dateNext, tipoPdD, null, fieldConverter);
  494.            
  495.             IExpression exprSenzaLatenze = this.transazioneSearchDAO.newExpression();
  496.             StatisticsUtils.setExpressionNullDate(this.transazioneSearchDAO, exprSenzaLatenze, data, dateNext, tipoPdD, null, fieldConverter);

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

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


  574.         } catch (ServiceException e){
  575.             this.logError(e.getMessage(),e);
  576.             generazioneOk = false;
  577.         } catch (NotImplementedException e) {
  578.             this.logError(e.getMessage(),e);
  579.             generazioneOk = false;
  580.         } catch (ExpressionNotImplementedException e) {
  581.             this.logError(e.getMessage(),e);
  582.             generazioneOk = false;
  583.         } catch (ExpressionException e) {
  584.             this.logError(e.getMessage(),e);
  585.             generazioneOk = false;
  586.         } catch (NotFoundException e) {
  587.             if(this.debug){
  588.                 this.logDebug(e.getMessage(),e);
  589.             }
  590.         }catch (Throwable e) {
  591.             this.logError(e.getMessage(),e);
  592.             generazioneOk = false;
  593.         }  

  594.         if(this.debug){
  595.             this.logDebug("Generazione statistiche ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  596.         }
  597.                
  598.         return generazioneOk;
  599.     }
  600.    
  601.     private boolean generaStatistiche(  TipoPdD tipoPdD, Date data, int statoRecord, BooleanNullable statiInCorso) {

  602.         boolean generazioneOk = true;
  603.        
  604.         if(this.debug){
  605.             this.logDebug("Generazione statistiche ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") ...");
  606.         }
  607.         try{
  608.             IExpression expr = this.transazioneSearchDAO.newExpression();

  609.             ISQLFieldConverter fieldConverter = ((IDBServiceUtilities<?>)this.transazioneSearchDAO).getFieldConverter();
  610.            
  611.             // ** Select field **
  612.             List<FunctionField> selectList = new ArrayList<>();
  613.             StatisticsUtils.addSelectFieldCountTransaction(selectList);
  614.             StatisticsUtils.addSelectFieldSizeTransaction(tipoPdD, selectList);
  615.            
  616.             // ** Where **
  617.             // Creo intervallo
  618.             Date dateNext = incrementDate(data, false);
  619.             StatisticsUtils.setExpression(this.transazioneSearchDAO, expr, data, dateNext, tipoPdD, false, null, fieldConverter);

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

  624.             if(this.forceIndexConfig!=null){
  625.                 if(this.forceIndexConfig.getTransazioniForceIndexGroupByNumeroDimensione()!=null){
  626.                     List<Index> listForceIndexes = this.forceIndexConfig.getTransazioniForceIndexGroupByNumeroDimensione();
  627.                     if(!listForceIndexes.isEmpty()){
  628.                         for (Index index : listForceIndexes) {
  629.                             expr.addForceIndex(index);
  630.                         }
  631.                     }
  632.                 }
  633.             }
  634.            
  635.             List<Map<String, Object>> list = this.transazioneSearchDAO.groupBy(expr, selectList.toArray(new FunctionField[1]));

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


  680.         } catch (ServiceException e){
  681.             this.logError(e.getMessage(),e);
  682.             generazioneOk = false;
  683.         } catch (NotImplementedException e) {
  684.             this.logError(e.getMessage(),e);
  685.             generazioneOk = false;
  686.         } catch (ExpressionNotImplementedException e) {
  687.             this.logError(e.getMessage(),e);
  688.             generazioneOk = false;
  689.         } catch (ExpressionException e) {
  690.             this.logError(e.getMessage(),e);
  691.             generazioneOk = false;
  692.         } catch (NotFoundException e) {
  693.             if(this.debug){
  694.                 this.logDebug(e.getMessage(),e);
  695.             }
  696.         }catch (Throwable e) {
  697.             this.logError(e.getMessage(),e);
  698.             generazioneOk = false;
  699.         }  

  700.         if(this.debug){
  701.             this.logDebug("Generazione statistiche ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  702.         }
  703.                
  704.         return generazioneOk;
  705.     }
  706.    
  707.     private StatisticBean readStatisticBean(Date data,Map<String, Object> row, ISQLFieldConverter fieldConverter, boolean useFieldConverter) throws ExpressionException{
  708.         StatisticBean stat = new StatisticBean();

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

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

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

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

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

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

  884.         } catch (Exception e) {
  885.             this.logError(e.getMessage(), e);
  886.         }

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

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

  979.             IExpression expr = this.transazioneSearchDAO.newExpression();
  980.            
  981.             List<FunctionField> selectList = new ArrayList<>();
  982.             StatisticsUtils.addSelectFieldCountTransaction(selectList);
  983.             StatisticsUtils.addSelectFieldSizeTransaction(tipoPdD, selectList);
  984.            
  985.             // Creo espressione
  986.             List<AliasFilter> aliases = new ArrayList<>();
  987.             if(gropuByStato){
  988.                 StatisticsUtils.setExpressionByStato(this.transazioneSearchDAO, expr, dateLeft, dateRight, tipoPdD, false, stat, fieldConverter);
  989.             }else{
  990.                 StatisticsUtils.setExpressionStatsPersonalizzate(this.transazioneSearchDAO, expr, dateLeft, dateRight, tipoPdD, false, stat, fieldConverter,
  991.                         aliases, idRisorsa, risorseFiltri);
  992.             }

  993.             // aggiungo eventuale filtro personalizzato
  994.             if(risorsaAggregata!=null && (risorsaAggregata.getFiltro() instanceof FilterImpl)){
  995.                 FilterImpl f = (FilterImpl) risorsaAggregata.getFiltro();
  996.                 expr.and(f.getExpression());
  997.             }
  998.            
  999.             if(this.debug){
  1000.                 this.logDebug("Analizzo dati di base statistica personalizzata ["+idStatisticaPersonalizzata+"]  ["+this.getTipoStatistiche()+
  1001.                         "] Intervallo date: ["+dateLeft.toString()+" - "+dateRight.toString()+"]");
  1002.                 this.logDebug("Valori query (ms) tr.data_ingresso_richiesta>["+dateLeft.getTime()+"] AND tr.data_ingresso_richiesta<=["+dateRight.getTime()+"]");
  1003.                 this.logDebug("Expr: "+expr.toString());
  1004.             }

  1005.             if(this.forceIndexConfig!=null){
  1006.                 if(this.forceIndexConfig.getTransazioniForceIndexGroupByCustomNumeroDimensione()!=null){
  1007.                     List<Index> listForceIndexes = this.forceIndexConfig.getTransazioniForceIndexGroupByCustomNumeroDimensione();
  1008.                     if(!listForceIndexes.isEmpty()){
  1009.                         for (Index index : listForceIndexes) {
  1010.                             expr.addForceIndex(index);
  1011.                         }
  1012.                     }
  1013.                 }
  1014.             }
  1015.            
  1016.             List<Map<String, Object>> list = this.transazioneSearchDAO.groupBy(expr, selectList.toArray(new FunctionField[1]));

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

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


  1145.         } catch (ServiceException e){
  1146.             this.logError(e.getMessage(),e);
  1147.         } catch (NotImplementedException e) {
  1148.             this.logError(e.getMessage(),e);
  1149.         } catch (ExpressionNotImplementedException e) {
  1150.             this.logError(e.getMessage(),e);
  1151.         } catch (ExpressionException e) {
  1152.             this.logError(e.getMessage(),e);
  1153.         } catch (NotFoundException e) {
  1154.             if(this.debug){
  1155.                 this.logDebug(e.getMessage(),e);
  1156.             }
  1157.         }catch (Exception e) {
  1158.             this.logError(e.getMessage(),e);
  1159.         }  

  1160.         if(this.debug){
  1161.             this.logDebug("Generazione statistica personalizzata ["+idStatisticaPersonalizzata+"] ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+
  1162.                     this.getIntervalloStatistica(dateStatistics,false)+") terminata");
  1163.         }
  1164.     }


  1165.    
  1166.    
  1167.    
  1168.    
  1169.    
  1170.    
  1171.     // ---- CRUD ----


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

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

  1176.         try{

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

  1199.             return true;

  1200.         }catch(Throwable e){
  1201.             this.logError(e.getMessage(), e);
  1202.            
  1203.             return false;
  1204.         }
  1205.         finally {
  1206.             if(this.debug){
  1207.                 this.logDebug("Update record statistiche allo stato '"+stato+"' ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  1208.             }
  1209.         }

  1210.     }
  1211.    
  1212.     private boolean updateStatoRecordStatistiche( TipoPdD tipoPdD, Date data,
  1213.             int case1WhenStato, int case1ThenStato,
  1214.             int case2WhenStato, int case2ThenStato) {

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

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

  1254.             return true;

  1255.         }catch(Throwable e){
  1256.             this.logError(e.getMessage(), e);
  1257.            
  1258.             return false;
  1259.         }
  1260.         finally {
  1261.             if(this.debug){
  1262.                 this.logDebug("Update record statistiche negli stati con CASE ("+case1WhenStato+"->"+case1ThenStato+") e ("+case2WhenStato+"->"+case2ThenStato+") ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  1263.             }
  1264.         }

  1265.     }
  1266.    
  1267.     private boolean deleteFisicoStatistiche( TipoPdD tipoPdD, Date data , int statoRecord, boolean equalsStatoRecord) {

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

  1271.         try{

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

  1302.             return true;
  1303.            
  1304.         }catch (Throwable e) {
  1305.             this.logError(e.getMessage(), e);
  1306.            
  1307.             return false;
  1308.         }
  1309.         finally {
  1310.             if(this.debug){
  1311.                 this.logDebug("Eliminazione statistiche con stato record '"+statoRecord+"' equals_stato_record:"+equalsStatoRecord+" ["+this.getTipoStatistiche()+"] ["+tipoPdD+"]("+this.getIntervalloStatistica(data)+") terminata");
  1312.             }
  1313.         }

  1314.     }

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


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

  1318.         if(this.debug){
  1319.             this.logDebug("Inserimento statistica ["+stat.toString()+"] in corso ...");
  1320.         }

  1321.         Statistica statisticaBase = new Statistica();

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

  1426.     }
  1427.    
  1428. }