File: ServiceStatus.java

package info (click to toggle)
libjaba-client-java 2.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 2,052 kB
  • sloc: java: 17,308; makefile: 12
file content (300 lines) | stat: -rw-r--r-- 13,358 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/* Copyright (c) 2013 Alexander Sherstnev
 * Copyright (c) 2011 Peter Troshin
 *  
 *  JAva Bioinformatics Analysis Web Services (JABAWS) @version: 2.0     
 * 
 *  This library is free software; you can redistribute it and/or modify it under the terms of the
 *  Apache License version 2 as published by the Apache Software Foundation
 * 
 *  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Apache 
 *  License for more details.
 * 
 *  A copy of the license is in apache_license.txt. It is also available here:
 * @see: http://www.apache.org/licenses/LICENSE-2.0.txt
 * 
 * Any republication or derived work distributed in source code form
 * must include this copyright and license notice.
 */

package compbio.stat.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.net.*;
import java.text.SimpleDateFormat;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.management.ReflectionException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import compbio.engine.conf.PropertyHelperManager;
import compbio.stat.servlet.util.RefreshIterator;
import compbio.stat.servlet.util.Scheduler;
import compbio.stat.servlet.util.SchedulerTask;
import compbio.util.PropertyHelper;
import compbio.util.Util;
import org.apache.log4j.Logger;

import compbio.ws.client.Services;
import compbio.ws.client.WSTester;

/**
 * Use cases:
 * <dl>
 * <li>Test web services and display results on the web page</li>
 * </dl>
 *
 * @author pvtroshin
 */

public class ServiceStatus extends HttpServlet {

    private static final Logger log = Logger.getLogger(ServiceStatus.class);

    private static PropertyHelper ph = PropertyHelperManager.getPropertyHelper();

    private final Scheduler scheduler = new Scheduler();

    private List<String> getEndPoints() throws MalformedObjectNameException, NullPointerException, UnknownHostException,
            AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"),
                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        List<String> endPoints = new ArrayList<String>();
        for (Iterator<ObjectName> i = objs.iterator(); i.hasNext(); ) {
            ObjectName obj = i.next();
            String scheme = mbs.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            String hostname = InetAddress.getLocalHost().getHostName();
            endPoints.add(scheme + "://" + hostname + ":" + port);
        }
        return endPoints;
    }

    private static int getIntProperty(String propValue) {
        int value = 0;
        if (!Util.isEmpty(propValue)) {
            propValue = propValue.trim();
            value = Integer.parseInt(propValue);
        }
        return value;
    }

    private static int refreshServiceStatusFrequency() {
        return getIntProperty(ph.getProperty("local.service.status.refresh.frequency"));
    }

    static int refreshUsageStatsFrequency() {
        return getIntProperty(ph.getProperty("local.usage.stats.refresh.frequency"));
    }

    @Override
    public void init() {
        // startup the scheduler with current time
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        int min = Calendar.getInstance().get(Calendar.MINUTE);
        int sec = Calendar.getInstance().get(Calendar.SECOND);
        // refresh sleep time (in between requests) - minutes
        final int refresh_freq = refreshServiceStatusFrequency();

        scheduler.schedule(new SchedulerTask() {
            public void run() {
                refreshCache();
            }
            private void refreshCache() {
                hitEndpointForRefresh();
                log.info("Refreshing the In Memory Cache...");
                log.info(String.format("Refreshing again in %d minutes", refresh_freq));
            }
        }, new RefreshIterator(hour, min, sec, refresh_freq));
    }

    public void clearContextCache() {
        // try remove the current values from the context
        try {
            this.getServletConfig().getServletContext().removeAttribute("serviceStatusResults");
            this.getServletConfig().getServletContext().removeAttribute("serviceStatusTimestamp");
            this.getServletConfig().getServletContext().removeAttribute("serviceStatusStart");
            this.getServletConfig().getServletContext().removeAttribute("serviceStatusEnd");
            this.getServletConfig().getServletContext().removeAttribute("serviceStatusAllGood");
            log.info("In Memory Cache Cleared!");
        } catch (Exception e) {
            log.warn("In Memory Cache Not Cleared. Perhaps not available yet!");
        }
    }

    private void hitEndpointForRefresh() {
        String endpointURL;
        endpointURL = (String) this.getServletConfig().getServletContext().getAttribute("serviceStatusURL");
        if (endpointURL != null){
            try {
                URL url = new URL(endpointURL);
                System.out.println(endpointURL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("User-Agent", "JABAWS Service Status Refreshing the Context Cache");
                int status = connection.getResponseCode();
                log.info(String.format("Hitting %s with an internal user-agent! status code: %s",
                        endpointURL, status));
            } catch (IOException e) {
                log.warn("Something wrong when hitting " + endpointURL);
                log.warn(e);
            }
        }
    }

    public ArrayList<ServiceTestResult> testServiceStatus(HttpServletRequest req) throws ServletException, IOException {

        ArrayList<ServiceTestResult> testResults = new ArrayList<ServiceTestResult>();

        // run the service status checkup
        List<String> eps = new ArrayList<String>();
        try {
            eps = getEndPoints();
        } catch (MalformedObjectNameException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (AttributeNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NullPointerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ReflectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (1 != eps.size()) {
            log.info(eps.size() + "EndPoints found");
            //System.out.println("      " + eps.size() + " EndPoints found");
            for (String endpoint : eps) {
                log.info(eps.size() + "EndPoint is " + endpoint);
                //System.out.println("   EndPoint is " + endpoint);
            }
        }

        String serverPath = new String();
        for (String endpoint : eps) {
            serverPath = endpoint + req.getContextPath();
        }

        for (Services service : Services.values()) {
            StringWriter testres = new StringWriter();
            PrintWriter writer = new PrintWriter(testres, true);
            WSTester tester = new WSTester(serverPath, writer);
            ServiceTestResult result = new ServiceTestResult(service);
            try {
                result.failed = tester.checkService(service);
            } catch (Exception e) {
                log.info(e, e.getCause());
                String mess = "Fails to connect to the web service: " + service + ". Reason: ";
                writer.println(mess + e.getLocalizedMessage() + "\nDetails: ");
                e.printStackTrace(writer);
            } finally {
                writer.close();
            }
            result.details = testres.toString();
            testResults.add(result);
        }
        return testResults;
    }

    public String overallStatusGood(ArrayList<ServiceTestResult> testResults) {
        // assumes all good but returns as soon as some service is down
        String success = "true";
        for (int i = 0; i < testResults.size(); i++) {
            if (!testResults.get(i).failed) {
                success = "false";
                break;
            }
        }
        return success;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * // PROBLEM: the code tries to test not WS endpoints on an internal
         * Tomcat, but on an external // endpoints with wrong info on the
         * proxing StringBuffer jabawspath = req.getRequestURL(); jabawspath =
         * jabawspath.delete(jabawspath.lastIndexOf("/"), jabawspath.length());
         * String serverPath = jabawspath.toString();
         */

        ArrayList<ServiceTestResult> testResults = new ArrayList<ServiceTestResult>();
        String timeStamp = new String();
        long startTime;
        long endTime;
        String refresh_freq;
        String goodStatus;

        // save the main caller URL in the context
        String url = new String();
        url = req.getRequestURL().toString();
        System.out.println("UR: " + url);
        this.getServletConfig().getServletContext().setAttribute("serviceStatusURL", url);

        // check user-agent: this is a trick to get the cache refreshed periodically
        String useragent = new String();
        useragent = req.getHeader("user-agent");
        // check if there are values available in the context
        if (this.getServletConfig().getServletContext().getAttribute("serviceStatusResults") == null ||
                useragent.equals("JABAWS Service Status Refreshing the Context Cache")) {

            // test the services and timeit
            startTime = System.nanoTime();
            testResults = testServiceStatus(req);
            endTime = System.nanoTime();
            // try clear the previous values if any
            clearContextCache();
            // add the current values to the context
            this.getServletConfig().getServletContext().setAttribute("serviceStatusResults", testResults);
            timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(
                    Calendar.getInstance().getTime());
            this.getServletConfig().getServletContext().setAttribute("serviceStatusTimestamp", timeStamp);
            this.getServletConfig().getServletContext().setAttribute("serviceStatusStart", startTime);
            this.getServletConfig().getServletContext().setAttribute("serviceStatusEnd", endTime);
            refresh_freq = String.valueOf(refreshServiceStatusFrequency());
            this.getServletConfig().getServletContext().setAttribute("serviceStatusRefreshFreq", refresh_freq);
            goodStatus = overallStatusGood(testResults);
            this.getServletConfig().getServletContext().setAttribute("serviceStatusAllGood", goodStatus);

        } else {
            // get last results available
            testResults = (ArrayList) this.getServletConfig().getServletContext().getAttribute("serviceStatusResults");
            timeStamp = (String) this.getServletConfig().getServletContext().getAttribute("serviceStatusTimestamp");
            startTime = (Long) this.getServletConfig().getServletContext().getAttribute("serviceStatusStart");
            endTime = (Long) this.getServletConfig().getServletContext().getAttribute("serviceStatusEnd");
            refresh_freq = (String) this.getServletConfig().getServletContext().getAttribute("serviceStatusRefreshFreq");
        }

        req.setAttribute("results", testResults);
        req.setAttribute("timestamp", timeStamp);
        req.setAttribute("timeexec", (endTime - startTime) / 1000000000);
        req.setAttribute("refreshfreq", refresh_freq);
        RequestDispatcher rd = req.getRequestDispatcher("statpages/ServicesStatus.jsp");
        rd.forward(req, resp);
    }

}