KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > uk > org > primrose > pool > jmx > html > HtmlJMXServer


1 /**
2 * Library name : Primrose - A Java Database Connection Pool.
3 * Published by Ben Keeping, http://primrose.org.uk .
4 * Copyright (C) 2004 Ben Keeping, primrose.org.uk
5 * Email: Use "Contact Us Form" on website
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */

21
22 package uk.org.primrose.pool.jmx.html;
23 import uk.org.primrose.pool.jmx.*;
24 import com.sun.jdmk.comm.*;
25 import javax.management.*;
26 import javax.management.loading.*;
27 import javax.management.remote.JMXConnectorServer JavaDoc;
28 import javax.management.remote.JMXConnectorServerFactory JavaDoc;
29 import javax.management.remote.JMXServiceURL JavaDoc;
30 import javax.management.NotificationBroadcaster JavaDoc;
31 import java.util.*;
32 import java.net.*;
33 import java.io.*;
34 import java.lang.reflect.*;
35 import javax.naming.Context JavaDoc;
36 import javax.naming.InitialContext JavaDoc;
37
38 public class HtmlJMXServer extends Thread JavaDoc {
39     int port = 8091;
40     String JavaDoc cssFileName = "";
41     String JavaDoc jsFileName = "";
42
43     public HtmlJMXServer(int port, String JavaDoc cssFileName, String JavaDoc jsFileName) {
44         this.port = port;
45         this.cssFileName = cssFileName;
46         this.jsFileName = jsFileName;
47     }
48
49     public void run() {
50         try {
51             ServerSocket ss = new ServerSocket(port);
52             System.err.println("[HtmlJMXServer] Listening on port : " +port);
53             while (true) {
54                 new HtmlJMXServerHandler(ss.accept()).start();
55             }
56         } catch (IOException ioe) {
57             ioe.printStackTrace(System.err);
58         }
59     }
60
61
62     class HtmlJMXServerHandler extends Thread JavaDoc {
63         Socket s = null;
64         MBeanServer mbs = null;
65         HtmlJMXServerHandler(Socket s) {
66             this.s = s;
67         }
68
69         public void run() {
70             try {
71                 // Get the base IO streams
72
InputStream is = s.getInputStream();
73                 OutputStream os = s.getOutputStream();
74
75
76                 // Read the command (URL)
77
BufferedReader br = new BufferedReader(new InputStreamReader(is));
78                 String JavaDoc line = br.readLine();
79                 //System.err.println("Got request : " +s);
80

81                 // Get the initial http request data
82
String JavaDoc httpRequest[] = line.split(" ");
83                 String JavaDoc httpMethod = httpRequest[0];
84                 String JavaDoc httpResource = httpRequest[1];
85                 String JavaDoc httpVersion = httpRequest[2];
86
87                 // write the header to the browser
88
writeHeaders(os, "200", 0, "text/html", null);
89
90                 // Write out start of page html
91
// including our dynamic links to javascript and css files
92
writeHtmlStart(os, cssFileName, jsFileName);
93
94                 // Write the body
95
// They want to view the root, so show the domains available
96
if (httpResource.equals("/")) {
97                     showAllDomains(os);
98                 } else if (httpResource.startsWith("/viewDomain")) {
99                     StringTokenizer st = new StringTokenizer(httpResource, "?");
100                     st.nextToken();
101                     String JavaDoc tmp = URLDecoder.decode(st.nextToken());
102                     String JavaDoc mbeanName = tmp.substring(tmp.indexOf("=")+1, tmp.length());
103                     viewSingleDomain(os, mbeanName);
104                 }
105
106                 // Write out end of page html
107
writeHtmlEnd(os);
108
109
110                 // Close our streams and socket
111
br.close();
112                 is.close();
113                 os.flush();
114                 os.close();
115                 s.close();
116             } catch (IOException ioe) {
117                 ioe.printStackTrace(System.err);
118             }
119
120
121         }
122
123         /**
124         * View attribute and operation info for our mbean
125         */

126         private void viewSingleDomain(OutputStream os, String JavaDoc mbeanName) throws IOException {
127             try {
128
129                 ArrayList mbeanServers = MBeanServerFactory.findMBeanServer(null);
130                 Iterator iter = mbeanServers.iterator();
131                 // The tomcat MBeanServer
132
iter.next();
133                 // Our MBeanServer
134
MBeanServer mbs = (MBeanServer)iter.next();
135
136                 // Create an name to query the mbs about our mbean
137
ObjectName on = new ObjectName(mbeanName);
138
139                 // Get the object that describes our MBean
140
MBeanInfo mbeanInfo = mbs.getMBeanInfo(on);
141
142                 // Get the attribute info, and write it to the browser
143
MBeanAttributeInfo[] attrInfo = mbeanInfo.getAttributes();
144                 boolean read = false;
145                 boolean write= false;
146                 String JavaDoc readOrWrite = "";
147                 ArrayList tdData = new ArrayList();
148                 tdData.add("<td><span class=\"tableHeader\">Name</span></td><td><span class=\"tableHeader\">Description</span></td><td><span class=\"tableHeader\">Data Type</span></td><td><span class=\"tableHeader\">Access</span></td><td><span class=\"tableHeader\">Value</span></td>");
149                 //tdData.add("<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>");
150
for (int i = 0; i < attrInfo.length; i++) {
151                     System.err.println(attrInfo[i].getName() +" " +attrInfo[i].getDescription());
152                     read = attrInfo[i].isReadable();
153                     write = attrInfo[i].isWritable();
154                     if (read && write) {
155                         readOrWrite = "RW";
156                     } else if (read && !write) {
157                         readOrWrite = "RO";
158                     } else {
159                         readOrWrite = "WO";
160                     }
161                     tdData.add("<td colspan=\"5\"><hr></td>");
162                     Object JavaDoc value = mbs.getAttribute(on, attrInfo[i].getName());
163                     tdData.add("<td>" +attrInfo[i].getName() +"</td><td>" +attrInfo[i].getDescription().replaceAll("Attribute exposed for management", "No description.") +"</td><td>" +attrInfo[i].getType().replaceAll("java.lang.", "") +"</td><td>" +readOrWrite +"</td><td>" +value +"</td>");
164                 }
165
166                 writeHtmlTable(os, "mainContent", tdData);
167
168
169                 // Get the operation info, and write it to the browser
170
MBeanOperationInfo[] operInfo = mbeanInfo.getOperations();
171
172                 tdData = new ArrayList();
173                 tdData.add("<td><span class=\"tableHeader\">Name</span></td><td><span class=\"tableHeader\">Description</span></td><td><span class=\"tableHeader\">Returns</span></td><td><span class=\"tableHeader\">Parameters</span></td>");
174                 //tdData.add("<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>");
175
for (int i = 0; i < operInfo.length; i++) {
176                     ArrayList al = new ArrayList();
177                     String JavaDoc parameters = "";
178                     MBeanParameterInfo[] params = operInfo[i].getSignature();
179                     if (params.length == 0) {
180                         al.add("<td colspan=\"2\">No parameters required.</td>");
181                     } else {
182                         for (int j = 0; j < params.length; j++) {
183                             al.add("<td>" +params[j].getType().replaceAll("java.lang.", "") +"</td><td><input class=\"inputTextBorder\" type=\"text\"></td>");
184                         }
185                     }
186                     tdData.add("<td colspan=\"4\"><hr></td>");
187                     tdData.add("<td><input class=\"button\" type=\"button\" value=\"" +operInfo[i].getName() +"\"></td><td>" +operInfo[i].getDescription().replaceAll("Operation exposed for management", "No description.") +"</td><td>" +operInfo[i].getReturnType().replaceAll("java.lang.", "") +"</td><td>" +createHtmlTable("mainContent", al) +"</td>");
188                 }
189
190                 writeHtmlTable(os, "mainContent", tdData);
191
192             } catch (Exception JavaDoc e) {
193                 e.printStackTrace(System.err);
194             }
195
196
197
198         }
199
200
201         /**
202         * Display our initial domains available
203         */

204         private void showAllDomains(OutputStream os) throws IOException {
205             try {
206
207                 ArrayList mbeanServers = MBeanServerFactory.findMBeanServer(null);
208                 Iterator iter = mbeanServers.iterator();
209                 // The tomcat MBeanServer
210
iter.next();
211                 // Our MBeanServer
212
MBeanServer mbs = (MBeanServer)iter.next();
213                 Set set = mbs.queryMBeans(null, null);
214                 Iterator iter2 = set.iterator();
215                 ArrayList tdData = new ArrayList();
216                 while (iter2.hasNext()) {
217                     ObjectInstance obji = (ObjectInstance)iter2.next();
218                     tdData.add("<td>Domain:</td><td><a HREF=\"/viewDomain?object=" +obji.getObjectName() +"\">" +obji.getObjectName() +"</a></td>");
219
220                 }
221                 writeHtmlTable(os, "mainContent", tdData);
222             } catch (Exception JavaDoc e) {
223                 e.printStackTrace(System.err);
224             }
225
226
227
228         }
229
230         /**
231         * Write our header to the browser
232         */

233         private void writeHeaders(OutputStream os, String JavaDoc httpStatus, int contentLength, String JavaDoc contentType, String JavaDoc cookieId) throws IOException {
234             os.write(("HTTP/1.1 "+httpStatus +";\n").getBytes());
235             os.write(("Date: " +new Date()).getBytes());
236             os.write("Server: beekeeper/0.1\n".getBytes());
237             os.write(("Last-Modified: " +new Date() +"\n").getBytes());
238             if (contentLength != 0) {
239                 os.write(("Content-Length: " +contentLength).getBytes());
240             }
241             os.write("Connection: close\n".getBytes());
242             os.write(("Content-Type: " +contentType +"\n").getBytes());
243             if (cookieId != null) {
244                 os.write(("Set-Cookie: jsessionid=" +cookieId +"\n").getBytes());
245             }
246             os.write("\n".getBytes());
247         }
248
249     }
250
251     private static void writeHtmlStart(OutputStream os, String JavaDoc cssFileName, String JavaDoc jsFileName) throws IOException {
252         String JavaDoc html = "<html>\r\n" +
253                         "<head>\r\n"+
254                         "<link rel=\"stylesheet\" type=\"text/css\" HREF=\"" +cssFileName +"\">\r\n" +
255                         "<script language=\"javascript\" SRC=\"" +jsFileName +"\"></script>\r\n" +
256                         "</head>\r\n"+
257                         "<body>\r\n";
258         os.write(html.getBytes());
259     }
260
261     private static void writeHtmlEnd(OutputStream os) throws IOException {
262         String JavaDoc html = "</body>\r\n" +
263                         "</html>\r\n";
264         os.write(html.getBytes());
265     }
266
267     private static void writeHtmlTable(OutputStream os, String JavaDoc cssClass, ArrayList tdData) throws IOException {
268         os.write(("<table width=\"80%\" class=\"" +cssClass +"\">\r\n").getBytes());
269
270         for (int i = 0; i < tdData.size(); i++) {
271             os.write(("<tr>" +tdData.get(i) +"</tr>\r\n").getBytes());
272         }
273         os.write("</table>\r\n".getBytes());
274     }
275
276     private static String JavaDoc createHtmlTable(String JavaDoc cssClass, ArrayList tdData) throws IOException {
277         String JavaDoc html = "";
278         html +=("<table width=\"80%\" class=\"" +cssClass +"\">\r\n");
279
280         for (int i = 0; i < tdData.size(); i++) {
281             html += ("<tr>" +tdData.get(i) +"</tr>\r\n");
282         }
283         html +="</table>\r\n";
284         return html;
285     }
286
287     /**
288     * A helper method. Calls methods
289     * dynamically with dynamic values.
290     */

291     private Object JavaDoc callGetMethod(String JavaDoc attributeName) {
292         //System.err.println("callGetMethod " +attributeName);
293
Class JavaDoc targetClass = this.getClass();
294         Method[] publicMethods = targetClass.getMethods();
295         for (int j = 0; j < publicMethods.length; j++) {
296             String JavaDoc fieldName = publicMethods[j].getName();
297             Class JavaDoc typeClass = publicMethods[j].getReturnType();
298             String JavaDoc fieldType = typeClass.getName();
299             //System.err.println(" Name: " + fieldName +", Type: " + fieldType);
300

301             if (("get" +attributeName).equalsIgnoreCase(fieldName)) {
302                 try {
303                     //System.err.println("Found method, using " +fieldName);
304
return publicMethods[j].invoke(this, null);
305                 } catch (IllegalAccessException JavaDoc iae) {
306                     iae.printStackTrace(System.err);
307                 } catch (InvocationTargetException ite) {
308                     ite.printStackTrace(System.err);
309                 }
310
311             }
312         }
313         return null;
314     }
315
316
317
318 }
Popular Tags