KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > bsf > dbline > JsDb


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2002 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowlegement:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowlegement may appear in the software itself,
24  * if and wherever such third-party acknowlegements normally appear.
25  *
26  * 4. The names "Apache BSF", "Apache", and "Apache Software Foundation"
27  * must not be used to endorse or promote products derived from
28  * this software without prior written permission. For written
29  * permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache"
32  * nor may "Apache" appear in their names without prior written
33  * permission of the Apache Group.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many individuals
50  * on behalf of the Apache Software Foundation and was originally created by
51  * Sanjiva Weerawarana and others at International Business Machines
52  * Corporation. For more information on the Apache Software Foundation,
53  * please see <http://www.apache.org/>.
54  */

55
56 package org.apache.bsf.dbline;
57
58 import java.io.*;
59 import java.util.*;
60 import java.net.ProtocolException JavaDoc;
61 import java.net.ConnectException JavaDoc;
62 import java.rmi.RemoteException JavaDoc;
63
64 import org.apache.bsf.debug.*;
65 import org.apache.bsf.debug.jsdi.*;
66
67 public class JsDb
68     implements Runnable JavaDoc {
69     
70     private JsObject global;
71     private Callbacks callbacks;
72     private Thread JavaDoc m_cmdThread;
73     private Object JavaDoc m_lock;
74     private static boolean m_inCallback;
75     private static int exitStatus = 0;
76     private static boolean running = false;
77
78     Vector m_buffers;
79     int m_currentDepth, m_stackDepth;
80     Context m_stack[];
81     JsObject undefined;
82     JsEngine m_jse;
83     Hashtable m_proxies, m_rot;
84     
85     static JsDb self;
86     static BSFDebugManager gBsfManager;
87     static final int JSDB_CMD_LEN = 256;
88     static final String JavaDoc usage[] =
89     {
90         "Supported commands:",
91         "load <FILENAME> <URI>",
92         "br shortname:16",
93         "rm <breakpoint id>",
94         "set_entry_exit shortname [true, false]",
95         "exec shortname:12,28 (start line, end line to be interpreted)",
96         "step [in, over, out]",
97         "run",
98         "thrinfo",
99         "list frames (display the stack of contexts)",
100         "list (display source around current position)",
101         "list shortname[:lineno] (display source starting at the given line)",
102         "up / down (move up or down the current context on the stack)",
103         "show frame (display the current context on the stack)",
104         "show object:id[,all] (display an object with the given id, ",
105         " the option 'all' precise to enum properties",
106         " with a DONTENUM attribute.)",
107         "show scope:id[,all] (display the scope chain of the object with ",
108         " the given id,the option all precise to enum ",
109         " properties with a DONTENUM attribute.)",
110         "show prototype:id[,all] (display the prototype chain of the object ",
111         " with the given id, the option all precise ",
112         " to enum properties with a DONTENUM attribute.)",
113         "put <id>:propname=value (where the value is either a string,",
114         " a float, a boolean, or an object)",
115         " Examples: ",
116         " put <2>:foo=That's it folks",
117         " put <4>:bar=4.0",
118         " put <45>:trueOrFalse=false",
119         " put <31>:foo=<4>",
120         "That's it...",
121         "Notations:",
122         " URI: full URI, sans hostname and protocol specification",
123         " shortname: last component of the URI"
124     };
125
126     public JsDb(String JavaDoc args[])
127         throws RemoteException JavaDoc {
128         
129         self = this;
130         m_buffers = new Vector();
131         m_proxies = new Hashtable();
132         m_rot = new Hashtable();
133         m_lock = new Object JavaDoc();
134         m_inCallback = false;
135         
136         callbacks = new Callbacks(this);
137         gBsfManager.registerDebugger("javascript", callbacks);
138         
139         m_cmdThread = new Thread JavaDoc(this, "User Input Thread");
140         m_cmdThread.start();
141     }
142     
143     /**
144      * This returns a proxy object for a remote JsObject.
145      * The debugger maintains a hashtable of its proxies
146      * keyed on JsObject.
147      */

148     JsObjectProxy proxyObject(JsObject obj) {
149         
150         if (obj == null) return null;
151
152         JsObjectProxy proxy = (JsObjectProxy) m_proxies.get(obj);
153         if (proxy == null) {
154             Integer JavaDoc oid;
155             proxy = new JsObjectProxy(obj);
156             m_proxies.put(obj, proxy);
157             oid = new Integer JavaDoc(proxy.getOid());
158             m_rot.put(oid, proxy);
159         }
160         return proxy;
161     }
162     
163     /**
164      * Display the properties of an Object.
165      * The "all" parameters indicates if one wants to see
166      * all the properties, including the ones with DONTENUM
167      * attribute.
168      * IMPORTANT Note:
169      * This shows only the properties on the object itself,
170      * the prototype chain is not considered.
171      */

172     private void displayProperties(JsObjectProxy proxy, boolean all)
173         throws RemoteException JavaDoc {
174         
175         Object JavaDoc ids[], id, value;
176         String JavaDoc name;
177         JsObject object = proxy.getObject();
178         JsObject scope = object.getScope(), prot = object.getPrototype();
179         JsObjectProxy scopeProxy, protProxy;
180         int n, index;
181
182         System.out.println("Object <" + proxy.getOid() + ">");
183
184         if (scope != null) {
185             scopeProxy = proxyObject(scope);
186             System.out.println(" Scope <" + scopeProxy.getOid() + ">");
187         }
188         else System.out.println(" No scope.");
189
190         if (prot != null) {
191             protProxy = proxyObject(prot);
192             System.out.println(" Prototype <" + protProxy.getOid() + ">");
193         }
194         else System.out.println(" No prototype.");
195         
196         ids = object.getIds(all);
197         if (ids != null) {
198             for (n = 0; n < ids.length; n++) {
199                 id = ids[n];
200                 if (id instanceof String JavaDoc) {
201                     name = (String JavaDoc) id;
202                     value = object.get(name);
203                     displayProperty(name, value);
204                 }
205                 else {
206                     index = ((Integer JavaDoc) id).intValue();
207                     value = object.get(index);
208                     displayProperty(String.valueOf(index), value);
209                 }
210             }
211         }
212         else System.out.println(" No properties.");
213     }
214     
215     /**
216      * Display the Scope of an Object.
217      * The "all" parameters indicates if one wants to see
218      * all the properties, including the ones with DONTENUM
219      * attribute.
220      * IMPORTANT Note:
221      * This shows only the properties on the object itself,
222      * the prototype chain is not considered.
223      */

224     private void displayScope(JsObjectProxy proxy, boolean all)
225         throws RemoteException JavaDoc {
226         
227         Object JavaDoc ids[], id, value;
228         String JavaDoc name;
229         JsObject object = proxy.getObject();
230         JsObject scope = object.getScope();
231         JsObjectProxy scopeProxy;
232         int n, index;
233         
234         if (scope == null) {
235             System.out.println("No scope");
236             return;
237         }
238         System.out.println("Scope chain for Object <" + proxy.getOid() + ">");
239         
240         while (scope != null) {
241             scopeProxy = proxyObject(scope);
242             System.out.println("** Scope <" + scopeProxy.getOid() + ">");
243             
244             ids = scope.getIds(all);
245             for (n = 0; n < ids.length; n++) {
246                 id = ids[n];
247                 if (id instanceof String JavaDoc) {
248                     name = (String JavaDoc) id;
249                     value = object.get(name);
250                     displayProperty(name, value);
251                 }
252                 else {
253                     index = ((Integer JavaDoc) id).intValue();
254                     value = object.get(index);
255                     displayProperty(String.valueOf(index), value);
256                 }
257             }
258             scope = scope.getScope();
259         }
260     }
261     
262     /**
263      * Display the prototype chain...
264      * The "all" parameters indicates if one wants to see
265      * all the properties, including the ones with DONTENUM
266      * attribute.
267      * IMPORTANT Note:
268      * This shows only the properties on the object itself,
269      * the prototype chain is not considered.
270      */

271     private void displayPrototype(JsObjectProxy proxy, boolean all)
272         throws RemoteException JavaDoc {
273         
274         Object JavaDoc ids[], id, value;
275         String JavaDoc name;
276         JsObject object = proxy.getObject();
277         JsObject prot = object.getPrototype();
278         JsObjectProxy protProxy;
279         int n, index;
280         
281         if (prot == null) {
282             System.out.println("Empty prototype chain.");
283             return;
284         }
285         else System.out.println("Prototype Chain for Object <"
286                                 + proxy.getOid() + ">");
287         
288         while (prot != null) {
289             protProxy = proxyObject(prot);
290             System.out.println("** Prototype <" + protProxy.getOid() + ">");
291             
292             ids = prot.getIds(all);
293             for (n = 0; n < ids.length; n++) {
294                 id = ids[n];
295                 if (id instanceof String JavaDoc) {
296                     name = (String JavaDoc) id;
297                     value = object.get(name);
298                     displayProperty(name, value);
299                 }
300                 else {
301                     index = ((Integer JavaDoc) id).intValue();
302                     value = object.get(index);
303                     displayProperty(String.valueOf(index), value);
304                 }
305             }
306             prot = prot.getPrototype();
307         }
308     }
309     
310     /**
311      * Display a property. A property value can only be of the
312      * following types:
313      * <UL>
314      * <LI>java.lang.Boolean objects</LI>
315      * <LI>java.lang.String objects</LI>
316      * <LI>java.lang.Number objects</LI>
317      * <LI>org.apache.bsf.debug.jsdi.JsObject objects</LI>
318      * <LI>null</LI>
319      * <LI>The object returned by JsContext.getUndefinedValue()</LI>
320      */

321     private void displayProperty(String JavaDoc name, Object JavaDoc value) {
322         
323         System.out.print(" ");
324         
325         if (value instanceof Number JavaDoc) {
326             System.out.println(name + "=" + ((Number JavaDoc) value).floatValue());
327         }
328         else if (value instanceof String JavaDoc) {
329             System.out.println(name + "=" + value);
330         }
331         else if (value instanceof Boolean JavaDoc) {
332             System.out.println(name + "=" + ((Boolean JavaDoc) value).booleanValue());
333         }
334         else if (value instanceof JsObject) {
335             if (value == undefined) {
336                 System.out.println(name + "= undefined");
337             }
338             else {
339                 JsObjectProxy proxy = proxyObject((JsObject) value);
340                 int oid = proxy.getOid();
341
342                 System.out.println(name + "= Object <" + oid + ">");
343             }
344         }
345         else System.out.println(name + value);
346     }
347
348     /**
349      * Search for a buffer with the given name as
350      * a short name (no path).
351      * A prefix search is done, that is, any buffer
352      * that has a matching prefix will be returned.
353      */

354     private Buffer findBufferWithShortName(String JavaDoc name) {
355
356         Enumeration e = m_buffers.elements();
357         Buffer buffer;
358         String JavaDoc bufferName;
359
360         while (e.hasMoreElements()) {
361             buffer = (Buffer) e.nextElement();
362             bufferName = buffer.getName();
363             if (bufferName.startsWith(name)) return buffer;
364         }
365         return null;
366     }
367
368     /**
369      * Search for a buffer with the given URI (full path).
370      * A prefix search is done, that is, any buffer
371      * that has a matching prefix will be returned.
372      */

373     private Buffer findBufferWithURI(String JavaDoc name) {
374
375         Enumeration e = m_buffers.elements();
376         Buffer buffer;
377
378         while (e.hasMoreElements()) {
379             buffer = (Buffer) e.nextElement();
380             if (name.equals(buffer.getURI())) return buffer;
381         }
382         return null;
383     }
384
385     public void run() {
386         
387         String JavaDoc cmd;
388         boolean resume = false;
389         
390         running = true;
391         
392         while (running) {
393             cmd = readCmd();
394             try {
395                 if (cmd != null) resume = parseCmd(cmd);
396                 if (resume) inCallback(false);
397             } catch (Throwable JavaDoc t) {
398                 System.err.println("\nError while parsing/executing command.");
399                 t.printStackTrace();
400             }
401         }
402         System.exit(exitStatus);
403     }
404
405     /**
406      * Suspend a callback until the user enters a "resume"
407      * kind of commands...
408      */

409     private static void inCallback(boolean inCallback) {
410         
411         m_inCallback = inCallback;
412         if (m_inCallback) System.out.print("> ");
413     }
414
415     public String JavaDoc readCmd() {
416         
417         int count = 0;
418         char c, chars[] = new char[JSDB_CMD_LEN];
419         
420         if (m_inCallback) System.out.print("> ");
421         else System.out.print("< ");
422
423         while (count < JSDB_CMD_LEN) {
424             try {
425                 c = (char) System.in.read();
426                 chars[count++] = c;
427                 if (c == '\n')
428                     break;
429             } catch (IOException ex) {
430                 return null;
431             }
432         }
433         if (count == JSDB_CMD_LEN) {
434             System.out.println("\nLine too long.\n");
435             return null;
436         }
437         return new String JavaDoc(chars, 0, count);
438     }
439     
440     /**
441      * Parses a command line.
442      * Returns true if input needs to be suspended,
443      * that is, if the command was to resume execution
444      * in the debugged engine.
445      */

446     public boolean parseCmd(String JavaDoc line)
447         throws RemoteException JavaDoc {
448
449         boolean resume = cmdParser(line);
450         
451         if (m_inCallback) {
452             try {
453                 m_jse.poll();
454             } catch (RemoteException JavaDoc ex) {
455                 resume = true;
456             }
457         }
458         
459         return resume;
460     }
461
462     private boolean parseLoad(StringTokenizer cmdTokenizer)
463         throws RemoteException JavaDoc {
464     
465     String JavaDoc filename, uri;
466  
467         filename = cmdTokenizer.nextToken();
468         filename = filename.trim();
469         uri = cmdTokenizer.nextToken();
470         uri = uri.trim();
471         addBuffer(filename, uri);
472         return false;
473     }
474     
475     private void showUsage() {
476         
477         for (int l = 0; l < usage.length; l++) {
478             System.out.println(usage[l]);
479         }
480     }
481
482     private boolean parseStep(StringTokenizer cmdTokenizer)
483         throws RemoteException JavaDoc {
484     
485     String JavaDoc cmd, args;
486         
487         if (cmdTokenizer.hasMoreTokens()) {
488             cmd = cmdTokenizer.nextToken();
489             cmd = cmd.trim();
490             if (cmd.equals("in")) {
491                 m_jse.stepIn();
492                 return true;
493             }
494             else if (cmd.equals("out")) {
495                 if (!m_inCallback) {
496                     System.out.println("Not in a callback...");
497                     return false;
498                 }
499                 m_jse.stepOut();
500                 return true;
501             }
502             else if (cmd.equals("over")) {
503                 if (!m_inCallback) {
504                     System.out.println("Not in a callback...");
505                     return false;
506                 }
507                 m_jse.stepOver();
508                 return true;
509             }
510         }
511         else System.out.println("Incorrect syntax...");
512         
513         return false;
514     }
515
516     private boolean parseSetEntryExit(StringTokenizer cmdTokenizer)
517         throws RemoteException JavaDoc {
518         String JavaDoc buffername;
519         boolean onval;
520         Buffer buffer;
521
522         if (cmdTokenizer.countTokens() == 2) {
523             buffername = cmdTokenizer.nextToken();
524             onval = (Boolean.valueOf((cmdTokenizer.nextToken()).trim())).booleanValue();
525             buffer = findBufferWithShortName(buffername);
526
527             if (buffer != null) {
528                 gBsfManager.setEntryExit(buffer.getURI(), onval);
529                 System.out.println("Setting entry/exit status for " +
530                                    buffer.getURI() + " to " + onval);
531             }
532         }
533         else {
534             System.out.println("Incorrect syntax...");
535         }
536
537         return false;
538     }
539
540     private boolean parseRemoveBreakpoint(StringTokenizer cmdTokenizer)
541         throws RemoteException JavaDoc {
542         
543         String JavaDoc strid = cmdTokenizer.nextToken(), URI;
544         int bpid = Integer.valueOf(strid.trim()).intValue();
545         Enumeration e = m_buffers.elements();
546         BreakPoint bp;
547         Buffer buffer;
548         
549         while (e.hasMoreElements()) {
550             buffer = (Buffer) e.nextElement();
551             bp = buffer.removeBreakpoint(bpid);
552             if (bp != null) {
553                 URI = buffer.getURI();
554                 gBsfManager.removeBreakpoint(URI, bpid);
555                 System.out.println("Removed breakpoint " + bpid + " in " +
556                                    URI);
557                 break;
558             }
559         }
560         return false;
561     }
562     
563     private boolean parseBreakpoint(StringTokenizer cmdTokenizer)
564         throws RemoteException JavaDoc {
565         
566         String JavaDoc cmd, args, buffername, strno;
567         Integer JavaDoc lineno;
568         StringTokenizer wordTokenizer;
569         
570         args = cmdTokenizer.nextToken();
571         wordTokenizer = new StringTokenizer(args, ":,", false);
572         buffername = wordTokenizer.nextToken();
573         buffername = buffername.trim();
574         strno = wordTokenizer.nextToken();
575         lineno = Integer.valueOf(strno.trim());
576         addBreakpoint(buffername, (lineno.intValue() - 1));
577         return false;
578     }
579
580     private boolean parseExec(StringTokenizer cmdTokenizer)
581         throws RemoteException JavaDoc {
582         
583         String JavaDoc cmd, args, buffername, strno, scriptText;
584         Integer JavaDoc start, end;
585         StringTokenizer wordTokenizer;
586         Buffer buffer;
587         StringBuffer JavaDoc buf;
588
589         args = cmdTokenizer.nextToken();
590         wordTokenizer = new StringTokenizer(args, ":,", false);
591         buffername = wordTokenizer.nextToken();
592         buffername = buffername.trim();
593         strno = wordTokenizer.nextToken();
594         start = Integer.valueOf(strno.trim());
595         start = new Integer JavaDoc(start.intValue() - 1);
596         strno = wordTokenizer.nextToken();
597         end = Integer.valueOf(strno.trim());
598         end = new Integer JavaDoc(end.intValue() - 1);
599         buffer = findBufferWithShortName(buffername);
600         buf = buffer.buildFnOrScript(start.intValue(), end.intValue());
601         scriptText = buf.toString();
602
603         System.out.println("\nExecuting...");
604         try {
605             m_jse.eval(buffer.getName(), scriptText, start.intValue());
606         } catch (RemoteException JavaDoc ex) {
607             ex.printStackTrace();
608         }
609         System.out.println("\nExecution done.");
610
611         return false;
612     }
613
614     private boolean parseShow(StringTokenizer cmdTokenizer)
615         throws RemoteException JavaDoc {
616         
617         String JavaDoc cmd, args, what, strno;
618         StringTokenizer wordTokenizer;
619         Integer JavaDoc oid;
620         Boolean JavaDoc bool;
621
622         args = cmdTokenizer.nextToken();
623         wordTokenizer = new StringTokenizer(args, " :,", false);
624         what = wordTokenizer.nextToken();
625         what = what.trim();
626         
627         if (what.equals("frame")) {
628             showCurrentFrame();
629         }
630         else if (what.equals("scope")) {
631             bool = new Boolean JavaDoc(false);
632             strno = wordTokenizer.nextToken();
633             oid = Integer.valueOf(strno.trim());
634             if (wordTokenizer.hasMoreTokens()) {
635                 strno = wordTokenizer.nextToken();
636                 strno = strno.trim();
637                 if (strno.equals("all")) bool = new Boolean JavaDoc(true);
638             }
639             else bool = new Boolean JavaDoc(false);
640             showScope(oid, bool.booleanValue());
641             
642         }
643         else if (what.equals("prototype")) {
644             bool = new Boolean JavaDoc(false);
645             strno = wordTokenizer.nextToken();
646             oid = Integer.valueOf(strno.trim());
647             if (wordTokenizer.hasMoreTokens()) {
648                 strno = wordTokenizer.nextToken();
649                 strno = strno.trim();
650                 if (strno.equals("all")) bool = new Boolean JavaDoc(true);
651             }
652             else bool = new Boolean JavaDoc(false);
653             showPrototype(oid, bool.booleanValue());
654         }
655         else if (what.equals("object")) {
656             bool = new Boolean JavaDoc(false);
657             strno = wordTokenizer.nextToken();
658             oid = Integer.valueOf(strno.trim());
659             if (wordTokenizer.hasMoreTokens()) {
660                 strno = wordTokenizer.nextToken();
661                 strno = strno.trim();
662                 if (strno.equals("all")) bool = new Boolean JavaDoc(true);
663             } else bool = new Boolean JavaDoc(false);
664             showObject(oid, bool.booleanValue());
665         }
666         return false;
667     }
668     
669     private boolean parsePut(String JavaDoc args)
670         throws RemoteException JavaDoc {
671
672         String JavaDoc token, strval, propname;
673         StringTokenizer wordTokenizer, fieldTokenizer;
674         Float JavaDoc fval;
675         Integer JavaDoc oid;
676         Boolean JavaDoc bool;
677         JsObjectProxy proxy;
678         JsObject target, oval;
679
680         wordTokenizer = new StringTokenizer(args, ":=", false);
681         token = wordTokenizer.nextToken();
682         token = token.trim();
683         token = token.substring(1, token.length() - 1);
684         oid = Integer.valueOf(token);
685         proxy = (JsObjectProxy) m_rot.get(oid);
686
687         if (proxy == null) return false;
688         target = proxy.getObject();
689         token = wordTokenizer.nextToken();
690         propname = token.trim();
691         token = wordTokenizer.nextToken();
692         token = token.trim();
693
694         try {
695             fval = Float.valueOf(token);
696             target.put(propname, fval);
697         } catch (NumberFormatException JavaDoc ex) {
698             if (token.equals("false")) {
699                 bool = new Boolean JavaDoc(false);
700                 target.put(propname, bool);
701             }
702             else if (token.equals("true")) {
703                 bool = new Boolean JavaDoc(true);
704                 target.put(propname, bool);
705             }
706             else if (token.startsWith("<")) {
707                 token = token.substring(1, token.length() - 1);
708                 oid = Integer.valueOf(token);
709                 proxy = (JsObjectProxy) m_rot.get(oid);
710                 if (proxy == null) return false;
711                 oval = proxy.getObject();
712                 target.put(propname, oval);
713             }
714             else target.put(propname, token);
715         }
716         return false;
717     }
718
719     private boolean parseList(StringTokenizer cmdTokenizer)
720         throws RemoteException JavaDoc {
721         
722         String JavaDoc cmd, args, what, strno;
723         StringTokenizer wordTokenizer;
724         
725         if (!cmdTokenizer.hasMoreTokens()) {
726             listBuffer();
727             return false;
728         }
729         
730         args = cmdTokenizer.nextToken();
731         wordTokenizer = new StringTokenizer(args, " :", false);
732         what = wordTokenizer.nextToken();
733         what = what.trim();
734         
735         if (what.equals("buffers")) {
736             listBuffers();
737         }
738         else if (what.equals("breakpoints")) {
739             listBreakpoints();
740         }
741         else if (what.equals("frames")) {
742             listFrames();
743         }
744         else {
745             Integer JavaDoc lineno = new Integer JavaDoc(-1);
746             if (wordTokenizer.hasMoreTokens()) {
747                 strno = wordTokenizer.nextToken();
748                 lineno = Integer.valueOf(strno.trim());
749                 lineno = new Integer JavaDoc(lineno.intValue() - 1);
750             }
751             listBuffer(what, lineno.intValue());
752         }
753         return false;
754     }
755
756     public boolean cmdParser(String JavaDoc line)
757         throws RemoteException JavaDoc {
758         
759         String JavaDoc cmd, args;
760         StringTokenizer cmdTokenizer = new StringTokenizer(line, " ", false);
761         
762         if (cmdTokenizer.hasMoreTokens()) {
763             cmd = cmdTokenizer.nextToken();
764             cmd = cmd.trim();
765             cmd = cmd.toLowerCase();
766             if (cmd.equals("load")) {
767                 return parseLoad(cmdTokenizer);
768             }
769             else if (cmd.equals("put")) {
770                 if (m_inCallback) {
771                     args = line.substring(line.indexOf(" "));
772                     parsePut(args);
773                 }
774                 else System.out.println("Not in a callback...");
775             }
776             else if (cmd.equals("usage") || cmd.equals("help")) {
777                 showUsage();
778             }
779             else if (cmd.equals("step")) {
780                 if (m_inCallback) return parseStep(cmdTokenizer);
781                 else System.out.println("Not in a callback...");
782             }
783             else if (cmd.equals("br")) {
784                 return parseBreakpoint(cmdTokenizer);
785             }
786             else if (cmd.equals("rm")) {
787                 return parseRemoveBreakpoint(cmdTokenizer);
788             }
789             else if (cmd.equals("set_entry_exit")) {
790                 return parseSetEntryExit(cmdTokenizer);
791             }
792             else if (cmd.equals("exec")) {
793                 if (m_inCallback) return parseExec(cmdTokenizer);
794                 else System.out.println("Not in a callback...");
795             }
796             else if (cmd.equals("up")) {
797                 if (m_inCallback) up();
798                 else System.out.println("Not in a callback...");
799             }
800             else if (cmd.equals("down")) {
801                 if (m_inCallback) down();
802                 else System.out.println("Not in a callback...");
803             }
804             else if (cmd.equals("run")) {
805                 if (m_inCallback) {
806                     m_jse.run();
807                     return true;
808                 }
809                 else System.out.println("Not in a callback...");
810             }
811             else if (cmd.equals("show")) {
812                 return parseShow(cmdTokenizer);
813             }
814             else if (cmd.equals("list")) {
815                 return parseList(cmdTokenizer);
816             }
817             else if (cmd.equals("thrinfo")) {
818                 if (m_inCallback) showThrInfo();
819                 else System.out.println("Not in a callback...");
820             }
821             else if (cmd.equals("quit")) {
822                 exitDebugger(0);
823             }
824             else if (cmd.equals("")) {
825                 // Ignore bogus user input.
826
}
827             else System.out.println("Unrecognized command: " + cmd +
828                                     "\nTo see valid commands, type usage");
829         }
830         return false;
831     }
832     
833     public void addBreakpoint(String JavaDoc buffername, int lineno)
834         throws RemoteException JavaDoc {
835     
836     Buffer buffer = findBufferWithShortName(buffername);
837         
838         if (buffer != null) {
839             BreakPoint bp = new BreakPoint();
840             bp.m_lineno = lineno;
841             bp.m_buffer = buffer;
842             buffer.addBreakpoint(bp);
843             gBsfManager.placeBreakpointAtLine(bp.m_id, buffer.getURI(),
844                                               lineno);
845             System.out.println("Breakpoint " + bp.m_id + " at "
846                                + (bp.m_lineno + 1));
847         }
848     }
849
850     public Buffer addBuffer(String JavaDoc filename, String JavaDoc uri) {
851         
852         Buffer buffer = findBufferWithURI(uri);
853         
854         if (buffer == null) buffer = Buffer.factory(filename, uri);
855         if (buffer != null) {
856             m_buffers.addElement(buffer);
857             System.out.println("Loaded buffer: " + uri);
858         }
859         return buffer;
860     }
861
862     public void createdEngine(JsEngine engine)
863         throws RemoteException JavaDoc {
864
865         m_jse = engine;
866         m_jse.setDebugger(callbacks);
867         undefined = m_jse.getUndefinedValue();
868     }
869
870     public void deletedEngine(JsEngine engine) {
871         
872         if (m_jse == engine || m_jse.equals(engine)) m_jse = null;
873     }
874
875     public void down() {
876         
877         m_currentDepth--;
878         if (m_currentDepth < 0) m_currentDepth = 0;
879     }
880
881     public void showThrInfo() {
882         try {
883             System.out.println("Thread: " + m_jse.getThread());
884             System.out.println("ThreadGroup: " + m_jse.getThreadGroup());
885         } catch (RemoteException JavaDoc ex) {
886             ex.printStackTrace();
887             return;
888         }
889     }
890
891     public static void exitDebugger(int status) {
892         inCallback(false);
893         BSFConnect.disconnect();
894         exitStatus = status;
895         running = false;
896     }
897
898     /**
899      * initialize the engine. put the manager into the context -> manager
900      * map hashtable too.
901      */

902     public void handleBreakpointHit(JsContext top)
903         throws RemoteException JavaDoc {
904     
905     int d, lineno;
906         JsContext cx;
907         String JavaDoc name;
908         Buffer buffer;
909         JsEngine jse = top.getEngine();
910         
911         if (m_jse != jse) throw new Error JavaDoc();
912   
913     m_stackDepth = m_jse.getContextCount();
914         System.out.println("\n stack depth="+m_stackDepth);
915         if (m_stackDepth <= 0)
916             throw new RemoteException JavaDoc("Error: Stack cannot be empty.");
917
918         m_stack = new Context[m_stackDepth];
919         for (d = 0; d < m_stackDepth; d++) {
920             cx = m_jse.getContext(d);
921             name = cx.getSourceName();
922             buffer = findBufferWithURI(name);
923             m_stack[d] = new Context(cx, buffer);
924         }
925         m_currentDepth = 0;
926         lineno = m_stack[0].getCurrentLine();
927         name = m_stack[0].getBufferName();
928         System.out.println(" in JSP " + name + " at line " + (lineno + 1));
929         
930         inCallback(true);
931     }
932
933     public void handleEngineStopped(JsContext cx) {
934     }
935
936     public void handleExceptionThrown(JsContext top, Object JavaDoc exception)
937         throws RemoteException JavaDoc {
938         
939         int d, lineno;
940         String JavaDoc name;
941         JsContext cx;
942         Buffer buffer;
943         JsEngine jse = top.getEngine();
944         
945         if (m_jse != jse) throw new Error JavaDoc();
946         
947         m_stackDepth = m_jse.getContextCount();
948         m_stack = new Context[m_stackDepth];
949         for (d = 0; d < m_stackDepth; d++) {
950             cx = m_jse.getContext(d);
951             name = cx.getSourceName();
952             buffer = findBufferWithURI(name);
953             m_stack[d] = new Context(cx, buffer);
954         }
955         m_currentDepth = 0;
956         lineno = m_stack[0].getCurrentLine();
957         name = m_stack[0].getBufferName();
958         System.out.println("Exception thrown at line " + name
959                            + ":" + (lineno + 1) + " reached.");
960         inCallback(true);
961     }
962
963     /**
964      * initialize the engine. put the manager into the context -> manager
965      * map hashtable too.
966      */

967     public void handleSteppingDone(JsContext top)
968         throws RemoteException JavaDoc {
969     
970     int d, lineno;
971         JsContext cx;
972         String JavaDoc name;
973         Buffer buffer;
974         JsEngine jse = top.getEngine();
975     
976     if (m_jse != jse) throw new Error JavaDoc();
977
978         m_stackDepth = m_jse.getContextCount();
979         System.out.println("\n stack depth="+m_stackDepth);
980         if (m_stackDepth <= 0)
981             throw new RemoteException JavaDoc("Error: Stack cannot be empty.");
982
983         m_stack = new Context[m_stackDepth];
984         for (d = 0; d < m_stackDepth; d++) {
985             cx = m_jse.getContext(d);
986             name = cx.getSourceName();
987             buffer = findBufferWithURI(name);
988             m_stack[d] = new Context(cx, buffer);
989         }
990         m_currentDepth = 0;
991         lineno = m_stack[0].getCurrentLine();
992         name = m_stack[0].getBufferName();
993         System.out.println("Stepped to line " + name
994                            + ":" + (lineno + 1) + " reached.");
995         inCallback(true);
996     }
997     
998     public void listBreakpoints() {
999         
1000        Enumeration e = m_buffers.elements(), ebp;
1001        BreakPoint bp;
1002        Buffer buffer;
1003
1004        while (e.hasMoreElements()) {
1005            buffer = (Buffer) e.nextElement();
1006            System.out.println("Buffer " + buffer.getName());
1007            ebp = buffer.getBreakpoints();
1008            while (ebp.hasMoreElements()) {
1009                bp = (BreakPoint) ebp.nextElement();
1010                System.out.println("Breakpoint " + bp.m_id
1011                                   + " at " + (bp.m_lineno + 1));
1012            }
1013        }
1014    }
1015    
1016    public void listBuffer() {
1017        
1018        String JavaDoc line, name;
1019        int d, start, end;
1020        Context cx;
1021        Buffer buffer;
1022        
1023        if (m_stack == null) return;
1024        
1025        cx = m_stack[m_currentDepth];
1026        name = cx.getBufferName();
1027        
1028        buffer = cx.getBuffer();
1029        start = cx.getCurrentLine();
1030        
1031        listBufferLines(buffer, start - 5, 10, cx);
1032    }
1033    
1034    public void listBuffer(String JavaDoc buffername, int start) {
1035
1036        Buffer buffer = findBufferWithShortName(buffername);
1037        Context cx = null;
1038        int d;
1039
1040        if (buffer == null) return;
1041
1042        for (d = 0; d < m_stackDepth; d++) {
1043            cx = m_stack[d];
1044            if (buffer == cx.getBuffer()) break;
1045            cx = null;
1046        }
1047        listBufferLines(buffer, start, 10, cx);
1048    }
1049
1050    public void listBufferLines(Buffer buffer, int start,
1051                                int count, Context cx) {
1052        
1053        String JavaDoc line;
1054        int d, l;
1055        
1056        if (start < 0) start = buffer.getCurrentLine();
1057        
1058        for (l = start; l < start + count; l++) {
1059            line = buffer.getLine(l);
1060            if (line == null)
1061                break;
1062            if (cx != null && l == cx.getCurrentLine())
1063                System.out.print("-> " + (l+1) + ":");
1064            else
1065                System.out.print(" " + (l+1) + ":");
1066            System.out.println(line);
1067        }
1068        buffer.setCurrentLine(l);
1069    }
1070
1071    public void listBuffers() {
1072        
1073        Enumeration e = m_buffers.elements();
1074        Buffer buffer;
1075
1076        while (e.hasMoreElements()) {
1077            buffer = (Buffer) e.nextElement();
1078            System.out.println(buffer.getName());
1079        }
1080    }
1081
1082    public void listFrames() {
1083
1084        int d;
1085        Context cx;
1086
1087        for (d = m_currentDepth; d < m_stackDepth; d++) {
1088            cx = m_stack[d];
1089            System.out.print(cx.getBufferName());
1090            System.out.println(":" + (cx.getCurrentLine() + 1));
1091        }
1092    }
1093
1094    public static void main(String JavaDoc args[]) {
1095
1096        try {
1097            Object JavaDoc lock = new Object JavaDoc();
1098            String JavaDoc host =
1099                System.getProperty("org.apache.bsf.dbline.hostName");
1100
1101            while (gBsfManager == null && exitStatus == 0) {
1102                try {
1103                    gBsfManager =
1104                        BSFConnect.connect(host, -1);
1105                } catch (ProtocolException JavaDoc pe) {
1106                    System.out.println(pe.getMessage());
1107                    exitStatus = 1;
1108                    continue;
1109                } catch (ConnectException JavaDoc ce) {
1110                    System.out.println(ce.getMessage());
1111                    exitStatus = 2;
1112                    continue;
1113                } catch (Throwable JavaDoc re) {
1114                    gBsfManager = null;
1115                }
1116                
1117                if (gBsfManager != null) {
1118                    new JsDb(args);
1119                }
1120                else {
1121                    System.out.println("Manager not there yet, sleeping.");
1122                    synchronized (lock) {
1123                        try {
1124                            lock.wait(10000);
1125                        } catch (InterruptedException JavaDoc ie) {
1126                        }
1127                    }
1128                }
1129            }
1130        } catch (Exception JavaDoc e) {
1131            e.printStackTrace();
1132            return;
1133        }
1134
1135        if (exitStatus > 0) System.exit(exitStatus);
1136    }
1137
1138    public void showCurrentFrame()
1139        throws RemoteException JavaDoc {
1140
1141        int d, n, index;
1142        Context cx = m_stack[m_currentDepth];
1143        JsContext jscx = cx.getJsContext();
1144        JsObject scope = jscx.getScope(), args;
1145        boolean notAfunction = false;
1146        Object JavaDoc ids[], value;
1147        String JavaDoc name;
1148        JsObjectProxy proxy;
1149        
1150        System.out.print("\nCurrent frame: " + cx.getBufferName());
1151        System.out.println(":" + cx.getCurrentLine());
1152        System.out.println("\nProperties in scope: ");
1153        while (scope != null) {
1154            proxy = proxyObject(scope);
1155            displayProperties(proxy, false);
1156            scope = scope.getScope();
1157        }
1158    }
1159    
1160    public void showObject(Integer JavaDoc oid, boolean all)
1161        throws RemoteException JavaDoc {
1162        
1163        JsObjectProxy proxy = (JsObjectProxy) m_rot.get(oid);
1164        
1165        if (proxy == null) System.out.println("Unknown object <"
1166                                              + oid + "> !");
1167        else displayProperties(proxy, all);
1168    }
1169    
1170    public void showScope(Integer JavaDoc oid, boolean all)
1171        throws RemoteException JavaDoc {
1172    
1173    JsObjectProxy proxy = (JsObjectProxy) m_rot.get(oid);
1174        
1175        if (proxy == null) System.out.println("Unknown object <"
1176                                              + oid + "> !");
1177    else displayScope(proxy, all);
1178    }
1179    
1180    public void showPrototype(Integer JavaDoc oid, boolean all)
1181        throws RemoteException JavaDoc {
1182    
1183    JsObjectProxy proxy = (JsObjectProxy) m_rot.get(oid);
1184        
1185        if (proxy == null) System.out.println("Unknown object <"
1186                                              + oid + "> !");
1187    else displayPrototype(proxy, all);
1188    }
1189    
1190    public void up() {
1191
1192        m_currentDepth++;
1193        if (m_currentDepth >= m_stackDepth) m_currentDepth = m_stackDepth - 1;
1194    }
1195}
1196
Popular Tags