KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > fr > dyade > aaa > agent > HttpDebug


1 /*
2  * Copyright (C) 2001 - 2003 ScalAgent Distributed Technologies
3  * Copyright (C) 1996 - 2000 BULL
4  * Copyright (C) 1996 - 2000 INRIA
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library 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 GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA.
20  */

21 package fr.dyade.aaa.agent;
22
23 import java.io.*;
24 import java.net.*;
25 import java.text.*;
26 import java.util.*;
27
28 import org.objectweb.util.monolog.api.BasicLevel;
29 import org.objectweb.util.monolog.api.Logger;
30
31 import fr.dyade.aaa.util.Daemon;
32
33 /**
34  * A <code>HttpDebug</code> service provides an HTTP interface to
35  * access to debugging functions in running agent servers.
36  * <p>
37  * The <code>HttpDebug</code> service needs an argument: the TCP port number.
38  * Moreover, The <code>HttpDebug</code> service exports its connecting
39  * parameters in a file named server<serverId>HttpProxy.cnx.
40  * It may be accessed using a HTTP browser client.
41  * <p>
42  * Actually, there is only one thread running, which reads and analyses
43  * commands from the input flow,and writes results synchronously onto the
44  * output flow.
45  */

46 public class HttpDebug {
47   static HttpDebug httpd = null;
48
49   static int port = 8090;
50   HttpDebugMonitor monitors[] = null;
51   ServerSocket listen = null;
52
53   static boolean debug = true;
54
55   DebugMonitor dmon = null;
56
57   static Logger xlogmon = null;
58
59   /**
60    * Initializes the package as a well known service.
61    * <p>
62    * Creates a <code>HttpDebug</code> proxy.
63    *
64    * @param args parameters from the configuration file
65    * @param firstTime <code>true</code> when service starts anew
66    */

67   public static void init(String JavaDoc args, boolean firstTime) throws Exception JavaDoc {
68     if (args.length()!=0) {
69       try {
70     port = Integer.parseInt(args);
71       } catch (NumberFormatException JavaDoc exc) {}
72     }
73
74     // Get the logging monitor from current server MonologLoggerFactory
75
xlogmon = Debug.getLogger(Debug.A3Service + ".HttpDebug");
76
77     if (httpd == null)
78       httpd = new HttpDebug(port);
79     startService();
80   }
81
82   public static void startService() {
83     for (int i=0; i<httpd.monitors.length; i++) {
84       httpd.monitors[i].start();
85     }
86 // if (debug) dmon.start();
87
}
88
89   public static void stopService() {
90     for (int i=0; i<httpd.monitors.length; i++) {
91       if (httpd.monitors[i] != null) httpd.monitors[i].stop();
92     }
93 // if (debug && (dmon != null)) dmon.stop();
94
httpd = null;
95   }
96
97   String JavaDoc host = null;
98   String JavaDoc base = null;
99
100   /**
101    * Creates an HttpDebug service.
102    *
103    * @param port TCP listen port of this proxy.
104    */

105   private HttpDebug(int port) throws IOException {
106     if (port != 0)
107       this.port = port;
108
109     host = InetAddress.getLocalHost().getHostName();
110     base = "http://" + host + ":" + port;
111     listen = new ServerSocket(port);
112
113     monitors = new HttpDebugMonitor[1];
114     for (int i=0; i<monitors.length; i++) {
115       monitors[i] = new HttpDebugMonitor("HttpDebug#" +
116                                          AgentServer.getServerId() + '.' + i);
117     }
118
119 // if (debug) dmon = new DebugMonitor();
120
}
121
122   /**
123    * Provides a string image for this object.
124    */

125   public String JavaDoc toString() {
126     StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
127
128     strBuf.append("(").append(super.toString());
129     strBuf.append(",port=").append(port);
130     strBuf.append(",monitors=[");
131     for (int i=0; i<monitors.length; i++) {
132       strBuf.append(monitors[i].toString()).append(",");
133     }
134     strBuf.append("]");
135     strBuf.append(")");
136
137     return strBuf.toString();
138   }
139
140   final static String JavaDoc CMD_HELP = "/HELP";
141
142   final static String JavaDoc CMD_ADMIN = "/ADMIN";
143   final static String JavaDoc CMD_AGENTS = CMD_ADMIN + "/AGENTS";
144   final static String JavaDoc CMD_SERVERS = CMD_ADMIN + "/SERVERS";
145   final static String JavaDoc CMD_MSG_CONS = CMD_ADMIN + "/MSGCONS";
146   final static String JavaDoc CMD_SERVICES = CMD_ADMIN + "/SERVICES";
147
148   final static String JavaDoc CMD_DUMP_AGENT = CMD_ADMIN + "/DUMP_AGENT";
149
150   final static String JavaDoc CMD_DEBUG = "/DEBUG";
151   final static String JavaDoc CMD_DEBUG_WAIT = "/XEBUGWAIT";
152   final static String JavaDoc CMD_DEBUG_RUN = "/XEBUGRUN";
153
154   final static String JavaDoc CMD_CLASS = "/CLASS";
155
156   final static String JavaDoc CMD_STOP = "/STOP";
157   final static String JavaDoc CMD_START = "/START";
158   final static String JavaDoc CMD_QUEUE = "/QUEUE";
159   final static String JavaDoc CMD_DUMP = "/DUMP";
160   final static String JavaDoc CMD_REMOVE = "/REMOVE";
161
162   final static String JavaDoc CMD_THREADS = "/THREADS";
163
164   class HttpDebugMonitor extends Daemon {
165     Socket socket = null;
166     BufferedReader reader = null;
167     PrintWriter writer = null;
168
169     /**
170      * Constructor.
171      */

172     protected HttpDebugMonitor(String JavaDoc name) {
173       super(name, HttpDebug.xlogmon);
174       // Get the logging monitor from HttpDebug (overload Daemon setup)
175
this.setThreadGroup(AgentServer.getThreadGroup());
176     }
177
178     /**
179      * Provides a string image for this object.
180      *
181      * @return printable image of this object
182      */

183     public String JavaDoc toString() {
184       return "(" + super.toString() +
185     ",socket=" + socket + ")";
186     }
187
188     public void run() {
189       try {
190         while (running) {
191           canStop = true;
192           try {
193             socket = listen.accept();
194             canStop = false;
195           } catch (IOException exc) {
196             if (running)
197               logmon.log(BasicLevel.ERROR,
198                          getName() + ", error during accept", exc);
199           }
200
201           if (! running) break;
202
203           try {
204             // Get the streams
205
reader = new BufferedReader(
206               new InputStreamReader(socket.getInputStream()));
207             writer = new PrintWriter(socket.getOutputStream(), true);
208       
209             // Reads then parses the request
210
doRequest(reader.readLine());
211
212             writer.flush();
213           } catch (Exception JavaDoc exc) {
214             logmon.log(BasicLevel.ERROR,
215                        getName() + ", error during connection", exc);
216           } finally {
217             // Closes the connection
218
try {
219               reader.close();
220             } catch (Exception JavaDoc exc) {}
221             reader = null;
222             try {
223               writer.close();
224             } catch (Exception JavaDoc exc) {}
225             writer = null;
226             try {
227               socket.close();
228             } catch (Exception JavaDoc exc) {}
229             socket = null;
230           }
231         }
232       } finally {
233         finish();
234       }
235     }
236
237     protected void close() {
238       try {
239     listen.close();
240       } catch (Exception JavaDoc exc) {}
241       listen = null;
242     }
243
244     protected void shutdown() {
245       close ();
246     }
247
248     void header(String JavaDoc title) throws IOException {
249       writer.println("<HTML>");
250       writer.println("<HEAD>");
251       writer.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"/>");
252       writer.println("<STYLE TYPE=\"text/css\">");
253       writer.println("<!-- ");
254       writer.println(" /* Style definitions */");
255       writer.println(" H1 {font-family:Arial,Helvetica;font-weight:bold;font-size:36pt}");
256       writer.println(" H2 {font-family:Arial,Helvetica;font-weight:bold;font-size:20pt}");
257       writer.println(" H3 {font-family:Arial,Helvetica;font-weight:bold;font-size:16pt}");
258       writer.println(" CODE {font-size:14}");
259
260       writer.println(" .NORMAL {font-family:Arial,Helvetica;font-style:normal;font-size:14}");
261       writer.println(" .BOTTOM {font-family:Arial,Helvetica;font-style:italic;font-size:10pt}");
262
263       writer.println(" .FONT1 {font-family:Arial,Helvetica;font-weight:normal;font-size:18pt}");
264       writer.println(" .FONT2 {font-family:Arial,Helvetica;font-weight:normal;font-size:14pt}");
265       writer.println(" .FONT3 {font-family:Arial,Helvetica;font-weight:normal;font-size:12pt}");
266
267       writer.println(" a:link {color:white}");
268       writer.println(" a:visited{color:white}");
269       writer.println(" a:active{color:white}");
270       writer.println("-->");
271       writer.println("</STYLE>");
272       writer.println("<TITLE>" + title + "</TITLE>");
273       writer.println("</HEAD>");
274
275       writer.println("<BODY bgcolor=\"#CCCCCC\">");
276
277       writer.println("<H1>" + title + "</H1>");
278
279       writer.println("<HR WIDTH=\"100%\"/>");
280     }
281
282     void menu() throws IOException {
283       writer.println("<TABLE BORDER=\"1\" WIDTH=\"100%\" BGCOLOR=\"#3366FF\">");
284       writer.println("<TR>");
285       writer.println("<TD CLASS=FONT1><CENTER>");
286       writer.println("<A HREF=\"" + base + CMD_SERVERS + "\">Servers</A>");
287       writer.println("</CENTER></TD>");
288
289       writer.println("<TD CLASS=FONT1><CENTER>");
290       writer.println("<A HREF=\"" + base + CMD_AGENTS + "\">Agents</A>");
291       writer.println("</CENTER></TD>");
292
293       writer.println("<TD CLASS=FONT1><CENTER>");
294       writer.println("<A HREF=\"" + base +
295              CMD_MSG_CONS + "\">Consumers</A>");
296       writer.println("</CENTER></TD>");
297
298       writer.println("<TD CLASS=FONT1><CENTER>");
299       writer.println("<A HREF=\"" + base +
300              CMD_SERVICES + "\">Services</A>");
301       writer.println("</CENTER></TD>");
302
303       if (debug) {
304 // writer.println("<TD CLASS=FONT1><CENTER>");
305
// writer.println("<A HREF=\"" + base +
306
// CMD_DEBUG + "\" target=\"A3Debug\">Debug</A>");
307
// writer.println("</CENTER></TD>");
308

309     writer.println("<TD CLASS=FONT1><CENTER>");
310     writer.println("<A HREF=\"" + base +
311                CMD_THREADS + "\">Threads</A>");
312     writer.println("</CENTER></TD>");
313       }
314
315       writer.println("</TR>");
316       writer.println("</TABLE>");
317       writer.println("<HR WIDTH=\"100%\"/>");
318     }
319
320     void error(Exception JavaDoc exc) throws IOException {
321       writer.println("<H2>Error</H2>");
322       writer.println("<BLOCKQUOTE><PRE>");
323       exc.printStackTrace(writer);
324       writer.println("</PRE></BLOCKQUOTE>");
325     }
326
327     void help() throws IOException {
328       writer.println("<H2>Help</H2>");
329       usage();
330     }
331
332     void unknown(String JavaDoc cmd) throws IOException {
333       writer.println("<H2>Error</H2>");
334       writer.println("<P CLASS=FONT2>");
335       writer.println("Unknown command \"" + cmd + "\"");
336       writer.println("</P>");
337       usage();
338     }
339
340     void usage() throws IOException {
341       writer.println("<H2>Usage</H2>");
342       writer.println("<P CLASS=FONT2>");
343       writer.println("To be provided.");
344       writer.println("</P>");
345     }
346
347     void footer() throws IOException {
348       writer.println("<HR WIDTH=\"100%\"/>");
349       writer.println("<P CLASS=BOTTOM>");
350       writer.println("Generated by fr.dyade.aaa.agent.HttpDebug, version 1.0, date:" + new Date().toString());
351       writer.println("</P>");
352
353       writer.println("</BODY>");
354       writer.println("</HTML>");
355     }
356
357     public void doRequest(String JavaDoc request) {
358       String JavaDoc cmd = null;
359
360 // System.out.println("request=" + request);
361

362       try {
363     StringTokenizer st = new StringTokenizer(request);
364     if ((st.countTokens() >= 2) && st.nextToken().equals("GET")) {
365       cmd = st.nextToken();
366       
367       StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
368       try {
369         if ((cmd.equals("/")) ||
370         (cmd.equals(CMD_HELP))) {
371           // first page
372
header("A3 AgentServer #" + AgentServer.getServerId());
373           menu();
374           help();
375         } else if (cmd.startsWith(CMD_HELP)) {
376           header("A3 AgentServer #" + AgentServer.getServerId());
377           // help(cmd.substring(CMD_HELP.length()));
378
} else if (cmd.startsWith(CMD_ADMIN)) {
379           header("A3 AgentServer #" + AgentServer.getServerId() +
380              " Administration");
381           menu();
382
383           if (cmd.equals(CMD_AGENTS)) {
384         // a list of agents has been requested
385
listAgents(buf);
386           } else if (cmd.startsWith(CMD_SERVERS)) {
387         // a list of servers has been requested
388
listServers(cmd.substring(CMD_SERVERS.length()), buf);
389         if (cmd.substring(CMD_SERVERS.length()).startsWith(CMD_STOP)) {
390                   AgentServer.stop(false);
391         }
392           } else if (cmd.startsWith(CMD_MSG_CONS)) {
393         // a list of consumers has been requested
394
listConsumers(cmd.substring(CMD_MSG_CONS.length()), buf);
395           } else if (cmd.startsWith(CMD_SERVICES)) {
396         // a list of services has been requested
397
listServices(cmd.substring(CMD_SERVICES.length()), buf);
398           } else if (cmd.startsWith(CMD_DUMP_AGENT)) {
399         // a dump command has been requested
400
dumpAgent(cmd.substring(CMD_DUMP_AGENT.length()), buf);
401           }
402         } else if (cmd.equals(CMD_DEBUG_WAIT)) {
403           header("A3 AgentServer #" + AgentServer.getServerId());
404           writer.println("<H2>Debug Waiting</H2>");
405         } else if (cmd.equals(CMD_DEBUG_RUN)) {
406           header("A3 AgentServer #" + AgentServer.getServerId());
407           writer.println("<H2>Debug Running</H2>");
408         } else if (cmd.startsWith(CMD_DEBUG)) {
409           // a debug tool has been requested
410
header("A3 AgentServer #" + AgentServer.getServerId() +
411              " Debug Tool");
412           debug(cmd.substring(CMD_DEBUG.length()), buf);
413         } else if (cmd.startsWith(CMD_CLASS)) {
414           loadClass(cmd.substring(CMD_CLASS.length()));
415         } else if (cmd.startsWith(CMD_THREADS)) {
416           // a list of threads has been requested
417
header("A3 AgentServer #" + AgentServer.getServerId());
418           menu();
419           listThread(cmd.substring(CMD_THREADS.length()), buf);
420         } else {
421           unknown(cmd);
422         }
423         writer.println(buf.toString());
424       } catch (Exception JavaDoc exc) {
425         error(exc);
426       }
427       footer();
428     }
429       } catch(IOException exc) {
430         logmon.log(BasicLevel.WARN,
431                    getName() + ", error in \"" + cmd + "\"", exc);
432       } finally {
433       }
434     }
435
436     /**
437      * List all active threads in current ThreadGroup
438      */

439     void listThread(String JavaDoc cmd, StringBuffer JavaDoc buf) {
440       String JavaDoc group = null;
441       if ((cmd.length() > 1) && (cmd.charAt(0) == '/'))
442     group = cmd.substring(1);
443
444       ThreadGroup JavaDoc tg = Thread.currentThread().getThreadGroup();
445       while (tg.getParent() != null)
446     tg = tg.getParent();
447       int nbt = tg.activeCount();
448       Thread JavaDoc[] tab = new Thread JavaDoc[nbt];
449       nbt = tg.enumerate(tab);
450       buf.append("<H2>List of threads</H2>\n");
451       buf.append("<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 WIDTH=\"100%\">\n");
452       for (int j=0; j<nbt; j++) {
453         if (tab[j] == null) continue;
454     if ((group != null) &&
455         ! tab[j].getThreadGroup().getName().equals(group))
456       continue;
457     buf.append("<TR><TD CLASS=FONT2><PRE>\n");
458     buf.append("name=").append(tab[j].getName()).append("\n")
459       .append("group=").append(tab[j].getThreadGroup().getName()).append("\n")
460       .append("isAlive=").append(tab[j].isAlive()).append("\n")
461       .append("isDaemon=").append(tab[j].isDaemon()).append("\n");
462     buf.append("</PRE></TD></TR>\n");
463     buf.append("");
464       }
465       buf.append("</TABLE>");
466
467       return;
468     }
469   
470     /**
471      * List all agents deployed on the current server
472      */

473     void listAgents(StringBuffer JavaDoc buf) {
474       buf.append("<H2>List of agents</H2>\n");
475       buf.append("<PRE>\n");
476       buf.append("now=" + AgentServer.engine.now + "\n");
477       buf.append("NumberAgents=" + AgentServer.engine.agents.size() + "\n");
478       buf.append("NbMaxAgents=" + AgentServer.engine.NbMaxAgents + "\n");
479       buf.append("</PRE>\n");
480       buf.append("<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 WIDTH=\"100%\">\n");
481       AgentId list[] = AgentServer.engine.getLoadedAgentIdlist();
482       for (int i=0; i<list.length; i++) {
483     Agent agent = (Agent) AgentServer.engine.agents.get(list[i]);
484     buf.append("<TR>\n");
485     buf.append("<TD CLASS=FONT1 WIDTH=\"20%\"><CENTER>\n");
486     if (agent != null) {
487       buf.append(urlAgent(list[i]) + "\n");
488     } else {
489       buf.append(list[i] + "\n");
490     }
491     buf.append("</CENTER></TD>\n");
492     buf.append("<TD WIDTH=\"80%\"><PRE>\n");
493     if (agent != null) {
494       buf.append("name=" + agent.name + "\n\n");
495       buf.append("\tclass=" + agent.getClass().getName() + "\n\n");
496       buf.append("fixed=" + agent.fixed + "\n");
497       buf.append("last=" + agent.last + "\n");
498     }
499     buf.append("</PRE></TD>\n");
500     buf.append("</TR>\n");
501       }
502       buf.append("</TABLE>");
503
504       return;
505     }
506
507     String JavaDoc urlServer(short serverId) {
508       if (serverId == AgentServer.getServerId())
509     return base;
510
511       try {
512         ServerDesc desc = AgentServer.getServerDesc(serverId);
513     int port = Integer.parseInt(
514       AgentServer.getServiceArgs(desc.sid,
515                      "fr.dyade.aaa.agent.HttpDebug"));
516         if (desc.getHostname().equals("localhost"))
517           return new String JavaDoc("http://" +
518                             InetAddress.getLocalHost().getHostName() +
519                             ":" + port);
520         else
521           return new String JavaDoc("http://" + desc.getHostname() + ":" + port);
522       } catch (Exception JavaDoc exc) {}
523       return null;
524     }
525
526
527     String JavaDoc urlAgent(AgentId id) {
528       String JavaDoc url = urlServer(id.getTo());
529       if (url == null)
530     return id.toString();
531
532       return new String JavaDoc("<A HREF=\"" + urlServer(id.getTo()) +
533             CMD_DUMP_AGENT + "/" +
534             id.toString().substring(1) + "\">" +
535             id + "</A>");
536     }
537
538     /**
539      * List all servers.
540      */

541     void listServers(String JavaDoc cmd, StringBuffer JavaDoc buf) {
542       buf.append("<H2>List of servers</H2>\n");
543       buf.append("<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 WIDTH=\"100%\">\n");
544       for (short i=0; i<AgentServer.getServerNb(); i++ ) {
545     int port = -1;
546     ServerDesc desc = null;
547         try {
548           desc = (ServerDesc) AgentServer.getServerDesc(i);
549         } catch (Exception JavaDoc exc) {
550           desc = null;
551         }
552         if (desc == null) continue;
553     buf.append("<TR>\n");
554     buf.append("<TD CLASS=FONT1 WIDTH=\"20%\" VALIGN=TOP>\n");
555
556     String JavaDoc url = urlServer(desc.sid);
557     if ((url != null) && (i == AgentServer.getServerId()) &&
558         (cmd.startsWith(CMD_STOP))) {
559       // The server will be stopped, prevent all new request.
560
url = null;
561     }
562
563     if (url != null) {
564       buf.append("<A HREF=\"" + url + CMD_SERVERS + "\">Server #" + desc.sid + "</A>\n");
565       buf.append("<BLOCKQUOTE><FONT CLASS=FONT3>\n");
566       buf.append("<P><A HREF=\"" + url + CMD_AGENTS + "\">Agents</A>\n");
567       buf.append("<P><A HREF=\"" + url + CMD_MSG_CONS + "\">Messages Consumers</A>\n");
568       buf.append("<P><A HREF=\"" + url + CMD_SERVICES + "\">Services</A>\n");
569       buf.append("</FONT></BLOCKQUOTE>\n");
570     } else {
571       buf.append("Server #" + desc.sid + "\n");
572     }
573     buf.append("</TD>\n" +
574            "<TD WIDTH=\"80%\" VALIGN=TOP>\n");
575     
576     if (url != null) {
577       buf.append("<BLOCKQUOTE><FORM ACTION=\"" +
578              url + CMD_SERVERS + CMD_STOP +
579              "\" METHOD=\"GET\">\n" +
580              "<INPUT TYPE=\"submit\" VALUE=\"STOP\" NAME=\"A\">\n" +
581              "</FORM></BLOCKQUOTE>\n");
582     }
583
584     buf.append("<PRE><CODE>\n" +
585            "name=" + desc.name + "\n");
586 // buf.append("isTransient=" + desc.isTransient + "\n");
587
if (desc.gateway == desc.sid) {
588       buf.append("domain=<A HREF=\"" + base + CMD_MSG_CONS +
589              "/" + desc.domain.getName() + "\">" +
590              desc.domain.getName() + "</A>\n");
591       buf.append("hostname=" + desc.getHostname() + "\n");
592       buf.append("port=" + desc.getPort() + "\n");
593       if (desc.active) {
594         buf.append("active=" + desc.active + "\n");
595       } else {
596         buf.append("last=" + desc.last + "\n");
597         buf.append("retry=" + desc.retry);
598       }
599     } else {
600       buf.append("gateway=#" + desc.gateway + "\n");
601     }
602     buf.append("</CODE></PRE></TD>\n");
603     buf.append("</TR>\n");
604       }
605       buf.append("</TABLE>");
606
607       return;
608     }
609
610 // int getArg(String cmd) {
611
// if (cmd.charAt(0) != '+')
612
// return -1;
613

614 // int i = 1;
615
// for (; i < cmd.length();i += 1) {
616
// if ((cmd.charAt(i) < '0') || (cmd.charAt(i) > '9'))
617
// break;
618
// }
619
// try {
620
// if (i > 1)
621
// return Integer.parseInt(cmd.substring(1, i));
622
// } catch (Exception exc) {
623
// // Can never happened
624
// }
625
// return -1;
626
// }
627

628     /**
629      *
630      */

631     void listConsumers(String JavaDoc cmd, StringBuffer JavaDoc buf) {
632       String JavaDoc msgConsId = null;
633       int sub = -1;
634
635       if (cmd.startsWith(CMD_QUEUE)) {
636     sub = 0;
637     msgConsId = cmd.substring(CMD_QUEUE.length() +1);
638       } else if (cmd.startsWith(CMD_START)) {
639     sub = 1;
640     msgConsId = cmd.substring(CMD_START.length() +1);
641       } else if (cmd.startsWith(CMD_STOP)) {
642     sub = 2;
643     msgConsId = cmd.substring(CMD_STOP.length() +1);
644       }
645
646       buf.append("<H2>List of messages consumers</H2>\n");
647       buf.append("<TABLE BORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"0\" WIDTH=\"100%\">\n");
648       for (Enumeration c=AgentServer.getConsumers(); c.hasMoreElements(); ) {
649     MessageConsumer cons = (MessageConsumer) c.nextElement();
650
651     buf.append("<TR>\n" +
652            "<TD CLASS=FONT1 VALIGN=\"TOP\" WIDTH=\"20%\">\n" +
653            "<CENTER>").append(cons.getName()).append("</CENTER>\n");
654     buf.append("</TD>\n");
655     buf.append("<TD WIDTH=\"80%\">");
656
657     buf.append("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD COLSPAN=\"3\">");
658     
659     if (msgConsId.equals(cons.getName())) {
660       if (sub == 1) {
661         try {
662           cons.start();
663         } catch (Exception JavaDoc exc) {
664           buf.append("<TR><TD COLSPAN=\"3\"><PRE WIDTH=\"80\">");
665           buf.append(exc.toString()).append(" during starting.\n");
666           buf.append("</PRE></TD></TR>");
667         }
668       } else if (sub == 2) {
669           cons.stop();
670       }
671     }
672
673     buf.append(cons.getClass().getName());
674     if (cons.isRunning()) {
675       buf.append(" is running.");
676     } else {
677       buf.append(" is stopped.");
678     }
679     buf.append("</TD></TR><TR>");
680
681     buf.append("<TD CLASS=FONT1 ALIGN=\"CENTER\" BGCOLOR=\"#3366FF\"><A HREF=\"")
682       .append(base).append(CMD_MSG_CONS)
683           .append(CMD_STOP + "+").append(cons.getName())
684       .append("\">STOP</A>\n")
685       .append("</TD>");
686
687     buf.append("<TD CLASS=FONT1 ALIGN=\"CENTER\" BGCOLOR=\"#3366FF\"><A HREF=\"")
688       .append(base).append(CMD_MSG_CONS)
689           .append(CMD_START + "+").append(cons.getName())
690       .append("\">START</A>\n")
691       .append("</TD>");
692
693     buf.append("<TD CLASS=FONT1 ALIGN=\"CENTER\" BGCOLOR=\"#3366FF\"><A HREF=\"")
694       .append(base).append(CMD_MSG_CONS)
695           .append(CMD_QUEUE + "+").append(cons.getName())
696       .append("\">QUEUE</A>\n")
697       .append("</TD>");
698
699     buf.append("</TR><TR><TD COLSPAN=\"3\">");
700     buf.append("<PRE WIDTH=\"80\">\n");
701     buf.append(cons.toString());
702     buf.append("</PRE>");
703     buf.append("</TD></TR>");
704     
705     if ((msgConsId.equals(cons.getName())) && (sub == 0) && (cons.getQueue().size() > 0)) {
706       buf.append("<TR><TD COLSPAN=\"3\"><PRE WIDTH=\"80\">");
707       dumpQueue(buf, cons.getQueue().toString().toCharArray());
708       buf.append("</PRE></TD></TR>");
709     }
710
711     buf.append("</TABLE>");
712     buf.append("</TD>");
713     buf.append("</TR>\n");
714       }
715       buf.append("</TABLE>");
716
717       return;
718     }
719
720     void dumpQueue(StringBuffer JavaDoc buf, char dump[]) {
721       int j;
722       AgentId id;
723
724       try {
725     int idx = 0;
726     if (dump[idx++] != '(') throw new IllegalArgumentException JavaDoc();
727     while (true) {
728       try {
729         if (dump[idx++] != '(') throw new IllegalArgumentException JavaDoc();
730         // get "from="
731
while (dump[idx] != '=') buf.append(dump[idx++]);
732         buf.append(dump[idx++]);
733         // Get AgentId
734
if (dump[idx] != '#') throw new IllegalArgumentException JavaDoc();
735         id = null;
736         j = dumpAgentId(dump, idx);
737         if (j != -1)
738           id = AgentId.fromString(new String JavaDoc(dump, idx, j-idx));
739         if (id == null)
740           throw new IllegalArgumentException JavaDoc();
741         // The rigth URL
742
buf.append(urlAgent(id));
743         idx = j;
744         // get ",to="
745
while (dump[idx] != '=') buf.append(dump[idx++]);
746         buf.append(dump[idx++]);
747         // Get AgentId
748
if (dump[idx] != '#') throw new IllegalArgumentException JavaDoc();
749         id = null;
750         j = dumpAgentId(dump, idx);
751         if (j != -1)
752           id = AgentId.fromString(new String JavaDoc(dump, idx, j-idx));
753         if (id == null)
754           throw new IllegalArgumentException JavaDoc();
755         // The rigth URL
756
buf.append(urlAgent(id));
757         idx = j;
758         // get ",not="
759
if (dump[idx] == ',')
760           buf.append('\n');
761         else
762           throw new IllegalArgumentException JavaDoc();
763         idx++;
764         while (dump[idx] != '=') buf.append(dump[idx++]);
765         buf.append(dump[idx++]);
766         // Copy notification with AgentId transformation
767
if (dump[idx++] != '[') throw new IllegalArgumentException JavaDoc();
768         while (dump[idx] != ']') {
769           if (dump[idx] == '#') {
770         id = null;
771         j = dumpAgentId(dump, idx);
772         if (j != -1)
773           id = AgentId.fromString(new String JavaDoc(dump, idx, j-idx));
774         if (id != null) {
775           // The rigth URL
776
buf.append(urlAgent(id));
777           idx = j;
778         }
779           }
780           buf.append(dump[idx++]);
781         }
782         idx++; // skip ']'
783
idx++; // skip ','
784
// get ",update="
785
if (dump[idx] == ',')
786           buf.append('\n');
787         else
788           throw new IllegalArgumentException JavaDoc();
789         idx++;
790         while (dump[idx] != '=') buf.append(dump[idx++]);
791         buf.append(dump[idx++]);
792         //
793
if (dump[idx++] != '[') throw new IllegalArgumentException JavaDoc();
794         while (dump[idx] != ']') buf.append(dump[idx++]);
795         idx++;
796         // get deadline if there is one
797
if (dump[idx] != ')') {
798           if (dump[idx] == ',')
799         buf.append('\n');
800           else
801         throw new IllegalArgumentException JavaDoc();
802           idx++;
803           while (dump[idx] != ')') buf.append(dump[idx++]);
804         }
805         idx++;
806         if (dump[idx] == ')')
807           break;
808         else
809           buf.append("\n<hr>");
810       } catch (IllegalArgumentException JavaDoc exc) {
811         // search next '('
812
throw exc;
813       }
814     }
815       } catch (Exception JavaDoc exc) {
816     exc.printStackTrace();
817       }
818     }
819
820     void listServices(String JavaDoc cmd, StringBuffer JavaDoc buf) {
821       int sub = -1;
822       String JavaDoc sclass = null;
823
824       if (cmd.startsWith(CMD_START)) {
825     sub = 1;
826     sclass = cmd.substring(CMD_START.length() +1);
827       } else if (cmd.startsWith(CMD_STOP)) {
828     sub = 2;
829     sclass = cmd.substring(CMD_STOP.length() +1);
830       } else if (cmd.startsWith(CMD_REMOVE)) {
831     sub = 3;
832     sclass = cmd.substring(CMD_REMOVE.length() +1);
833       }
834
835       buf.append("<H2>List of services</H2>\n");
836       buf.append("<TABLE BORDER=\"1\" WIDTH=\"100%\">\n");
837
838       if (sub == 3) {
839     buf.append("<TR><TD><PRE>");
840     try {
841       ServiceManager.stop(sclass);
842       buf.append("\nService <").append(sclass).append("> stopped.");
843     } catch (Exception JavaDoc exc) {
844       buf.append("\nCan't stop service \"")
845         .append(sclass).append("\" :\n\t")
846         .append(exc.getMessage());
847     }
848     try {
849       ServiceManager.unregister(sclass);
850       buf.append("\nService <").append(sclass).append("> unregistred.");
851     } catch (Exception JavaDoc exc) {
852       buf.append("\nCan't unregister service \"")
853         .append(sclass).append("\" :\n\t")
854         .append(exc.getMessage());
855     }
856     buf.append("</PRE></TD></TR>\n");
857       }
858
859       ServiceDesc services[] = ServiceManager.getServices();
860       for (int i=0; i<services.length; i++ ){
861     buf.append("<TABLE BORDER=\"1\" WIDTH=\"100%\">\n");
862     buf.append("<TR><TD CLASS=FONT1 VALIGN=\"TOP\" COLSPAN=\"2\">")
863       .append(services[i].getClassName());
864
865     if (services[i].getClassName().equals(sclass)) {
866       if (sub == 1) {
867         try {
868           ServiceManager.start(sclass);
869         } catch (Exception JavaDoc exc) {
870           buf.append("<PRE>\nCan't start service: \n\t")
871         .append(exc.getMessage())
872         .append("</PRE>");
873         }
874       } else if (sub == 2) {
875         try {
876           ServiceManager.stop(sclass);
877         } catch (Exception JavaDoc exc) {
878           buf.append("<PRE>\nCan't stop service: \n\t")
879         .append(exc.getMessage())
880         .append("</PRE>");
881         }
882       }
883     }
884
885     buf.append("</TD></TR>");
886
887     buf.append("<TR><TD ROWSPAN=\"2\" WIDTH=\"70%\"><PRE>")
888       .append("\narguments=").append(services[i].getArguments())
889       .append("\ninitialized=").append(services[i].isInitialized())
890       .append("\nrunning=").append(services[i].isRunning())
891       .append("</PRE></TD>\n");
892
893     buf.append("<TD CLASS=FONT1 ALIGN=\"CENTER\" BGCOLOR=\"#3366FF\">")
894       .append("<A HREF=\"")
895       .append(base).append(CMD_SERVICES);
896     if (services[i].isRunning()) {
897       buf.append(CMD_STOP + "+")
898         .append(services[i].getClassName())
899         .append("\">STOP</A>\n");
900     } else {
901       buf.append(CMD_START + "+")
902         .append(services[i].getClassName())
903         .append("\">START</A>\n");
904     }
905     buf.append("</TD></TR>\n");
906
907     buf.append("<TR><TD CLASS=FONT1 ALIGN=\"CENTER\" BGCOLOR=\"#3366FF\">")
908       .append("<A HREF=\"")
909       .append(base).append(CMD_SERVICES)
910       .append(CMD_REMOVE + "+")
911       .append(services[i].getClassName())
912       .append("\">REMOVE</A>\n")
913       .append("</TD></TR>\n");
914
915 // buf.append("<TR><TD><PRE><CODE>\n");
916
// buf.append("class=" + services[i].getClassName() + "\n");
917
// buf.append("args=" + services[i].getArguments());
918
// buf.append("</CODE></PRE></TD></TR>\n");
919

920     buf.append("</TABLE>");
921       }
922       buf.append("</TABLE>");
923
924       return;
925     }
926
927     /**
928      * Parses an AgentId from a char array, it determines the sub-array
929      * that contain an AgentId, then you can get it with fromString:
930      * <pre>
931      * end = dumpAgentId(dump, start);
932      * if (end != -1)
933      * id = AgentId.fromString(new String(dump, start, end-start));
934      * </pre>
935      *
936      * @param dump The char array.
937      * @param idx The current index in array (shoul be the first
938      * charracter of the AgentId: '#').
939      *
940      * @return The index of first char after the AgentId, -1 if
941      * thebeginning of the array do not correspond to an
942      * AgentId.
943      */

944     int dumpAgentId(char dump[], int idx) {
945       if (dump[idx] != '#')
946     return -1;
947
948       int j = idx+1;
949       while ((j < dump.length) &&
950          (dump[j] >= '0') && (dump[j] <= '9')) j++;
951       if ((j == (idx +1)) || (dump[j] != '.') || (j == dump.length))
952     return -1;
953
954       idx = j; j = j+1;
955       while ((j < dump.length) &&
956          (dump[j] >= '0') && (dump[j] <= '9')) j++;
957       if ((j == (idx +1)) || (dump[j] != '.') || (j == dump.length))
958     return -1;
959
960       idx = j; j = j+1;
961       while ((j < dump.length) &&
962          (dump[j] >= '0') && (dump[j] <= '9')) j++;
963
964      if (j == (idx +1)) return -1;
965
966      return j;
967     }
968
969     /**
970      * Executes a dump command.
971      *
972      * @ param agentid String which contains the agentid
973      * like #x.y.z ,x,y,z are numbers.
974      */

975     void dumpAgent(String JavaDoc cmd, StringBuffer JavaDoc buf) {
976       AgentId id = null;
977       try {
978     if (cmd.charAt(0) != '/') throw new IllegalArgumentException JavaDoc();
979     id = AgentId.fromString(new String JavaDoc("#" + cmd.substring(1)));
980     if (id == null) throw new IllegalArgumentException JavaDoc();
981       } catch (IllegalArgumentException JavaDoc exc) {
982     buf.append("<H2>Error</H2>\n" +
983            "<P>\n" +
984            "Can't parse AgentId #x.y.z in \"" + cmd + "\"\n" +
985            "</P>\n");
986     return;
987       }
988
989       buf.append("<H2>Dump agent " + id + "</H2>\n");
990
991       Agent agent = (Agent) AgentServer.engine.agents.get(id);
992       if (agent == null) {
993     buf.append("<P CLASS=FONT2>\n" +
994            "Agent not loaded in memory.\n" +
995            "</P>\n");
996     return;
997       }
998
999       try {
1000    char dump[] = agent.toString().toCharArray();
1001    for (int i=0; i<dump.length; i++) {
1002      if (dump[i] == '(') {
1003        buf.append("<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0>\n");
1004        buf.append("<TR><TD CLASS=FONT1><PRE>\n");
1005      } else if (dump[i] == ',') {
1006        buf.append("\n");
1007      } else if (dump[i] == ')') {
1008        buf.append("</PRE></TD></TR>\n");
1009        buf.append("</TABLE>");
1010      } else if (dump[i] == '#') {
1011        id = null;
1012        int j = dumpAgentId(dump, i);
1013        if (j != -1)
1014          id = AgentId.fromString(new String JavaDoc(dump, i, j-i));
1015        if (id == null) {
1016          buf.append(dump[i]);
1017        } else {
1018          // TODO: the rigth URL
1019
buf.append(urlAgent(id));
1020          i = j -1;
1021        }
1022      } else {
1023        buf.append(dump[i]);
1024      }
1025    }
1026      } catch (IllegalArgumentException JavaDoc exc) {
1027    buf.setLength(0);
1028    buf.append("<H2>Error</H2>\n" +
1029           "<P>\n" +
1030           "Can't parse AgentId #x.y.z in \"" + cmd + "\"\n" +
1031           "</P>\n");
1032    return;
1033      }
1034    }
1035
1036    /**
1037     *
1038     */

1039    void debug(String JavaDoc cmd, StringBuffer JavaDoc buf) {
1040      ServerSocket server = null;
1041      int listen = -1;
1042
1043      buf.append("<H2>Debug Tool</H2>\n");
1044
1045      try {
1046    server = new ServerSocket(0);
1047      } catch (IOException exc) {
1048    buf.append(exc.toString()).append(" during connection.\n");
1049    return;
1050      }
1051      listen = server.getLocalPort();
1052
1053      // The applet
1054
buf.append("<APPLET CODE=\"AppletDebug.class\" CODEBASE=\"")
1055    .append(CMD_CLASS).append("\" WIDTH=\"800\" HEIGHT=\"200\">\n")
1056    .append("<PARAM NAME=\"host\" VALUE=\"").append(host).append("\"/>\n")
1057    .append("<PARAM NAME=\"port\" VALUE=\"").append(listen).append("\"/>\n")
1058    .append("<PARAM NAME=\"url\" VALUE=\"").append(base).append(CMD_DEBUG_WAIT).append("\"/>\n")
1059    .append("</APPLET>\n");
1060      
1061      // The Internal Frame
1062
buf.append("<IFRAME name=\"debug\" SRC=\"")
1063    .append(CMD_DEBUG_WAIT)
1064    .append("\" width=\"800\" height=\"400\" scrolling=\"auto\" frameborder=\"1\">\n")
1065    .append("Your browser does not support internal frames (HTML 4.0)\n.")
1066    .append("</IFRAME>\n");
1067
1068// DebugMonitor dmon = new DebugMonitor(server);
1069
// bp.start();
1070
}
1071
1072    void loadClass(String JavaDoc cmd) {
1073      BufferedOutputStream bos = null;
1074
1075// System.out.println("load:" + cmd);
1076
try {
1077    bos = new BufferedOutputStream(socket.getOutputStream());
1078    File file = new File(cmd.substring(1));
1079    byte[] c = new byte[(int) file.length()];
1080    new FileInputStream(file).read(c);
1081    bos.write(c, 0, c.length);
1082      } catch (IOException exc) {
1083    exc.printStackTrace();
1084      } finally {
1085    try {
1086      bos.flush();
1087      bos.close();
1088    } catch (IOException exc) {}
1089      }
1090    }
1091  }
1092
1093  class DebugMonitor extends Daemon {
1094    ServerSocket server = null;
1095    int listen = -1;
1096
1097    public DebugMonitor() {
1098      super("DebugMonitor");
1099
1100      // Get the logging monitor from HttpDebug (overload Daemon setup)
1101
logmon = HttpDebug.xlogmon;
1102
1103      try {
1104    server = new ServerSocket(0);
1105    listen = server.getLocalPort();
1106      } catch (IOException exc) {
1107    server = null;
1108    listen = -1;
1109      }
1110    }
1111
1112    public void run() {
1113      Socket socket = null;
1114      PrintWriter writer = null;
1115      
1116// while (isRunning) {
1117
// canStop = true;
1118
// socket = server.accept();
1119
// writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
1120

1121// while (isRunning) {
1122
// canStop = false;
1123
// System.out.println("writes:" + base + HttpDebugMonitor.CMD_DEBUG_RUN);
1124
// writer.println(base + HttpDebugMonitor.CMD_DEBUG_RUN);
1125
// if (writer.checkError())
1126
// throw new IOException();
1127
// canStop = true;
1128

1129// try {
1130
// Thread.currentThread().sleep(1000);
1131
// } catch (InterruptedException exc) {}
1132

1133// canStop = false;
1134
// System.out.println("writes:" + base + HttpDebugMonitor.CMD_DEBUG_WAIT);
1135
// writer.println(base + HttpDebugMonitor.CMD_DEBUG_WAIT);
1136
// if (writer.checkError())
1137
// throw new IOException();
1138
// canStop = true;
1139

1140// try {
1141
// System.out.println("wait");
1142
// Thread.currentThread().sleep(10000);
1143
// } catch (InterruptedException exc) {}
1144
// }
1145
// } catch (IOException exc) {
1146
// try {
1147
// socket.close();
1148
// } catch (IOException exc2) {}
1149
// exc.printStackTrace();
1150
// } finally {
1151
// finish();
1152
// }
1153
}
1154   
1155    protected void close() {}
1156
1157    protected void shutdown() {}
1158  }
1159}
1160
Popular Tags