EngineResponseCaching.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */


  20. package org.openspcoop2.pdd.core.jmx;

  21. import java.util.Iterator;

  22. import javax.management.Attribute;
  23. import javax.management.AttributeList;
  24. import javax.management.AttributeNotFoundException;
  25. import javax.management.DynamicMBean;
  26. import javax.management.InvalidAttributeValueException;
  27. import javax.management.JMException;
  28. import javax.management.MBeanAttributeInfo;
  29. import javax.management.MBeanConstructorInfo;
  30. import javax.management.MBeanException;
  31. import javax.management.MBeanInfo;
  32. import javax.management.MBeanOperationInfo;
  33. import javax.management.MBeanParameterInfo;
  34. import javax.management.NotificationBroadcasterSupport;
  35. import javax.management.ReflectionException;

  36. import org.slf4j.Logger;
  37. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  38. import org.openspcoop2.pdd.core.response_caching.GestoreCacheResponseCaching;
  39. import org.openspcoop2.pdd.core.response_caching.ResponseCached;
  40. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;


  41. /**
  42.  * Implementazione JMX per la gestione dei token
  43.  *  
  44.  * @author Poli Andrea (apoli@link.it)
  45.  * @author $Author$
  46.  * @version $Rev$, $Date$
  47.  */
  48. public class EngineResponseCaching extends NotificationBroadcasterSupport implements DynamicMBean {

  49.     public static final String CACHE_METHOD_NAME_GET_OBJECT_BY_UUID = "getResponseCached";
  50.     public static final String CACHE_METHOD_NAME_REMOVE_OBJECT_BY_UUID = "removeResponseCached";
  51.    
  52.    
  53.     /** Attributi */
  54.     private boolean cacheAbilitata = false;
  55.    
  56.     /** getAttribute */
  57.     @Override
  58.     public Object getAttribute(String attributeName) throws AttributeNotFoundException,MBeanException,ReflectionException{
  59.        
  60.         if( (attributeName==null) || (attributeName.equals("")) )
  61.             throw new IllegalArgumentException("Il nome dell'attributo e' nullo o vuoto");
  62.        
  63.         if(attributeName.equals(JMXUtils.CACHE_ATTRIBUTE_ABILITATA))
  64.             return this.cacheAbilitata;
  65.        
  66.         throw new AttributeNotFoundException("Attributo "+attributeName+" non trovato");
  67.     }
  68.    
  69.     /** getAttributes */
  70.     @Override
  71.     public AttributeList getAttributes(String [] attributesNames){
  72.        
  73.         if(attributesNames==null)
  74.             throw new IllegalArgumentException("Array nullo");
  75.        
  76.         AttributeList list = new AttributeList();
  77.         for (int i=0; i<attributesNames.length; i++){
  78.             try{
  79.                 list.add(new Attribute(attributesNames[i],getAttribute(attributesNames[i])));
  80.             }catch(JMException ex){}
  81.         }
  82.         return list;
  83.     }
  84.    
  85.     /** setAttribute */
  86.     @Override
  87.     public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException{
  88.        
  89.         if( attribute==null )
  90.             throw new IllegalArgumentException("Il nome dell'attributo e' nullo");
  91.        
  92.         try{
  93.            
  94.             if(attribute.getName().equals(JMXUtils.CACHE_ATTRIBUTE_ABILITATA)){
  95.                 boolean v = (Boolean) attribute.getValue();
  96.                 if(v){
  97.                     // la cache DEVE essere abilitata
  98.                     if(!this.cacheAbilitata){
  99.                         this.abilitaCache();
  100.                     }
  101.                 }
  102.                 else{
  103.                     // la cache DEVE essere disabilitata
  104.                     if(this.cacheAbilitata){
  105.                         this.disabilitaCache();
  106.                     }
  107.                 }
  108.             }
  109.            
  110.             else
  111.                 throw new AttributeNotFoundException("Attributo "+attribute.getName()+" non trovato");
  112.            
  113.         }catch(ClassCastException ce){
  114.             throw new InvalidAttributeValueException("il tipo "+attribute.getValue().getClass()+" dell'attributo "+attribute.getName()+" non e' valido");
  115.         }catch(JMException j){
  116.             throw new MBeanException(j);
  117.         }
  118.        
  119.     }
  120.    
  121.     /** setAttributes */
  122.     @Override
  123.     public AttributeList setAttributes(AttributeList list){
  124.        
  125.         if(list==null)
  126.             throw new IllegalArgumentException("Lista degli attributi e' nulla");
  127.        
  128.         AttributeList ret = new AttributeList();
  129.         Iterator<?> it = ret.iterator();
  130.        
  131.         while(it.hasNext()){
  132.             try{
  133.                 Attribute attribute = (Attribute) it.next();
  134.                 setAttribute(attribute);
  135.                 ret.add(attribute);
  136.             }catch(JMException ex){}
  137.         }
  138.        
  139.         return ret;
  140.        
  141.     }
  142.    
  143.     /** invoke */
  144.     @Override
  145.     public Object invoke(String actionName, Object[]params, String[]signature) throws MBeanException,ReflectionException{
  146.        
  147.         if( (actionName==null) || (actionName.equals("")) )
  148.             throw new IllegalArgumentException("Nessuna operazione definita");
  149.        
  150.         if(actionName.equals(JMXUtils.CACHE_METHOD_NAME_RESET)){
  151.             return this.resetCache();
  152.         }
  153.        
  154.         if(actionName.equals(JMXUtils.CACHE_METHOD_NAME_PRINT_STATS)){
  155.             return this.printStatCache();
  156.         }
  157.        
  158.         if(actionName.equals(JMXUtils.CACHE_METHOD_NAME_DISABILITA)){
  159.             return this.disabilitaCacheConEsito();
  160.         }
  161.        
  162.         if(actionName.equals(JMXUtils.CACHE_METHOD_NAME_ABILITA)){
  163.             if(params.length != 4)
  164.                 throw new MBeanException(new Exception("[AbilitaCache] Lunghezza parametri non corretta: "+params.length));
  165.            
  166.             Long param1 = null;
  167.             if(params[0]!=null && !"".equals(params[0])){
  168.                 param1 = (Long)params[0];
  169.                 if(param1<0){
  170.                     param1 = null;
  171.                 }
  172.             }
  173.            
  174.             Boolean param2 = null;
  175.             if(params[1]!=null && !"".equals(params[1])){
  176.                 param2 = (Boolean)params[1];
  177.             }
  178.            
  179.             Long param3 = null;
  180.             if(params[2]!=null && !"".equals(params[2])){
  181.                 param3 = (Long)params[2];
  182.                 if(param3<0){
  183.                     param3 = null;
  184.                 }
  185.             }
  186.            
  187.             Long param4 = null;
  188.             if(params[3]!=null && !"".equals(params[3])){
  189.                 param4 = (Long)params[3];
  190.                 if(param4<0){
  191.                     param4 = null;
  192.                 }
  193.             }
  194.                    
  195.             return this.abilitaCache(param1, param2, param3, param4 );
  196.         }
  197.        
  198.         if(actionName.equals(JMXUtils.CACHE_METHOD_NAME_LIST_KEYS)){
  199.             return this.listKeysCache();
  200.         }
  201.        
  202.         if(actionName.equals(JMXUtils.CACHE_METHOD_NAME_GET_OBJECT)){
  203.            
  204.             if(params.length != 1)
  205.                 throw new MBeanException(new Exception("["+JMXUtils.CACHE_METHOD_NAME_GET_OBJECT+"] Lunghezza parametri non corretta: "+params.length));
  206.            
  207.             String param1 = null;
  208.             if(params[0]!=null && !"".equals(params[0])){
  209.                 param1 = (String)params[0];
  210.             }
  211.            
  212.             return this.getObjectCache(param1);
  213.         }
  214.        
  215.         if(actionName.equals(JMXUtils.CACHE_METHOD_NAME_REMOVE_OBJECT)){
  216.            
  217.             if(params.length != 1)
  218.                 throw new MBeanException(new Exception("["+JMXUtils.CACHE_METHOD_NAME_REMOVE_OBJECT+"] Lunghezza parametri non corretta: "+params.length));
  219.            
  220.             String param1 = null;
  221.             if(params[0]!=null && !"".equals(params[0])){
  222.                 param1 = (String)params[0];
  223.             }
  224.            
  225.             return this.removeObjectCache(param1);
  226.         }
  227.        
  228.         if(actionName.equals(CACHE_METHOD_NAME_GET_OBJECT_BY_UUID)){
  229.            
  230.             if(params.length != 1)
  231.                 throw new MBeanException(new Exception("["+CACHE_METHOD_NAME_GET_OBJECT_BY_UUID+"] Lunghezza parametri non corretta: "+params.length));
  232.            
  233.             String param1 = null;
  234.             if(params[0]!=null && !"".equals(params[0])){
  235.                 param1 = (String)params[0];
  236.             }
  237.            
  238.             return this.getObjectCacheByUUID(param1);
  239.         }
  240.        
  241.         if(actionName.equals(CACHE_METHOD_NAME_REMOVE_OBJECT_BY_UUID)){
  242.            
  243.             if(params.length != 1)
  244.                 throw new MBeanException(new Exception("["+CACHE_METHOD_NAME_REMOVE_OBJECT_BY_UUID+"] Lunghezza parametri non corretta: "+params.length));
  245.            
  246.             String param1 = null;
  247.             if(params[0]!=null && !"".equals(params[0])){
  248.                 param1 = (String)params[0];
  249.             }
  250.            
  251.             return this.removeObjectCacheByUUID(param1);
  252.         }
  253.        
  254.         throw new UnsupportedOperationException("Operazione "+actionName+" sconosciuta");
  255.     }
  256.    
  257.     /* MBean info */
  258.     @Override
  259.     public MBeanInfo getMBeanInfo(){
  260.        
  261.         // Descrizione della classe nel MBean
  262.         String className = this.getClass().getName();
  263.         String description = "Risposte salvate che sono transitate sul Gateway ("+OpenSPCoop2Properties.getInstance().getVersione()+")";
  264.        
  265.         // MetaData per l'attributo abilitaCache
  266.         MBeanAttributeInfo cacheAbilitataVAR = JMXUtils.MBEAN_ATTRIBUTE_INFO_CACHE_ABILITATA;
  267.        
  268.         // MetaData per l'operazione resetCache
  269.         MBeanOperationInfo resetCacheOP = JMXUtils.MBEAN_OPERATION_RESET_CACHE;
  270.        
  271.         // MetaData per l'operazione printStatCache
  272.         MBeanOperationInfo printStatCacheOP = JMXUtils.MBEAN_OPERATION_PRINT_STATS_CACHE;
  273.        
  274.         // MetaData per l'operazione disabilitaCache
  275.         MBeanOperationInfo disabilitaCacheOP = JMXUtils.MBEAN_OPERATION_DISABILITA_CACHE;
  276.        
  277.         // MetaData per l'operazione abilitaCache con parametri
  278.         MBeanOperationInfo abilitaCacheParametriOP = JMXUtils.MBEAN_OPERATION_ABILITA_CACHE_CON_PARAMETRI;
  279.        
  280.         // MetaData per l'operazione listKeysCache
  281.         MBeanOperationInfo listKeysCacheOP = JMXUtils.MBEAN_OPERATION_LIST_KEYS_CACHE;

  282.         // MetaData per l'operazione getObjectCache
  283.         MBeanOperationInfo getObjectCacheOP = JMXUtils.MBEAN_OPERATION_GET_OBJECT_CACHE;
  284.        
  285.         // MetaData per l'operazione removeObjectCache
  286.         MBeanOperationInfo removeObjectCacheOP = JMXUtils.MBEAN_OPERATION_REMOVE_OBJECT_CACHE;
  287.        
  288.         // get by uuid
  289.         MBeanOperationInfo getObjectByUUID
  290.             = new MBeanOperationInfo(CACHE_METHOD_NAME_GET_OBJECT_BY_UUID,"Recupera la risposta salvata in cache",
  291.                 new MBeanParameterInfo[]{
  292.                     new MBeanParameterInfo("key",String.class.getName(),"Identificativo della risposta in cache"),
  293.                 },
  294.                 String.class.getName(),
  295.                 MBeanOperationInfo.ACTION);
  296.        
  297.         // remove by uuid
  298.         MBeanOperationInfo removeObjectByUUID
  299.             = new MBeanOperationInfo(CACHE_METHOD_NAME_REMOVE_OBJECT_BY_UUID,"Rimuove la risposta salvata in cache",
  300.                 new MBeanParameterInfo[]{
  301.                     new MBeanParameterInfo("key",String.class.getName(),"Identificativo della risposta in cache"),
  302.                 },
  303.                 String.class.getName(),
  304.                 MBeanOperationInfo.ACTION);
  305.        
  306.         // Mbean costruttore
  307.         MBeanConstructorInfo defaultConstructor = new MBeanConstructorInfo("Default Constructor","Crea e inizializza una nuova istanza del MBean",null);

  308.         // Lista attributi
  309.         MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[]{cacheAbilitataVAR};
  310.        
  311.         // Lista Costruttori
  312.         MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[]{defaultConstructor};
  313.        
  314.         // Lista operazioni
  315.         MBeanOperationInfo[] operations = new MBeanOperationInfo[]{getObjectByUUID,removeObjectByUUID,
  316.                 resetCacheOP,printStatCacheOP,disabilitaCacheOP,abilitaCacheParametriOP,listKeysCacheOP,getObjectCacheOP,removeObjectCacheOP};
  317.        
  318.         return new MBeanInfo(className,description,attributes,constructors,operations,null);
  319.     }
  320.    
  321.     /* Variabili per la gestione JMX */
  322.     private Logger log;
  323.    
  324.     /* Costruttore */
  325.     public EngineResponseCaching(){
  326.         this.log = OpenSPCoop2Logger.getLoggerOpenSPCoopCore();
  327.                
  328.         // Configurazione
  329.         this.cacheAbilitata = GestoreCacheResponseCaching.isCacheAbilitata();
  330.            
  331.     }
  332.    
  333.     public boolean isCacheAbilitata() {
  334.         return this.cacheAbilitata;
  335.     }
  336.    
  337.     /* Metodi di management JMX */
  338.     public String resetCache(){
  339.         try{
  340.             if(this.cacheAbilitata==false)
  341.                 throw new Exception("Cache non abilitata");
  342.             GestoreCacheResponseCaching.resetCache();
  343.             return JMXUtils.MSG_RESET_CACHE_EFFETTUATO_SUCCESSO;
  344.         }catch(Throwable e){
  345.             this.log.error(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage(),e);
  346.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  347.         }
  348.     }
  349.    
  350.     public String printStatCache(){
  351.         try{
  352.             if(this.cacheAbilitata==false)
  353.                 throw new Exception("Cache non abilitata");
  354.             return GestoreCacheResponseCaching.printStatsCache("\n");
  355.         }catch(Throwable e){
  356.             this.log.error(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage(),e);
  357.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  358.         }
  359.     }
  360.    
  361.     public String abilitaCache(){
  362.         try{
  363.             GestoreCacheResponseCaching.abilitaCache();
  364.             this.cacheAbilitata = true;
  365.             return JMXUtils.MSG_ABILITAZIONE_CACHE_EFFETTUATA;
  366.         }catch(Throwable e){
  367.             this.log.error(e.getMessage(),e);
  368.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  369.         }
  370.     }

  371.     public String abilitaCache(Long dimensioneCache,Boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond){
  372.         try{
  373.             GestoreCacheResponseCaching.abilitaCache(dimensioneCache,algoritmoCacheLRU,itemIdleTime,itemLifeSecond, this.log);
  374.             this.cacheAbilitata = true;
  375.             return JMXUtils.MSG_ABILITAZIONE_CACHE_EFFETTUATA;
  376.         }catch(Throwable e){
  377.             this.log.error(e.getMessage(),e);
  378.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  379.         }
  380.     }
  381.    
  382.     public void disabilitaCache() throws JMException{
  383.         try{
  384.             GestoreCacheResponseCaching.disabilitaCache();
  385.             this.cacheAbilitata = false;
  386.         }catch(Throwable e){
  387.             this.log.error(e.getMessage(),e);
  388.             throw new JMException(e.getMessage());
  389.         }
  390.     }
  391.     public String disabilitaCacheConEsito() {
  392.         try{
  393.             disabilitaCache();
  394.             return JMXUtils.MSG_DISABILITAZIONE_CACHE_EFFETTUATA;
  395.         }catch(Throwable e){
  396.             this.log.error(e.getMessage(),e);
  397.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  398.         }
  399.     }
  400.    
  401.     public String listKeysCache(){
  402.         try{
  403.             if(this.cacheAbilitata==false)
  404.                 throw new Exception("Cache non abilitata");
  405.             return GestoreCacheResponseCaching.listKeysCache("\n");
  406.         }catch(Throwable e){
  407.             this.log.error(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage(),e);
  408.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  409.         }
  410.     }
  411.    
  412.     public String getObjectCache(String key){
  413.         try{
  414.             if(this.cacheAbilitata==false)
  415.                 throw new Exception("Cache non abilitata");
  416.             return GestoreCacheResponseCaching.getObjectCache(key);
  417.         }catch(Throwable e){
  418.             this.log.error(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage(),e);
  419.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  420.         }
  421.     }
  422.    
  423.     public String removeObjectCache(String key){
  424.         try{
  425.             if(this.cacheAbilitata==false)
  426.                 throw new Exception("Cache non abilitata");
  427.             GestoreCacheResponseCaching.removeObjectCache(key);
  428.             return JMXUtils.MSG_RIMOZIONE_CACHE_EFFETTUATA;
  429.         }catch(Throwable e){
  430.             this.log.error(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage(),e);
  431.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  432.         }
  433.     }
  434.    
  435.     public String getObjectCacheByUUID(String key){
  436.         try{
  437.             if(this.cacheAbilitata==false)
  438.                 throw new Exception("Cache non abilitata");
  439.             ResponseCached rc = GestoreCacheResponseCaching.getInstance().readByUUID(key);
  440.             if(rc == null) {
  441.                 return "oggetto con chiave ["+key+"] non presente";
  442.             }
  443.             else {
  444.                 return rc.print();
  445.             }
  446.         }catch(Throwable e){
  447.             this.log.error(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage(),e);
  448.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  449.         }
  450.     }
  451.    
  452.     public String removeObjectCacheByUUID(String key){
  453.         try{
  454.             if(this.cacheAbilitata==false)
  455.                 throw new Exception("Cache non abilitata");
  456.             GestoreCacheResponseCaching.getInstance().removeByUUID(key);
  457.             return JMXUtils.MSG_RIMOZIONE_CACHE_EFFETTUATA;
  458.         }catch(Throwable e){
  459.             this.log.error(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage(),e);
  460.             return JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+e.getMessage();
  461.         }
  462.     }

  463. }