JWS-121 Improved the AnnualStat and ServiceStatus classes so they start the scheduler...
authorFábio Madeira <fmmarquesmadeira@dundee.ac.uk>
Fri, 2 Jun 2017 14:07:58 +0000 (15:07 +0100)
committerFábio Madeira <fmmarquesmadeira@dundee.ac.uk>
Fri, 2 Jun 2017 14:07:58 +0000 (15:07 +0100)
conf/Engine.local.properties
webservices/compbio/stat/servlet/AnnualStat.java
webservices/compbio/stat/servlet/ServiceStatus.java
website/statpages/MonthlySummary.jsp
website/statpages/ServicesStatus.jsp

index 1f54acb..39d7e63 100644 (file)
@@ -36,3 +36,9 @@ local.jobdir.maxlifespan=168
 # Frequency of cleaning job directory (in minutes)\r
 # normal rate: once a date = 24 * 60 = 1440\r
 local.jobdir.cleaning.frequency=1440\r
+\r
+#################################################################################\r
+# Frequency of Service Status Memory Cache refresh (in minutes)\r
+local.service.status.refresh.frequency=10\r
+# Frequency of Usage Statistics Memory Cache refresh (in minutes)\r
+local.usage.stats.refresh.frequency=60\r
index eead7a5..bfa439c 100644 (file)
@@ -19,6 +19,8 @@ package compbio.stat.servlet;
 \r
 import java.io.IOException;\r
 import java.io.PrintWriter;\r
+import java.net.HttpURLConnection;\r
+import java.net.URL;\r
 import java.sql.SQLException;\r
 import java.util.Date;\r
 import java.util.Map;\r
@@ -31,51 +33,175 @@ import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;\r
 import javax.servlet.http.HttpServletResponse;\r
 \r
+import compbio.engine.conf.PropertyHelperManager;\r
 import compbio.stat.collector.StatDB;\r
-import compbio.stat.servlet.util.StatCollection;\r
-import compbio.stat.servlet.util.Totals;\r
+import compbio.stat.servlet.util.*;\r
+import compbio.util.PropertyHelper;\r
+import compbio.util.Util;\r
+\r
+import org.apache.log4j.Logger;\r
 \r
 public class AnnualStat extends HttpServlet {\r
 \r
-       @Override\r
-       protected void doGet(HttpServletRequest req, HttpServletResponse resp)\r
-                       throws ServletException, IOException {\r
-\r
-               try {\r
-                       long startTime = System.nanoTime();\r
-                       StatDB db = new StatDB();\r
-                       Date earliestRec = db.getEarliestRecord();\r
-                       if (earliestRec == null) {\r
-                               PrintWriter writer = resp.getWriter();\r
-                               writer.println("No statistics found in the database. Please allow "\r
-                                               + "at least one hour after a server start for the statistics "\r
-                                               + "collector to collect the data. ");\r
-                               writer.close();\r
-                               return;\r
-                       }\r
-                       Map<Date, Totals> monthlyTotals = StatCollection.getStats(earliestRec);\r
-                       long endTime = System.nanoTime();\r
-                       req.setAttribute("stat", monthlyTotals);\r
-                       req.setAttribute("total", Totals.sumOfTotals(monthlyTotals));\r
-//                     req.setAttribute("timeexec", (endTime - startTime) / 1000000);\r
-                       req.setAttribute("timeexec", (endTime - startTime) / 100000000);\r
-                       String timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(\r
-                               Calendar.getInstance().getTime());\r
-                       req.setAttribute("timestamp", timeStamp);\r
-\r
-                       RequestDispatcher dispatcher = req.getRequestDispatcher("statpages/MonthlySummary.jsp");\r
-\r
-                       req.setAttribute("isAdmin", isAdmin(req));\r
-                       dispatcher.forward(req, resp);\r
-\r
-               } catch (SQLException e) {\r
-                       e.printStackTrace();\r
-                       throw new ServletException(e);\r
-               }\r
-       }\r
-\r
-       static boolean isAdmin(final HttpServletRequest request) {\r
-               return request.isUserInRole("admin");\r
-       }\r
+    private static final Logger log = Logger.getLogger(AnnualStat.class);\r
+\r
+    private static PropertyHelper ph = PropertyHelperManager.getPropertyHelper();\r
+\r
+    private final Scheduler scheduler = new Scheduler();\r
+\r
+    private static int getIntProperty(String propValue) {\r
+        int value = 0;\r
+        if (!Util.isEmpty(propValue)) {\r
+            propValue = propValue.trim();\r
+            value = Integer.parseInt(propValue);\r
+        }\r
+        return value;\r
+    }\r
+\r
+    static int refreshUsageStatsFrequency() {\r
+        return getIntProperty(ph.getProperty("local.usage.stats.refresh.frequency"));\r
+    }\r
+\r
+    @Override\r
+    public void init() {\r
+        // startup the scheduler with current time\r
+        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);\r
+        int min = Calendar.getInstance().get(Calendar.MINUTE);\r
+        int sec = Calendar.getInstance().get(Calendar.SECOND);\r
+        // refresh sleep time (in between requests) - minutes\r
+        final int refresh_freq = refreshUsageStatsFrequency();\r
+\r
+        scheduler.schedule(new SchedulerTask() {\r
+            public void run() {\r
+                refreshCache();\r
+            }\r
+\r
+            private void refreshCache() {\r
+                hitEndpointForRefresh();\r
+                log.info("Refreshing the In Memory Cache...");\r
+                log.info(String.format("Refreshing again in %d minutes", refresh_freq));\r
+            }\r
+        }, new RefreshIterator(hour, min, sec, refresh_freq));\r
+    }\r
+\r
+    public void clearContextCache() {\r
+        // try remove the current values from the context\r
+        try {\r
+            this.getServletConfig().getServletContext().removeAttribute("usageStatsResults");\r
+            this.getServletConfig().getServletContext().removeAttribute("usageStatsTimestamp");\r
+            this.getServletConfig().getServletContext().removeAttribute("usageStatsStart");\r
+            this.getServletConfig().getServletContext().removeAttribute("usageStatsEnd");\r
+            log.info("In Memory Cache Cleared!");\r
+        } catch (Exception e) {\r
+            log.warn("In Memory Cache Not Cleared. Perhaps not available yet!");\r
+        }\r
+    }\r
+\r
+    private void hitEndpointForRefresh() {\r
+        String endpointURL;\r
+        endpointURL = (String) this.getServletConfig().getServletContext().getAttribute("usageStatsURL");\r
+        if (endpointURL != null){\r
+            try {\r
+                URL url = new URL(endpointURL);\r
+                System.out.println(endpointURL);\r
+                HttpURLConnection connection = (HttpURLConnection) url.openConnection();\r
+                connection.setRequestProperty("User-Agent", "JABAWS Usage Stats Refreshing the Context Cache");\r
+                int status = connection.getResponseCode();\r
+                log.info(String.format("Hitting %s with an internal user-agent! status code: %s",\r
+                        endpointURL, status));\r
+            } catch (IOException e) {\r
+                log.warn("Something wrong when hitting " + endpointURL);\r
+                log.warn(e);\r
+            }\r
+        }\r
+    }\r
+\r
+    public Map<Date, Totals> checkMonthlyTotals(HttpServletResponse resp) throws ServletException, IOException {\r
+\r
+        try {\r
+            System.out.println("Updating the Usage Stats In Memory Cache...");\r
+            StatDB db = new StatDB();\r
+            Date earliestRec = db.getEarliestRecord();\r
+            if (earliestRec == null) {\r
+                PrintWriter writer = resp.getWriter();\r
+                writer.println("No statistics found in the database. Please allow "\r
+                        + "at least one hour after a server start for the statistics "\r
+                        + "collector to collect the data. ");\r
+                writer.close();\r
+                return null;\r
+            }\r
+            return StatCollection.getStats(earliestRec);\r
+        } catch (SQLException e) {\r
+            e.printStackTrace();\r
+            throw new ServletException(e);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp)\r
+            throws ServletException, IOException {\r
+\r
+        Map<Date, Totals> monthlyTotals;\r
+        String timeStamp = new String();\r
+        long startTime;\r
+        long endTime;\r
+        String refresh_freq;\r
+\r
+        // save the main caller URL in the context\r
+        String url = new String();\r
+        url = req.getRequestURL().toString();\r
+        System.out.println("UR: " + url);\r
+        this.getServletConfig().getServletContext().setAttribute("usageStatsURL", url);\r
+\r
+        // check user-agent: this is a trick to get the cache refreshed periodically\r
+        String useragent = new String();\r
+        useragent = req.getHeader("user-agent");\r
+        // check if there are values available in the context\r
+        if (this.getServletConfig().getServletContext().getAttribute("usageStatsResults") == null ||\r
+                useragent.equals("JABAWS Usage Stats Refreshing the Context Cache")) {\r
+\r
+            // get stats from db\r
+            startTime = System.nanoTime();\r
+            monthlyTotals = checkMonthlyTotals(resp);\r
+            endTime = System.nanoTime();\r
+            if (monthlyTotals != null) {\r
+                // try clear the previous values if any\r
+                clearContextCache();\r
+                // add the current values to the context\r
+                this.getServletConfig().getServletContext().setAttribute("usageStatsResults", monthlyTotals);\r
+                timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(\r
+                        Calendar.getInstance().getTime());\r
+                this.getServletConfig().getServletContext().setAttribute("usageStatsTimestamp", timeStamp);\r
+                this.getServletConfig().getServletContext().setAttribute("usageStatsStart", startTime);\r
+                this.getServletConfig().getServletContext().setAttribute("usageStatsEnd", endTime);\r
+                refresh_freq = String.valueOf(refreshUsageStatsFrequency());\r
+                this.getServletConfig().getServletContext().setAttribute("usageStatsRefreshFreq", refresh_freq);\r
+            } else {\r
+                return;\r
+            }\r
+\r
+        } else {\r
+            // get last results available\r
+            monthlyTotals = (Map<Date, Totals>) this.getServletConfig().getServletContext().getAttribute("usageStatsResults");\r
+            timeStamp = (String) this.getServletConfig().getServletContext().getAttribute("usageStatsTimestamp");\r
+            startTime = (Long) this.getServletConfig().getServletContext().getAttribute("usageStatsStart");\r
+            endTime = (Long) this.getServletConfig().getServletContext().getAttribute("usageStatsEnd");\r
+            refresh_freq = (String) this.getServletConfig().getServletContext().getAttribute("usageStatsRefreshFreq");\r
+        }\r
+\r
+        req.setAttribute("stat", monthlyTotals);\r
+        req.setAttribute("total", Totals.sumOfTotals(monthlyTotals));\r
+        req.setAttribute("timeexec", (endTime - startTime) / 100000000);\r
+        req.setAttribute("timestamp", timeStamp);\r
+        req.setAttribute("refreshfreq", refresh_freq);\r
+        RequestDispatcher dispatcher = req.getRequestDispatcher("statpages/MonthlySummary.jsp");\r
+        req.setAttribute("isAdmin", isAdmin(req));\r
+        dispatcher.forward(req, resp);\r
+\r
+    }\r
+\r
+    static boolean isAdmin(final HttpServletRequest request) {\r
+        return request.isUserInRole("admin");\r
+    }\r
 \r
 }\r
index 0b82be9..8b29ded 100644 (file)
@@ -25,11 +25,8 @@ import java.io.StringWriter;
 import java.lang.management.ManagementFactory;\r
 import java.net.InetAddress;\r
 import java.net.UnknownHostException;\r
-import java.util.ArrayList;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Set;\r
-import java.util.Calendar;\r
+import java.util.*;\r
+import java.net.*;\r
 import java.text.SimpleDateFormat;\r
 \r
 import javax.management.AttributeNotFoundException;\r
@@ -46,6 +43,12 @@ import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;\r
 import javax.servlet.http.HttpServletResponse;\r
 \r
+import compbio.engine.conf.PropertyHelperManager;\r
+import compbio.stat.servlet.util.RefreshIterator;\r
+import compbio.stat.servlet.util.Scheduler;\r
+import compbio.stat.servlet.util.SchedulerTask;\r
+import compbio.util.PropertyHelper;\r
+import compbio.util.Util;\r
 import org.apache.log4j.Logger;\r
 \r
 import compbio.ws.client.Services;\r
@@ -56,106 +59,242 @@ import compbio.ws.client.WSTester;
  * <dl>\r
  * <li>Test web services and display results on the web page</li>\r
  * </dl>\r
- * \r
+ *\r
  * @author pvtroshin\r
- * \r
  */\r
 \r
 public class ServiceStatus extends HttpServlet {\r
 \r
-       private final static Logger log = Logger.getLogger(ServiceStatus.class);\r
-\r
-       private List<String> getEndPoints() throws MalformedObjectNameException, NullPointerException, UnknownHostException,\r
-                       AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException {\r
-               MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\r
-               Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"),\r
-                               Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));\r
-               List<String> endPoints = new ArrayList<String>();\r
-               for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {\r
-                       ObjectName obj = i.next();\r
-                       String scheme = mbs.getAttribute(obj, "scheme").toString();\r
-                       String port = obj.getKeyProperty("port");\r
-                       String hostname = InetAddress.getLocalHost().getHostName();\r
-                       endPoints.add(scheme + "://" + hostname + ":" + port);\r
-               }\r
-               return endPoints;\r
-       }\r
-\r
-       @Override\r
-       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\r
-               /**\r
-                * // PROBLEM: the code tries to test not WS endpoints on an internal\r
-                * Tomcat, but on an external // endpoints with wrong info on the\r
-                * proxing StringBuffer jabawspath = req.getRequestURL(); jabawspath =\r
-                * jabawspath.delete(jabawspath.lastIndexOf("/"), jabawspath.length());\r
-                * String serverPath = jabawspath.toString();\r
-                */\r
-               List<String> eps = new ArrayList<String>();\r
-               try {\r
-                       eps = getEndPoints();\r
-               } catch (MalformedObjectNameException e) {\r
-                       // TODO Auto-generated catch block\r
-                       e.printStackTrace();\r
-               } catch (AttributeNotFoundException e) {\r
-                       // TODO Auto-generated catch block\r
-                       e.printStackTrace();\r
-               } catch (InstanceNotFoundException e) {\r
-                       // TODO Auto-generated catch block\r
-                       e.printStackTrace();\r
-               } catch (NullPointerException e) {\r
-                       // TODO Auto-generated catch block\r
-                       e.printStackTrace();\r
-               } catch (MBeanException e) {\r
-                       // TODO Auto-generated catch block\r
-                       e.printStackTrace();\r
-               } catch (ReflectionException e) {\r
-                       // TODO Auto-generated catch block\r
-                       e.printStackTrace();\r
-               }\r
-               if (1 != eps.size()) {\r
-                       log.info(eps.size() + "EndPoints found");\r
-                       //System.out.println("      " + eps.size() + " EndPoints found");\r
-                       for (String endpoint : eps) {\r
-                               log.info(eps.size() + "EndPoint is " + endpoint);\r
-                               //System.out.println("   EndPoint is " + endpoint);\r
-                       }\r
-               }\r
-\r
-               String serverPath = new String();\r
-               for (String endpoint : eps) {\r
-                       serverPath = endpoint + req.getContextPath();\r
-               }\r
-               //System.out.println("Testing services at " + serverPath);\r
-\r
-               List<ServiceTestResult> testResults = new ArrayList<ServiceTestResult>();\r
-               long startTime = System.nanoTime();\r
-               for (Services service : Services.values()) {\r
-                       StringWriter testres = new StringWriter();\r
-                       PrintWriter writer = new PrintWriter(testres, true);\r
-                       WSTester tester = new WSTester(serverPath, writer);\r
-                       ServiceTestResult result = new ServiceTestResult(service);\r
-                       try {\r
-                               result.failed = tester.checkService(service);\r
-                       } catch (Exception e) {\r
-                               log.info(e, e.getCause());\r
-                               String mess = "Fails to connect to the web service: " + service + ". Reason: ";\r
-                               writer.println(mess + e.getLocalizedMessage() + "\nDetails: ");\r
-                               e.printStackTrace(writer);\r
-                       } finally {\r
-                               writer.close();\r
-                       }\r
-                       result.details = testres.toString();\r
-                       testResults.add(result);\r
-               }\r
-               req.setAttribute("results", testResults);\r
-               long endTime = System.nanoTime();\r
-//             req.setAttribute("timeexec", (endTime - startTime) / 1000000);\r
-               req.setAttribute("timeexec", (endTime - startTime) / 100000000);\r
-               String timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(\r
-                               Calendar.getInstance().getTime());\r
-               req.setAttribute("timestamp", timeStamp);\r
-               RequestDispatcher rd = req.getRequestDispatcher("statpages/ServicesStatus.jsp");\r
-               rd.forward(req, resp);\r
-       }\r
+    private static final Logger log = Logger.getLogger(ServiceStatus.class);\r
+\r
+    private static PropertyHelper ph = PropertyHelperManager.getPropertyHelper();\r
+\r
+    private final Scheduler scheduler = new Scheduler();\r
+\r
+    private List<String> getEndPoints() throws MalformedObjectNameException, NullPointerException, UnknownHostException,\r
+            AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException {\r
+        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\r
+        Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"),\r
+                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));\r
+        List<String> endPoints = new ArrayList<String>();\r
+        for (Iterator<ObjectName> i = objs.iterator(); i.hasNext(); ) {\r
+            ObjectName obj = i.next();\r
+            String scheme = mbs.getAttribute(obj, "scheme").toString();\r
+            String port = obj.getKeyProperty("port");\r
+            String hostname = InetAddress.getLocalHost().getHostName();\r
+            endPoints.add(scheme + "://" + hostname + ":" + port);\r
+        }\r
+        return endPoints;\r
+    }\r
+\r
+    private static int getIntProperty(String propValue) {\r
+        int value = 0;\r
+        if (!Util.isEmpty(propValue)) {\r
+            propValue = propValue.trim();\r
+            value = Integer.parseInt(propValue);\r
+        }\r
+        return value;\r
+    }\r
+\r
+    private static int refreshServiceStatusFrequency() {\r
+        return getIntProperty(ph.getProperty("local.service.status.refresh.frequency"));\r
+    }\r
+\r
+    static int refreshUsageStatsFrequency() {\r
+        return getIntProperty(ph.getProperty("local.usage.stats.refresh.frequency"));\r
+    }\r
+\r
+    @Override\r
+    public void init() {\r
+        // startup the scheduler with current time\r
+        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);\r
+        int min = Calendar.getInstance().get(Calendar.MINUTE);\r
+        int sec = Calendar.getInstance().get(Calendar.SECOND);\r
+        // refresh sleep time (in between requests) - minutes\r
+        final int refresh_freq = refreshServiceStatusFrequency();\r
+\r
+        scheduler.schedule(new SchedulerTask() {\r
+            public void run() {\r
+                refreshCache();\r
+            }\r
+            private void refreshCache() {\r
+                hitEndpointForRefresh();\r
+                log.info("Refreshing the In Memory Cache...");\r
+                log.info(String.format("Refreshing again in %d minutes", refresh_freq));\r
+            }\r
+        }, new RefreshIterator(hour, min, sec, refresh_freq));\r
+    }\r
+\r
+    public void clearContextCache() {\r
+        // try remove the current values from the context\r
+        try {\r
+            this.getServletConfig().getServletContext().removeAttribute("serviceStatusResults");\r
+            this.getServletConfig().getServletContext().removeAttribute("serviceStatusTimestamp");\r
+            this.getServletConfig().getServletContext().removeAttribute("serviceStatusStart");\r
+            this.getServletConfig().getServletContext().removeAttribute("serviceStatusEnd");\r
+            this.getServletConfig().getServletContext().removeAttribute("serviceStatusAllGood");\r
+            log.info("In Memory Cache Cleared!");\r
+        } catch (Exception e) {\r
+            log.warn("In Memory Cache Not Cleared. Perhaps not available yet!");\r
+        }\r
+    }\r
+\r
+    private void hitEndpointForRefresh() {\r
+        String endpointURL;\r
+        endpointURL = (String) this.getServletConfig().getServletContext().getAttribute("serviceStatusURL");\r
+        if (endpointURL != null){\r
+            try {\r
+                URL url = new URL(endpointURL);\r
+                System.out.println(endpointURL);\r
+                HttpURLConnection connection = (HttpURLConnection) url.openConnection();\r
+                connection.setRequestProperty("User-Agent", "JABAWS Service Status Refreshing the Context Cache");\r
+                int status = connection.getResponseCode();\r
+                log.info(String.format("Hitting %s with an internal user-agent! status code: %s",\r
+                        endpointURL, status));\r
+            } catch (IOException e) {\r
+                log.warn("Something wrong when hitting " + endpointURL);\r
+                log.warn(e);\r
+            }\r
+        }\r
+    }\r
+\r
+    public ArrayList<ServiceTestResult> testServiceStatus(HttpServletRequest req) throws ServletException, IOException {\r
+\r
+        ArrayList<ServiceTestResult> testResults = new ArrayList<ServiceTestResult>();\r
+\r
+        // run the service status checkup\r
+        List<String> eps = new ArrayList<String>();\r
+        try {\r
+            eps = getEndPoints();\r
+        } catch (MalformedObjectNameException e) {\r
+            // TODO Auto-generated catch block\r
+            e.printStackTrace();\r
+        } catch (AttributeNotFoundException e) {\r
+            // TODO Auto-generated catch block\r
+            e.printStackTrace();\r
+        } catch (InstanceNotFoundException e) {\r
+            // TODO Auto-generated catch block\r
+            e.printStackTrace();\r
+        } catch (NullPointerException e) {\r
+            // TODO Auto-generated catch block\r
+            e.printStackTrace();\r
+        } catch (MBeanException e) {\r
+            // TODO Auto-generated catch block\r
+            e.printStackTrace();\r
+        } catch (ReflectionException e) {\r
+            // TODO Auto-generated catch block\r
+            e.printStackTrace();\r
+        }\r
+        if (1 != eps.size()) {\r
+            log.info(eps.size() + "EndPoints found");\r
+            //System.out.println("      " + eps.size() + " EndPoints found");\r
+            for (String endpoint : eps) {\r
+                log.info(eps.size() + "EndPoint is " + endpoint);\r
+                //System.out.println("   EndPoint is " + endpoint);\r
+            }\r
+        }\r
+\r
+        String serverPath = new String();\r
+        for (String endpoint : eps) {\r
+            serverPath = endpoint + req.getContextPath();\r
+        }\r
+\r
+        for (Services service : Services.values()) {\r
+            StringWriter testres = new StringWriter();\r
+            PrintWriter writer = new PrintWriter(testres, true);\r
+            WSTester tester = new WSTester(serverPath, writer);\r
+            ServiceTestResult result = new ServiceTestResult(service);\r
+            try {\r
+                result.failed = tester.checkService(service);\r
+            } catch (Exception e) {\r
+                log.info(e, e.getCause());\r
+                String mess = "Fails to connect to the web service: " + service + ". Reason: ";\r
+                writer.println(mess + e.getLocalizedMessage() + "\nDetails: ");\r
+                e.printStackTrace(writer);\r
+            } finally {\r
+                writer.close();\r
+            }\r
+            result.details = testres.toString();\r
+            testResults.add(result);\r
+        }\r
+        return testResults;\r
+    }\r
+\r
+    public String overallStatusGood(ArrayList<ServiceTestResult> testResults) {\r
+        // assumes all good but returns as soon as some service is down\r
+        String success = "true";\r
+        for (int i = 0; i < testResults.size(); i++) {\r
+            if (!testResults.get(i).failed) {\r
+                success = "false";\r
+                break;\r
+            }\r
+        }\r
+        return success;\r
+    }\r
+\r
+    @Override\r
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\r
+        /**\r
+         * // PROBLEM: the code tries to test not WS endpoints on an internal\r
+         * Tomcat, but on an external // endpoints with wrong info on the\r
+         * proxing StringBuffer jabawspath = req.getRequestURL(); jabawspath =\r
+         * jabawspath.delete(jabawspath.lastIndexOf("/"), jabawspath.length());\r
+         * String serverPath = jabawspath.toString();\r
+         */\r
+\r
+        ArrayList<ServiceTestResult> testResults = new ArrayList<ServiceTestResult>();\r
+        String timeStamp = new String();\r
+        long startTime;\r
+        long endTime;\r
+        String refresh_freq;\r
+        String goodStatus;\r
+\r
+        // save the main caller URL in the context\r
+        String url = new String();\r
+        url = req.getRequestURL().toString();\r
+        System.out.println("UR: " + url);\r
+        this.getServletConfig().getServletContext().setAttribute("serviceStatusURL", url);\r
+\r
+        // check user-agent: this is a trick to get the cache refreshed periodically\r
+        String useragent = new String();\r
+        useragent = req.getHeader("user-agent");\r
+        // check if there are values available in the context\r
+        if (this.getServletConfig().getServletContext().getAttribute("serviceStatusResults") == null ||\r
+                useragent.equals("JABAWS Service Status Refreshing the Context Cache")) {\r
+\r
+            // test the services and timeit\r
+            startTime = System.nanoTime();\r
+            testResults = testServiceStatus(req);\r
+            endTime = System.nanoTime();\r
+            // try clear the previous values if any\r
+            clearContextCache();\r
+            // add the current values to the context\r
+            this.getServletConfig().getServletContext().setAttribute("serviceStatusResults", testResults);\r
+            timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(\r
+                    Calendar.getInstance().getTime());\r
+            this.getServletConfig().getServletContext().setAttribute("serviceStatusTimestamp", timeStamp);\r
+            this.getServletConfig().getServletContext().setAttribute("serviceStatusStart", startTime);\r
+            this.getServletConfig().getServletContext().setAttribute("serviceStatusEnd", endTime);\r
+            refresh_freq = String.valueOf(refreshServiceStatusFrequency());\r
+            this.getServletConfig().getServletContext().setAttribute("serviceStatusRefreshFreq", refresh_freq);\r
+            goodStatus = overallStatusGood(testResults);\r
+            this.getServletConfig().getServletContext().setAttribute("serviceStatusAllGood", goodStatus);\r
+\r
+        } else {\r
+            // get last results available\r
+            testResults = (ArrayList) this.getServletConfig().getServletContext().getAttribute("serviceStatusResults");\r
+            timeStamp = (String) this.getServletConfig().getServletContext().getAttribute("serviceStatusTimestamp");\r
+            startTime = (Long) this.getServletConfig().getServletContext().getAttribute("serviceStatusStart");\r
+            endTime = (Long) this.getServletConfig().getServletContext().getAttribute("serviceStatusEnd");\r
+            refresh_freq = (String) this.getServletConfig().getServletContext().getAttribute("serviceStatusRefreshFreq");\r
+        }\r
+\r
+        req.setAttribute("results", testResults);\r
+        req.setAttribute("timestamp", timeStamp);\r
+        req.setAttribute("timeexec", (endTime - startTime) / 100000000);\r
+        req.setAttribute("refreshfreq", refresh_freq);\r
+        RequestDispatcher rd = req.getRequestDispatcher("statpages/ServicesStatus.jsp");\r
+        rd.forward(req, resp);\r
+    }\r
 \r
 }\r
index a6cac63..01e96ea 100644 (file)
@@ -44,8 +44,8 @@ Date: May 2011
                                                        ${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}
                                                </a> </li>
                                                <li><strong>Time of execution:</strong> ${timeexec} sec</li>
-                                               <li><strong>Usage Statistics as of:</strong> ${timestamp}</li>
-                                               <li><a href="${pageContext.request.contextPath}/PublicAnnualStat" title="JABAWS server usage statistics."
+                                               <li><strong>Usage Statistics as of:</strong> ${timestamp} (Refreshes every ${refreshfreq} minutes)</li>
+                                               <li><a href="${pageContext.request.contextPath}/PublicAnnualStatRefresher" title="JABAWS server usage statistics."
                                                id="show_hidden2"><i class="fa fa-bar-chart" aria-hidden="true"></i> Refresh Usage Statistics</a></li>
                                        </ul>
                                        <br/>
index 97735f8..80f9425 100644 (file)
@@ -46,7 +46,6 @@ TODO refactor
                                <div style="margin: 20px ">
 
                                        <c:set var="host" value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}" />
-
                                        <ul>
                                                <li>
                                                        This servlet tests if the web services are healthy on the tomcat instance on which JABAWS is deployed. <br/>
@@ -57,8 +56,8 @@ TODO refactor
                                                <li>Click on the service status to see the results of the testing.</li>
                                                <li><strong>Server:</strong> <a href="${host}">${host}</a> </li>
                                                <li><strong>Time of execution:</strong> ${timeexec} sec</li>
-                                               <li><strong>Service Status as of:</strong> ${timestamp}</li>
-                                               <li><a href="${pageContext.request.contextPath}/ServiceStatus" title="JABAWS web-services status."
+                                               <li><strong>Service Status as of:</strong> ${timestamp} (Refreshes every ${refreshfreq} minutes)</li>
+                                               <li><a href="${pageContext.request.contextPath}/ServiceStatusRefresher" title="JABAWS web-services status."
                                                   id="show_hidden1"><i class="fa fa-cogs" aria-hidden="true"></i> Refresh Service Status</a></li>
                                                <%--<li> Your IP is ${pageContext.request.remoteAddr}</li>--%>
                                        </ul>