Proxy.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.services.connector;

  21. import java.io.BufferedReader;
  22. import java.io.IOException;
  23. import java.io.StringReader;
  24. import java.util.ArrayList;
  25. import java.util.HashMap;
  26. import java.util.List;
  27. import java.util.Map;

  28. import javax.servlet.ServletException;
  29. import javax.servlet.http.HttpServlet;
  30. import javax.servlet.http.HttpServletRequest;
  31. import javax.servlet.http.HttpServletResponse;

  32. import org.apache.commons.lang.StringUtils;
  33. import org.openspcoop2.core.commons.CoreException;
  34. import org.openspcoop2.core.constants.Costanti;
  35. import org.openspcoop2.pdd.config.DynamicClusterManager;
  36. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  37. import org.openspcoop2.pdd.core.CostantiPdD;
  38. import org.openspcoop2.pdd.core.jmx.ConfigurazionePdD;
  39. import org.openspcoop2.pdd.core.jmx.GestoreConsegnaApplicativi;
  40. import org.openspcoop2.pdd.core.jmx.GestoreRichieste;
  41. import org.openspcoop2.pdd.core.jmx.JMXUtils;
  42. import org.openspcoop2.pdd.core.jmx.MonitoraggioRisorse;
  43. import org.openspcoop2.pdd.core.jmx.StatoServiziJMXResource;
  44. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  45. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  46. import org.openspcoop2.pdd.services.connector.proxy.IProxyOperationService;
  47. import org.openspcoop2.pdd.services.connector.proxy.ProxyOperation;
  48. import org.openspcoop2.pdd.services.connector.proxy.ProxyOperationServiceFactory;
  49. import org.openspcoop2.protocol.sdk.state.URLProtocolContext;
  50. import org.openspcoop2.utils.LoggerWrapperFactory;
  51. import org.openspcoop2.utils.UtilsException;
  52. import org.openspcoop2.utils.datasource.JmxDataSource;
  53. import org.openspcoop2.utils.date.DateManager;
  54. import org.openspcoop2.utils.transport.TransportUtils;
  55. import org.openspcoop2.utils.transport.http.HttpConstants;
  56. import org.openspcoop2.utils.transport.http.HttpRequest;
  57. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  58. import org.openspcoop2.utils.transport.http.HttpResponse;
  59. import org.openspcoop2.utils.transport.http.HttpServletCredential;
  60. import org.openspcoop2.utils.transport.http.HttpUtilities;
  61. import org.slf4j.Logger;

  62. /**
  63.  * Proxy
  64.  *
  65.  * @author Poli Andrea (apoli@link.it)
  66.  * @author $Author$
  67.  * @version $Rev$, $Date$
  68.  */

  69. public class Proxy extends HttpServlet {

  70.      /**
  71.      * serialVersionUID
  72.      */
  73.     private static final long serialVersionUID = 1L;

  74.     private static final String SERVIZIO_NON_ABILITATO = "Servizio non abilitato";
  75.     private static final String SERVIZIO_NON_DISPONIBILE = "Servizio non disponibile";
  76.    
  77.     private static void logError(Logger log, String msg, Throwable e) {
  78.         log.error(msg, e);
  79.     }
  80.     private static void logError(Logger log, String msg) {
  81.         log.error(msg);
  82.     }
  83.     private static void logDebug(Logger log, String msg) {
  84.         log.debug(msg);
  85.     }
  86.    
  87.     private static void sendError(HttpServletResponse res, Logger log, String msg, int code) {
  88.         sendError(res, log, msg, code, msg, null);
  89.     }
  90.     @SuppressWarnings("unused")
  91.     private static void sendError(HttpServletResponse res, Logger log, String msg, int code, Throwable e) {
  92.         sendError(res, log, msg, code, msg, e);
  93.     }
  94.     private static void sendError(HttpServletResponse res, Logger log, String msg, int code, String logMsg) {
  95.         sendError(res, log, msg, code, logMsg, null);
  96.     }
  97.     private static void sendError(HttpServletResponse res, Logger log, String msg, int code, String logMsg, Throwable e) {
  98.         String prefix = "[Proxy] ";
  99.         if(e!=null) {
  100.             logError(log,prefix+logMsg, e);
  101.         }
  102.         else {
  103.             logError(log,prefix+logMsg);
  104.         }
  105.         res.setStatus(code);
  106.         res.setContentType(HttpConstants.CONTENT_TYPE_PLAIN);
  107.         try {
  108.             res.getOutputStream().write(msg.getBytes());
  109.         }catch(Exception t) {
  110.             logError(log,"[Proxy] SendError failed: "+t.getMessage(),t);
  111.         }
  112.     }

  113.     private static boolean saveContextOnlyOperation = true;
  114.     public static boolean isSaveContextOnlyOperation() {
  115.         return saveContextOnlyOperation;
  116.     }
  117.     public static void setSaveContextOnlyOperation(boolean saveContextOnlyOperation) {
  118.         Proxy.saveContextOnlyOperation = saveContextOnlyOperation;
  119.     }
  120.    
  121.     @Override public void doGet(HttpServletRequest req, HttpServletResponse res)
  122.     throws ServletException, IOException {
  123.        
  124.         Logger log = OpenSPCoop2Logger.getLoggerOpenSPCoopProxy();
  125.         if(log==null)
  126.             log = LoggerWrapperFactory.getLogger(Proxy.class);
  127.        
  128.         if( !OpenSPCoop2Startup.initialize){
  129.             CheckStatoPdD.serializeNotInitializedResponse(res, log);
  130.             return;
  131.         }
  132.        
  133.         OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  134.        
  135.         boolean proxyEnabled = false;
  136.         if(properties!=null && properties.isProxyReadJMXResourcesEnabled() ){
  137.             proxyEnabled = true;
  138.         }
  139.         if(!proxyEnabled){
  140.             String msg = SERVIZIO_NON_ABILITATO;
  141.             sendError(res, log, msg, 500);
  142.             return;
  143.         }
  144.                
  145.         // verifico l'esistenza di nodi
  146.         List<String> list = null;
  147.         try {
  148.             list = DynamicClusterManager.getInstance().getHostnames(log);
  149.         }catch(Exception e) {
  150.             String msg = SERVIZIO_NON_DISPONIBILE;
  151.             String logMsg = msg+": "+e.getMessage();
  152.             sendError(res, log, msg, 500, logMsg, e);
  153.             return;
  154.         }
  155.        
  156.         boolean asyncMode = properties.isProxyReadJMXResourcesAsyncProcessByTimer();
  157.         IProxyOperationService proxyOperationService = null;
  158.         if(asyncMode) {
  159.             String className = properties.getProxyReadJMXResourcesAsyncProcessByTimerServiceImplClass();
  160.             try {
  161.                 proxyOperationService = ProxyOperationServiceFactory.newInstance(className, log);
  162.             }catch(Exception e) {
  163.                 String msg = SERVIZIO_NON_DISPONIBILE;
  164.                 String logMsg = msg+": "+e.getMessage();
  165.                 sendError(res, log, msg, 500, logMsg, e);
  166.                 return;
  167.             }
  168.         }
  169.                
  170.         // === Costruisco nuova url ===
  171.        
  172.         // schema
  173.         String protocolSchema = properties.getProxyReadJMXResourcesSchema();
  174.         if(asyncMode) {
  175.             String tmp = properties.getProxyReadJMXResourcesAsyncProcessByTimerSchema();
  176.             if(tmp!=null && StringUtils.isNotEmpty(tmp)) {
  177.                 protocolSchema = tmp;
  178.             }
  179.         }
  180.         if(protocolSchema==null || StringUtils.isEmpty(protocolSchema)) {
  181.             protocolSchema = req.getScheme();
  182.         }
  183.         String protocol = (protocolSchema!=null && protocolSchema.trim().toLowerCase().startsWith("https")) ? "https://" : "http://";
  184.        
  185.         // hostname (solo in caso async-mode)
  186.         String hostnameAsync = null;
  187.         if(asyncMode) {
  188.             hostnameAsync = properties.getProxyReadJMXResourcesAsyncProcessByTimerHostname();
  189.         }
  190.        
  191.         // port
  192.         int port = req.getLocalPort();
  193.         if(asyncMode && properties.getProxyReadJMXResourcesAsyncProcessByTimerPort()!=null && properties.getProxyReadJMXResourcesAsyncProcessByTimerPort().intValue()>0) {
  194.             port = properties.getProxyReadJMXResourcesAsyncProcessByTimerPort().intValue();
  195.         }
  196.         else if(properties.getProxyReadJMXResourcesPort()!=null && properties.getProxyReadJMXResourcesPort().intValue()>0) {
  197.             port = properties.getProxyReadJMXResourcesPort().intValue();
  198.         }
  199.        
  200.         // context
  201.         String context = req.getContextPath();
  202.         if(!context.endsWith("/")) {
  203.             context = context + "/";
  204.         }
  205.         context = context + URLProtocolContext.Check_FUNCTION;
  206.        
  207.         // paramters
  208.         Map<String, List<String>> parameters = buildParameters(req);
  209.        
  210.         // Https
  211.         boolean https = properties.isProxyReadJMXResourcesHttpsEnabled();
  212.         boolean verificaHostname = false;
  213.         boolean autenticazioneServer = false;
  214.         String autenticazioneServerPath = null;
  215.         String autenticazioneServerType = null;
  216.         String autenticazioneServerPassword = null;
  217.         if(https) {
  218.             verificaHostname = properties.isProxyReadJMXResourcesHttpsEnabledVerificaHostName();
  219.             autenticazioneServer = properties.isProxyReadJMXResourcesHttpsEnabledAutenticazioneServer();
  220.             if(autenticazioneServer) {
  221.                 autenticazioneServerPath = properties.getProxyReadJMXResourcesHttpsEnabledAutenticazioneServerTruststorePath();
  222.                 autenticazioneServerType = properties.getProxyReadJMXResourcesHttpsEnabledAutenticazioneServerTruststoreType();
  223.                 autenticazioneServerPassword = properties.getProxyReadJMXResourcesHttpsEnabledAutenticazioneServerTruststorePassword();
  224.             }
  225.         }
  226.        
  227.         // Timeout
  228.         int readTimeout = properties.getProxyReadJMXResourcesReadTimeout();
  229.         int connectTimeout = properties.getProxyReadJMXResourcesConnectionTimeout();
  230.        
  231.         // Vengono utilizzate le credenziali del servizio check che dovranno essere uguali su tutti i nodi
  232.         String usernameCheck = properties.getCheckReadJMXResourcesUsername();
  233.         String passwordCheck = properties.getCheckReadJMXResourcesPassword();
  234.        
  235.        
  236.         // === Avvio gestione ===
  237.        
  238.         String resourceName = req.getParameter(CostantiPdD.CHECK_STATO_PDD_RESOURCE_NAME);
  239.         if(resourceName!=null && !"".equals(resourceName)){
  240.            
  241.             // prima di procedere verifico una eventuale autenticazione
  242.             String username = properties.getProxyReadJMXResourcesUsername();
  243.             String password = properties.getProxyReadJMXResourcesPassword();
  244.             if(username!=null && password!=null){
  245.                 HttpServletCredential identity = new HttpServletCredential(req, log);
  246.                 if(!username.equals(identity.getUsername())){
  247.                     String msg = "Servizio non autorizzato";
  248.                     String logMsg = msg+". Richiesta effettuata da username ["+identity.getUsername()+"] sconosciuto";
  249.                     sendError(res, log, msg, 500, logMsg);  
  250.                     return;
  251.                 }
  252.                 if(!password.equals(identity.getPassword())){
  253.                     String msg = "Servizio non autorizzato";
  254.                     String logMsg = msg+". Richiesta effettuata da username ["+identity.getUsername()+"] (password errata)";
  255.                     sendError(res, log, msg, 500, logMsg);  
  256.                     return;
  257.                 }
  258.             }
  259.            
  260.             /*
  261.              *  metodi void: in questo caso rientrano le reset cache.
  262.              *                Il servizio proxy invocherà ogni nodo.
  263.              *                Se anche solo uno dei nodi restituisce errore, viene ritornato quell’errore (si tratta di un caso anormale).
  264.              *                
  265.              *  metodi che devono restituire una stringa: in questo caso il servizio invocherà solamente un nodo a caso
  266.              *                poichè ogni nodo sono indistinguibili uno dall’altro.
  267.              *                In questa casistica dovranno essere gestiti con eccezione alcuni metodi specifici (es. Numero di thread attivi o numero di connessioni attivi)
  268.              *                per i quali si dovranno invocare tutti i nodi e aggregare i risultati.
  269.              * */
  270.            
  271.             String attributeName = req.getParameter(CostantiPdD.CHECK_STATO_PDD_ATTRIBUTE_NAME);
  272.             String attributeValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_ATTRIBUTE_VALUE);
  273.             String attributeBooleanValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_ATTRIBUTE_BOOLEAN_VALUE);
  274.             String methodName = req.getParameter(CostantiPdD.CHECK_STATO_PDD_METHOD_NAME);
  275.             String parameterValues = formatParameters(req);
  276.             logDebug(log,"==============");
  277.             if(attributeName!=null){
  278.                 logDebug(log,"resourceName["+resourceName+"] attributeName["+attributeName+"] attributeValue["+attributeValue+"] attributeBooleanValue["+attributeBooleanValue+"] ...");
  279.             }
  280.             else {
  281.                 logDebug(log,"resourceName["+resourceName+"] methodName["+methodName+"]"+parameterValues+" ...");
  282.             }
  283.             boolean invokeAllNodes = false;
  284.             boolean aggregate = false;
  285.            
  286.             String resourcePrefix = "[resource: "+resourceName+"] ";
  287.             String tipoOperazioneAsync = null;
  288.             int asyncCheckInterval = properties.getProxyReadJMXResourcesAsyncProcessByTimerCheckInterval();
  289.             if(asyncMode) {
  290.                 if(attributeName!=null && (attributeValue!=null || attributeBooleanValue!=null)) {
  291.                     tipoOperazioneAsync = resourcePrefix+"setAttribute '"+attributeName+"'";        
  292.                 }
  293.                 else {
  294.                     tipoOperazioneAsync = resourcePrefix+methodName;
  295.                 }
  296.             }
  297.            
  298.             if(attributeName!=null && (attributeValue!=null || attributeBooleanValue!=null)) {
  299.                 invokeAllNodes = true; // setAttribute
  300.             }
  301.             else if(methodName!=null){
  302.                 if(JMXUtils.CACHE_METHOD_NAME_RESET.equals(methodName) ||
  303.                         JMXUtils.CACHE_METHOD_NAME_REMOVE_OBJECT.equals(methodName)) {
  304.                     invokeAllNodes = true;
  305.                 }
  306.                 else if(CostantiPdD.JMX_GESTORE_RICHIESTE.equals(resourceName)
  307.                         &&
  308.                         (GestoreRichieste.CACHE_METHOD_NAME_REMOVE_DATI_CONTROLLO_TRAFFICO_GLOBALE.equals(methodName)
  309.                                 ||
  310.                                 GestoreRichieste.CACHE_METHOD_NAME_REMOVE_DATI_CONTROLLO_TRAFFICO_API.equals(methodName))
  311.                     ) {
  312.                     invokeAllNodes = true;
  313.                 }
  314.                 else if(CostantiPdD.JMX_CONFIGURAZIONE_PDD.equals(resourceName)
  315.                         &&
  316.                         (
  317.                                 methodName.startsWith(ConfigurazionePdD.RIPULISCI_RIFERIMENTI_CACHE_PREFIX)
  318.                                 ||
  319.                                 ConfigurazionePdD.ABILITA_PORTA_DELEGATA.equals(methodName)
  320.                                 ||
  321.                                 ConfigurazionePdD.DISABILITA_PORTA_DELEGATA.equals(methodName)
  322.                                 ||
  323.                                 ConfigurazionePdD.ABILITA_PORTA_APPLICATIVA.equals(methodName)
  324.                                 ||
  325.                                 ConfigurazionePdD.DISABILITA_PORTA_APPLICATIVA.equals(methodName)
  326.                                 ||
  327.                                 ConfigurazionePdD.ABILITA_CONNETTORE_MULTIPLO.equals(methodName)
  328.                                 ||
  329.                                 ConfigurazionePdD.DISABILITA_CONNETTORE_MULTIPLO.equals(methodName)
  330.                                 ||
  331.                                 ConfigurazionePdD.ABILITA_SCHEDULING_CONNETTORE_MULTIPLO.equals(methodName)
  332.                                 ||
  333.                                 ConfigurazionePdD.DISABILITA_SCHEDULING_CONNETTORE_MULTIPLO.equals(methodName)
  334.                                 ||
  335.                                 ConfigurazionePdD.ABILITA_SCHEDULING_CONNETTORE_MULTIPLO_RUNTIME.equals(methodName)
  336.                                 ||
  337.                                 ConfigurazionePdD.DISABILITA_SCHEDULING_CONNETTORE_MULTIPLO_RUNTIME.equals(methodName)
  338.                         )
  339.                         ) {
  340.                     invokeAllNodes = true;
  341.                 }
  342.                 else if(CostantiPdD.JMX_STATO_SERVIZI_PDD.equals(resourceName)
  343.                         &&
  344.                         (
  345.                                 StatoServiziJMXResource.ABILITA_COMPONENTE_PD.equals(methodName)
  346.                                 ||
  347.                                 StatoServiziJMXResource.DISABILITA_COMPONENTE_PD.equals(methodName)
  348.                                 ||
  349.                                 StatoServiziJMXResource.ABILITA_COMPONENTE_PA.equals(methodName)
  350.                                 ||
  351.                                 StatoServiziJMXResource.DISABILITA_COMPONENTE_PA.equals(methodName)
  352.                                 ||
  353.                                 StatoServiziJMXResource.ABILITA_COMPONENTE_IM.equals(methodName)
  354.                                 ||
  355.                                 StatoServiziJMXResource.DISABILITA_COMPONENTE_IM.equals(methodName)
  356.                         )
  357.                         ) {
  358.                     invokeAllNodes = true;
  359.                 }
  360.                 else if(CostantiPdD.JMX_LOAD_BALANCER.equals(resourceName)
  361.                         &&
  362.                         (
  363.                                 GestoreConsegnaApplicativi.UPDATE_CONNETTORI_PRIORITARI.equals(methodName)
  364.                                 ||
  365.                                 GestoreConsegnaApplicativi.RESET_CONNETTORI_PRIORITARI.equals(methodName)
  366.                         )
  367.                         ) {
  368.                     invokeAllNodes = true;
  369.                 }
  370.                 else if(
  371.                         (
  372.                                 CostantiPdD.JMX_MONITORAGGIO_RISORSE.equals(resourceName)
  373.                                 &&
  374.                                 (
  375.                                     MonitoraggioRisorse.CONNESSIONI_ALLOCATE_DB_MANAGER.equals(methodName)
  376.                                     ||
  377.                                     MonitoraggioRisorse.CONNESSIONI_ALLOCATE_QUEUE_MANAGER.equals(methodName)
  378.                                     ||
  379.                                     MonitoraggioRisorse.TRANSAZIONI_ATTIVE_ID.equals(methodName)
  380.                                     ||
  381.                                     MonitoraggioRisorse.TRANSAZIONI_ATTIVE_ID_PROTOCOLLO.equals(methodName)
  382.                                     ||
  383.                                     MonitoraggioRisorse.CONNESSIONI_ALLOCATE_CONNETTORI_PD.equals(methodName)
  384.                                     ||
  385.                                     MonitoraggioRisorse.CONNESSIONI_ALLOCATE_CONNETTORI_PA.equals(methodName)
  386.                                 )  
  387.                         )
  388.                        
  389.                         ||
  390.                        
  391.                         (
  392.                                 Costanti.JMX_NAME_DATASOURCE_PDD.equals(resourceName)
  393.                                 &&
  394.                                 JmxDataSource.CONNESSIONI_ALLOCATE.equals(methodName)
  395.                         )
  396.                        
  397.                         ||
  398.                        
  399.                         (
  400.                                 CostantiPdD.JMX_LOAD_BALANCER.equals(resourceName)
  401.                                 &&
  402.                                 GestoreConsegnaApplicativi.THREAD_POOL_STATUS.equals(methodName)
  403.                         )
  404.                     ){
  405.                     invokeAllNodes = true;
  406.                     aggregate = true;
  407.                     if(asyncMode) {
  408.                         String msg = SERVIZIO_NON_DISPONIBILE;
  409.                         String logMsg = msg+". L'operazione richiesta ("+resourcePrefix+methodName+") richiede un'aggregazione non attuabile in modalità asincrona";
  410.                         sendError(res, log, msg, 500, logMsg);  
  411.                         return;
  412.                     }
  413.                 }
  414.                        
  415.             }
  416.            
  417.             if(invokeAllNodes) {
  418.                
  419.                 // Se anche solo uno dei nodi restituisce errore, viene ritornato quell’errore (si tratta di un caso anormale).
  420.                 /**String urlHttpResponseFailed = null;*/
  421.                 HttpResponse httpResponseFailed = null;
  422.                 /**String urlHttpResponseOk = null;*/
  423.                 HttpResponse httpResponseOk = null;
  424.                 String urlT = null;
  425.                 Throwable t = null;
  426.                 ResultAggregate resultAggregate = null;
  427.                
  428.                 logDebug(log,"Invoke all node ...");
  429.                                
  430.                 List<String> lUsed = list;
  431.                 if(asyncMode) {
  432.                     // effettuo solo una registrazione
  433.                     lUsed = new ArrayList<>();
  434.                     lUsed.add("localhost"); // verra poi sostituito con hostnameAsync
  435.                 }
  436.                
  437.                 for (String hostname : lUsed) {
  438.                     String url = null;
  439.                     try {
  440.                         /**System.out.println("DEBUG");
  441.                         if("Erogatore".equals(hostname)) {
  442.                             port = 8180;
  443.                         }
  444.                         else {
  445.                             port = 8080;
  446.                         }
  447.                         System.out.println("DEBUG");*/
  448.                        
  449.                         String hostnameUsed = hostname;
  450.                         if(asyncMode && hostnameAsync!=null && StringUtils.isNotEmpty(hostnameAsync)) {
  451.                             hostnameUsed = hostnameAsync;
  452.                         }
  453.                        
  454.                         int portUsed = port;
  455.                         Integer portHostname = properties.getProxyReadJMXResourcesPort(hostname);
  456.                         if(portHostname!=null && portHostname.intValue()>0) {
  457.                             portUsed = portHostname.intValue();
  458.                         }
  459.                        
  460.                         boolean addContext = !asyncMode || !saveContextOnlyOperation;
  461.                         url = buildUrl(log, addContext, protocol, hostnameUsed, portUsed, context, parameters);
  462.                        
  463.                         if(aggregate && asyncMode) {
  464.                             // c'e' un controllo prima e quindi questa eccezione non dovrebbe avvenire
  465.                             throw new CoreException("L'operazione richiesta ("+url+") richiede un'aggregazione non attuabile in modalità asincrona");
  466.                         }
  467.                        
  468.                         HttpResponse httpResponse = null;
  469.                         if(asyncMode) {
  470.                             /**System.out.println("SAVE ALL METHOD BY URL '"+url+"'");*/
  471.                             httpResponse = saveOperation(proxyOperationService, url, tipoOperazioneAsync, log, asyncCheckInterval);
  472.                         }
  473.                         else {
  474.                             /**System.out.println("INVOKE ALL METHOD BY URL '"+url+"'");*/
  475.                             httpResponse = invokeHttp(url,
  476.                                     readTimeout, connectTimeout,
  477.                                     usernameCheck, passwordCheck,
  478.                                     https, verificaHostname, autenticazioneServer,
  479.                                     autenticazioneServerPath, autenticazioneServerType,  autenticazioneServerPassword);
  480.                         }
  481.                        
  482.                         String sResponse = null;
  483.                         if(httpResponse.getContent()!=null) {
  484.                             sResponse = new String(httpResponse.getContent());
  485.                         }
  486.                         boolean error = sResponse!=null && sResponse.startsWith(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA);
  487.                        
  488.                         if(httpResponse.getResultHTTPOperation()==200 && !error) {
  489.                             if(httpResponseOk==null) {
  490.                                 httpResponseOk = httpResponse;
  491.                                 /**urlHttpResponseOk = url;*/
  492.                             }
  493.                             if(aggregate) {
  494.                                 if(resultAggregate==null) {
  495.                                     resultAggregate = new ResultAggregate(resourceName, methodName);
  496.                                 }
  497.                                 resultAggregate.addResponse(sResponse, hostname);
  498.                             }
  499.                         }
  500.                         else {
  501.                             if(httpResponseFailed==null) {
  502.                                 httpResponseFailed = httpResponse;
  503.                                 /**urlHttpResponseFailed = url;*/
  504.                             }
  505.                         }
  506.                        
  507.                         logDebug(log,"Invoked '"+hostname+"' ("+httpResponse.getResultHTTPOperation()+")");
  508.                        
  509.                     }catch(Exception e) {
  510.                         String msg = "("+hostname+") Servizio non disponibile";
  511.                         t = new Exception(msg, e);
  512.                         urlT = url;
  513.                     }
  514.                 }
  515.                
  516.                 if(t!=null) {
  517.                     String msg = t.getMessage();
  518.                     String logMsg = "error occurs: "+t.getMessage();
  519.                     sendError(res, log, msg, 500, logMsg, t);  
  520.                 }
  521.                 else if(httpResponseFailed!=null) {
  522.                     logDebug(log,"Invoke all node complete 'ERROR'");
  523.                     writeResponse(httpResponseFailed, res, log);
  524.                 }
  525.                 else if(resultAggregate!=null) {
  526.                     logDebug(log,"Invoke all node complete 'Aggregate OK'");
  527.                     writeResponse(resultAggregate.getHttpResponse(), res, log);
  528.                 }
  529.                 else if(httpResponseOk!=null) {
  530.                     logDebug(log,"Invoke all node complete 'OK'");
  531.                     writeResponse(httpResponseOk, res, log);
  532.                 }
  533.                 else {
  534.                     String msg = SERVIZIO_NON_DISPONIBILE;
  535.                     String logMsg = "'CasoNonPrevisto' (url: "+urlT+") "+msg;
  536.                     sendError(res, log, msg, 500, logMsg);  
  537.                 }

  538.             }
  539.             else {
  540.                
  541.                 logDebug(log,"Invoke single node '"+list.get(0)+"' ...");
  542.                
  543.                 // Viene invocato un nodo a caso (il primo essendo quello piu' vecchio)
  544.                 String url = null;
  545.                 try {
  546.                    
  547.                     String hostname = list.get(0);
  548.                     String hostnameUsed = hostname;
  549.                     if(asyncMode && hostnameAsync!=null && StringUtils.isNotEmpty(hostnameAsync)) {
  550.                         hostnameUsed = hostnameAsync;
  551.                     }
  552.                    
  553.                     int portUsed = port;
  554.                     Integer portHostname = properties.getProxyReadJMXResourcesPort(hostname);
  555.                     if(portHostname!=null && portHostname.intValue()>0) {
  556.                         portUsed = portHostname.intValue();
  557.                     }
  558.                    
  559.                     url = buildUrl(log, true, protocol, hostnameUsed, portUsed, context, parameters);
  560.                     /**System.out.println("INVOKE SINGLE METHOD BY URL '"+url+"'");*/
  561.                     HttpResponse httpResponse = invokeHttp(url,
  562.                             readTimeout, connectTimeout,
  563.                             usernameCheck, passwordCheck,
  564.                             https, verificaHostname, autenticazioneServer,
  565.                             autenticazioneServerPath, autenticazioneServerType,  autenticazioneServerPassword);
  566.                     writeResponse(httpResponse, res, log);
  567.                    
  568.                 }catch(Exception e) {
  569.                     String msg = SERVIZIO_NON_DISPONIBILE;
  570.                     String logMsg = msg+" (url: "+url+"): "+e.getMessage();
  571.                     sendError(res, log, msg, 500, logMsg, e);  
  572.                 }
  573.             }
  574.            
  575.         }
  576.         else {
  577.            
  578.             logDebug(log,"Invoke single node CHECK '"+list.get(0)+"' ...");
  579.            
  580.             // Servizio check del gateway
  581.             // Viene invocato un nodo a caso (il primo essendo quello piu' vecchio)
  582.             String url = null;
  583.             try {
  584.                
  585.                 String hostname = list.get(0);
  586.                 String hostnameUsed = hostname;
  587.                 if(asyncMode && hostnameAsync!=null && StringUtils.isNotEmpty(hostnameAsync)) {
  588.                     hostnameUsed = hostnameAsync;
  589.                 }
  590.                
  591.                 int portUsed = port;
  592.                 Integer portHostname = properties.getProxyReadJMXResourcesPort(hostname);
  593.                 if(portHostname!=null && portHostname.intValue()>0) {
  594.                     portUsed = portHostname.intValue();
  595.                 }
  596.                
  597.                 url = buildUrl(log, true, protocol, hostnameUsed, portUsed, context, parameters);
  598.                 /**System.out.println("INVOKE SINGLE ATTRIBUTE BY URL '"+url+"'");*/
  599.                 HttpResponse httpResponse = invokeHttp(url,
  600.                                 readTimeout, connectTimeout,
  601.                                 usernameCheck, passwordCheck,
  602.                                 https, verificaHostname, autenticazioneServer,
  603.                                 autenticazioneServerPath, autenticazioneServerType,  autenticazioneServerPassword);
  604.                 writeResponse(httpResponse, res, log);
  605.             }catch(Exception e) {
  606.                 String msg = SERVIZIO_NON_DISPONIBILE;
  607.                 String logMsg = msg+" (url: "+url+"): "+e.getMessage();
  608.                 sendError(res, log, msg, 500, logMsg, e);  
  609.             }
  610.         }
  611.        

  612.     }
  613.    
  614.     public static HttpResponse invokeHttp(String url,
  615.             int readTimeout, int connectTimeout,
  616.             String usernameCheck, String passwordCheck,
  617.             boolean https, boolean verificaHostname, boolean autenticazioneServer,
  618.             String autenticazioneServerPath, String autenticazioneServerType, String autenticazioneServerPassword) throws UtilsException {
  619.         HttpResponse response = null;
  620.         if(https) {
  621.             HttpRequest httpRequest = new HttpRequest();
  622.             httpRequest.setUrl(url);
  623.             httpRequest.setConnectTimeout(connectTimeout);
  624.             httpRequest.setReadTimeout(readTimeout);
  625.             httpRequest.setUsername(usernameCheck);
  626.             httpRequest.setPassword(passwordCheck);
  627.             httpRequest.setMethod(HttpRequestMethod.GET);
  628.             httpRequest.setHostnameVerifier(verificaHostname);
  629.             if(autenticazioneServer) {
  630.                 httpRequest.setTrustStorePath(autenticazioneServerPath);
  631.                 httpRequest.setTrustStoreType(autenticazioneServerType);
  632.                 httpRequest.setTrustStorePassword(autenticazioneServerPassword);
  633.             }
  634.             else {
  635.                 httpRequest.setTrustAllCerts(true);
  636.             }
  637.             response = HttpUtilities.httpInvoke(httpRequest);
  638.         }
  639.         else {
  640.             response = HttpUtilities.getHTTPResponse(url,
  641.                     readTimeout, connectTimeout,
  642.                     usernameCheck, passwordCheck);
  643.         }
  644.         return response;
  645.     }
  646.     private HttpResponse saveOperation(IProxyOperationService proxyOperationService, String url, String description, Logger log, int asyncCheckInterval) {
  647.         HttpResponse response = new HttpResponse();
  648.         try {
  649.            
  650.             ProxyOperation proxyOperation = new ProxyOperation();
  651.             proxyOperation.setCommand(url);
  652.             proxyOperation.setDescription(description);
  653.             proxyOperation.setRegistrationTime(DateManager.getDate());
  654.             proxyOperationService.save(proxyOperation);
  655.            
  656.             response.setResultHTTPOperation(200);
  657.             response.setContentType(HttpConstants.CONTENT_TYPE_PLAIN);
  658.             response.setContent((JMXUtils.MSG_OPERAZIONE_EFFETTUATA_SUCCESSO_PREFIX+JMXUtils.MSG_OPERAZIONE_REGISTRATA_SUCCESSO.replace(JMXUtils.MSG_OPERAZIONE_REGISTRATA_SUCCESSO_TEMPLATE_SECONDI, asyncCheckInterval+"")).getBytes());
  659.         }catch(Exception t) {
  660.             response.setResultHTTPOperation(500);
  661.             response.setContentType(HttpConstants.CONTENT_TYPE_PLAIN);
  662.             logError(log,"[Proxy] saveOperation failed: "+t.getMessage(),t);
  663.             response.setContent((JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA+t.getMessage()).getBytes());
  664.         }
  665.         return response;
  666.     }

  667.     private void writeResponse(HttpResponse httpResponse, HttpServletResponse res, Logger log) {
  668.         try {
  669.             res.setStatus(httpResponse.getResultHTTPOperation());
  670.             if(httpResponse.getContentType()!=null) {
  671.                 res.setContentType(httpResponse.getContentType());
  672.             }
  673.             if(httpResponse.getContent()!=null) {
  674.                 res.getOutputStream().write(httpResponse.getContent());
  675.             }
  676.         }catch(Exception t) {
  677.             logError(log,"[Proxy] WriteResponse failed: "+t.getMessage(),t);
  678.         }
  679.     }
  680.    
  681.     private String buildUrl(Logger log, boolean addContext, String protocol, String hostname, int port, String context, Map<String, List<String>> parameters ) {
  682.         StringBuilder sb = new StringBuilder();
  683.         if(addContext) {
  684.             sb.append(protocol);
  685.             sb.append(hostname);
  686.             sb.append(":");
  687.             sb.append(port);
  688.         }
  689.         sb.append(context);
  690.         return TransportUtils.buildUrlWithParameters(parameters, sb.toString(), log);
  691.     }
  692.    
  693.     private Map<String, List<String>> buildParameters(HttpServletRequest req) {
  694.         Map<String, List<String>> parameters = new HashMap<>();        
  695.         java.util.Enumeration<?> en = req.getParameterNames();
  696.         while(en.hasMoreElements()){
  697.             String nomeProperty = (String)en.nextElement();
  698.             String [] s = req.getParameterValues(nomeProperty);
  699.             List<String> values = new ArrayList<>();
  700.             if(s!=null && s.length>0) {
  701.                 for (int i = 0; i < s.length; i++) {
  702.                     String value = s[i];
  703.                     values.add(value);
  704.                 }
  705.             }
  706.             else {
  707.                 values.add(req.getParameter(nomeProperty));
  708.             }
  709.             parameters.put(nomeProperty,values);
  710.         }
  711.         return parameters;
  712.     }
  713.    
  714.     private static String formatParameters(HttpServletRequest req) {
  715.         StringBuilder sb = new StringBuilder("");
  716.        
  717.         String paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_VALUE);
  718.         if(paramValue!=null) {
  719.             sb.append(" ").append("paramValue[").append(paramValue).append("]");
  720.         }
  721.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_INT_VALUE);
  722.         if(paramValue!=null) {
  723.             sb.append(" ").append("paramIntValue[").append(paramValue).append("]");
  724.         }
  725.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_LONG_VALUE);
  726.         if(paramValue!=null) {
  727.             sb.append(" ").append("paramLongValue[").append(paramValue).append("]");
  728.         }
  729.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_BOOLEAN_VALUE);
  730.         if(paramValue!=null) {
  731.             sb.append(" ").append("paramBooleanValue[").append(paramValue).append("]");
  732.         }
  733.        
  734.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_VALUE_2);
  735.         if(paramValue!=null) {
  736.             sb.append(" ").append("paramValue2[").append(paramValue).append("]");
  737.         }
  738.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_INT_VALUE_2);
  739.         if(paramValue!=null) {
  740.             sb.append(" ").append("paramIntValue2[").append(paramValue).append("]");
  741.         }
  742.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_LONG_VALUE_2);
  743.         if(paramValue!=null) {
  744.             sb.append(" ").append("paramLongValue2[").append(paramValue).append("]");
  745.         }
  746.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_BOOLEAN_VALUE_2);
  747.         if(paramValue!=null) {
  748.             sb.append(" ").append("paramBooleanValue2[").append(paramValue).append("]");
  749.         }
  750.        
  751.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_VALUE_3);
  752.         if(paramValue!=null) {
  753.             sb.append(" ").append("paramValue3[").append(paramValue).append("]");
  754.         }
  755.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_INT_VALUE_3);
  756.         if(paramValue!=null) {
  757.             sb.append(" ").append("paramIntValue3[").append(paramValue).append("]");
  758.         }
  759.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_LONG_VALUE_3);
  760.         if(paramValue!=null) {
  761.             sb.append(" ").append("paramLongValue3[").append(paramValue).append("]");
  762.         }
  763.         paramValue = req.getParameter(CostantiPdD.CHECK_STATO_PDD_PARAM_BOOLEAN_VALUE_3);
  764.         if(paramValue!=null) {
  765.             sb.append(" ").append("paramBooleanValue3[").append(paramValue).append("]");
  766.         }
  767.        
  768.         return sb.toString();
  769.     }
  770. }

  771. class ResultAggregate {
  772.    
  773.     private String resourceName;
  774.     private String methodName;
  775.     private List<String> list1 = new ArrayList<>();
  776.     private List<String> list2 = new ArrayList<>();
  777.     private List<String> list3 = new ArrayList<>();
  778.     private List<String> list4 = new ArrayList<>();
  779.     private List<String> list5 = new ArrayList<>();
  780.     private List<String> list6 = new ArrayList<>();
  781.     private List<String> list7 = new ArrayList<>();
  782.     private List<String> list8 = new ArrayList<>();
  783.    
  784.     ResultAggregate(String resourceName, String methodName){
  785.         this.resourceName = resourceName;
  786.         this.methodName = methodName;
  787.     }
  788.    
  789.     public void addResponse(String sResponse, String hostname) throws IOException {
  790.         if(sResponse==null) {
  791.             return;
  792.         }
  793.         try(StringReader sReader = new StringReader(sResponse);
  794.             BufferedReader bReader = new BufferedReader(sReader)) {
  795.             String line = bReader.readLine();
  796.             List<String> listUse = this.list1;
  797.             while (line != null) {
  798.                 if(MonitoraggioRisorse.MSG_NESSUNA_CONNESSIONE_ALLOCATA.equals(line) ||
  799.                         MonitoraggioRisorse.MSG_NESSUNA_TRANSAZIONE_ATTIVA.equals(line) ||
  800.                         JmxDataSource.MSG_NESSUNA_CONNESSIONE_ALLOCATA.equals(line)) {
  801.                     break;
  802.                 }
  803.                 try {
  804.                     if(line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_ALLOCATE) ||
  805.                             line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_HTTP_ALLOCATE) ||
  806.                             line.contains(MonitoraggioRisorse.MSG_TRANSAZIONI_ATTIVE) ||
  807.                             line.contains(MonitoraggioRisorse.MSG_TRANSAZIONI_ATTIVE_ID_PROTOCOLLO) ||
  808.                             line.contains(JmxDataSource.MSG_CONNESSIONI_ALLOCATE)) {
  809.                         continue;
  810.                     }
  811.                     if(line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_ALLOCATE_TRANSAZIONI)) {
  812.                         listUse = this.list2;
  813.                         continue;
  814.                     }
  815.                     if(line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_ALLOCATE_STATISTICHE)) {
  816.                         listUse = this.list3;
  817.                         continue;
  818.                     }
  819.                     if(line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_ALLOCATE_CONSEGNE_PRESE_IN_CARICO_SMISTATORE)) {
  820.                         listUse = this.list4;
  821.                         continue;
  822.                     }
  823.                     if(line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_ALLOCATE_CONSEGNE_PRESE_IN_CARICO_RUNTIME)) {
  824.                         listUse = this.list5;
  825.                         continue;
  826.                     }
  827.                     if(line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_ALLOCATE_CONSEGNE_PRESE_IN_CARICO_TRANSAZIONI)) {
  828.                         listUse = this.list6;
  829.                         continue;
  830.                     }
  831.                     if(line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_ALLOCATE_CONSEGNE_MESSAGE_BOX_RUNTIME)) {
  832.                         listUse = this.list7;
  833.                         continue;
  834.                     }
  835.                     if(line.contains(MonitoraggioRisorse.MSG_CONNESSIONI_ALLOCATE_CONSEGNE_MESSAGE_BOX_TRANSAZIONI)) {
  836.                         listUse = this.list8;
  837.                         continue;
  838.                     }
  839.                    
  840.                     listUse.add(line+" ["+hostname+"]");
  841.                 }finally {
  842.                     // read next line
  843.                     line = bReader.readLine();
  844.                 }
  845.             }
  846.         }
  847.     }
  848.    
  849.     public HttpResponse getHttpResponse() {
  850.         HttpResponse httpResponse = new HttpResponse();
  851.         httpResponse.setResultHTTPOperation(200);
  852.        
  853.         String content = null;
  854.         if(CostantiPdD.JMX_MONITORAGGIO_RISORSE.equals(this.resourceName)) {
  855.             if(MonitoraggioRisorse.CONNESSIONI_ALLOCATE_DB_MANAGER.equals(this.methodName) ||
  856.                     MonitoraggioRisorse.CONNESSIONI_ALLOCATE_QUEUE_MANAGER.equals(this.methodName)) {
  857.                 String[] risorse = null;
  858.                 String[] risorseTransaction = null;
  859.                 String[] risorseStatistiche = null;
  860.                 String[] risorseConsegnePreseInCaricoSmistatore = null;
  861.                 String[] risorseConsegnePreseInCaricoRuntime = null;
  862.                 String[] risorseConsegnePreseInCaricoTransazioni = null;
  863.                 String[] risorseConsegneMessageBoxRuntime = null;
  864.                 String[] risorseConsegneMessageBoxTransazioni = null;
  865.                 if(this.list1!=null && !this.list1.isEmpty()) {
  866.                     risorse = this.list1.toArray(new String[1]);
  867.                 }
  868.                 if(this.list2!=null && !this.list2.isEmpty()) {
  869.                     risorseTransaction = this.list2.toArray(new String[1]);
  870.                 }
  871.                 if(this.list3!=null && !this.list3.isEmpty()) {
  872.                     risorseStatistiche = this.list3.toArray(new String[1]);
  873.                 }
  874.                 if(this.list4!=null && !this.list4.isEmpty()) {
  875.                     risorseConsegnePreseInCaricoSmistatore = this.list4.toArray(new String[1]);
  876.                 }
  877.                 if(this.list5!=null && !this.list5.isEmpty()) {
  878.                     risorseConsegnePreseInCaricoRuntime = this.list5.toArray(new String[1]);
  879.                 }
  880.                 if(this.list6!=null && !this.list6.isEmpty()) {
  881.                     risorseConsegnePreseInCaricoTransazioni = this.list6.toArray(new String[1]);
  882.                 }
  883.                 if(this.list7!=null && !this.list7.isEmpty()) {
  884.                     risorseConsegneMessageBoxRuntime = this.list7.toArray(new String[1]);
  885.                 }
  886.                 if(this.list8!=null && !this.list8.isEmpty()) {
  887.                     risorseConsegneMessageBoxTransazioni = this.list8.toArray(new String[1]);
  888.                 }
  889.                 if(MonitoraggioRisorse.CONNESSIONI_ALLOCATE_DB_MANAGER.equals(this.methodName)) {
  890.                     content =  MonitoraggioRisorse.getResultUsedDBConnections(risorse, risorseTransaction, risorseStatistiche,
  891.                             risorseConsegnePreseInCaricoSmistatore, risorseConsegnePreseInCaricoRuntime, risorseConsegnePreseInCaricoTransazioni,
  892.                             risorseConsegneMessageBoxRuntime, risorseConsegneMessageBoxTransazioni);
  893.                 }
  894.                 else if(MonitoraggioRisorse.CONNESSIONI_ALLOCATE_QUEUE_MANAGER.equals(this.methodName)) {
  895.                     content =  MonitoraggioRisorse.getResultUsedQueueConnections(risorse);
  896.                 }
  897.             }
  898.             else if(MonitoraggioRisorse.TRANSAZIONI_ATTIVE_ID.equals(this.methodName)) {
  899.                 content =  MonitoraggioRisorse.getResultTransazioniAttiveId(this.list1);
  900.             }
  901.             else if(MonitoraggioRisorse.TRANSAZIONI_ATTIVE_ID_PROTOCOLLO.equals(this.methodName)) {
  902.                 content =  MonitoraggioRisorse.getResultTransazioniAttiveIdProtocollo(this.list1);
  903.             }
  904.             else if(MonitoraggioRisorse.CONNESSIONI_ALLOCATE_CONNETTORI_PD.equals(this.methodName)) {
  905.                 content =  MonitoraggioRisorse.getResultActiveConnections(this.list1);
  906.             }
  907.             else if(MonitoraggioRisorse.CONNESSIONI_ALLOCATE_CONNETTORI_PA.equals(this.methodName)) {
  908.                 content =  MonitoraggioRisorse.getResultActiveConnections(this.list1);
  909.             }
  910.         }
  911.         else if(Costanti.JMX_NAME_DATASOURCE_PDD.equals(this.resourceName)) {
  912.             String[] risorse = null;
  913.             if(this.list1!=null && !this.list1.isEmpty()) {
  914.                 risorse = this.list1.toArray(new String[1]);
  915.             }
  916.             content = JmxDataSource.getResultUsedDBConnections(risorse);
  917.         }
  918.         else if(CostantiPdD.JMX_LOAD_BALANCER.equals(this.resourceName) &&
  919.             this.list1!=null && !this.list1.isEmpty()) {
  920.             StringBuilder sb = new StringBuilder();
  921.             for (String l : this.list1) {
  922.                 if(sb.length()>0) {
  923.                     sb.append("\n");
  924.                 }
  925.                 sb.append(l);
  926.             }
  927.             content = sb.toString();
  928.         }
  929.        
  930.         if(content!=null) {
  931.             httpResponse.setContentType(HttpConstants.CONTENT_TYPE_PLAIN);
  932.             httpResponse.setContent(content.getBytes());
  933.         }
  934.         return httpResponse;
  935.     }

  936. }