KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > aspectj > debugger > base > Debugger


1 /* -*- Mode: JDE; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  *
3  * This file is part of the debugger and core tools for the AspectJ(tm)
4  * programming language; see http://aspectj.org
5  *
6  * The contents of this file are subject to the Mozilla Public License
7  * Version 1.1 (the "License"); you may not use this file except in
8  * compliance with the License. You may obtain a copy of the License at
9  * either http://www.mozilla.org/MPL/ or http://aspectj.org/MPL/.
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is AspectJ.
17  *
18  * The Initial Developer of the Original Code is Xerox Corporation. Portions
19  * created by Xerox Corporation are Copyright (C) 1999-2002 Xerox Corporation.
20  * All Rights Reserved.
21  */

22
23 package org.aspectj.debugger.base;
24
25 //import org.aspectj.debugger.DebuggerBuild;
26
import org.aspectj.debugger.request.*;
27
28 import com.sun.jdi.*;
29 import com.sun.jdi.event.*;
30 import com.sun.jdi.connect.*;
31 import com.sun.jdi.request.*;
32 import java.io.*;
33 import java.util.*;
34 import java.text.*;
35
36 /**
37  * Debugger.java
38  * The main debugger application.
39  *
40  * Created: Mon Aug 21 11:29:37 2000
41  *
42  * @author <a HREF="mailto:palm@parc.xerox.com"Jeffrey Palm</a>
43  */

44
45 public class Debugger implements CommandReceiver, ErrorLoggable {
46
47     public static boolean demoMode = true;
48
49     protected String JavaDoc currentStoppedSource = "";
50     protected String JavaDoc date = "00/11/14"; //TODO Change
51
protected String JavaDoc version = "ajdb, version " + date;
52     protected String JavaDoc prompt = ">";
53     protected String JavaDoc runningClass;
54     protected String JavaDoc status;
55     protected String JavaDoc oldClass = "";
56     protected String JavaDoc oldVmArgs = "";
57     protected String JavaDoc oldCommandLine = "";
58
59     private List requestActions;
60     private List monitorList;
61     private List excludes;
62     private List importPaths;
63     private List filePaths;
64
65     protected Threads threads;
66     protected DebuggerApp app;
67     
68     private Parser parser;
69     private SourceManager sourceManager;
70     private Evaluator evaluator;
71     private EventSpinner spinner;
72     private Options options = new Options();
73
74     private int currentStoppedLine = -1;
75     private int monitors = 1;
76     private boolean isRunning = false;
77     private boolean isStandAlone = true; //TODO: Will be false
78
private boolean isStopped = false;
79
80     public static boolean debug = false; //true
81
public static void db(Object JavaDoc o) {
82         if (debug) {
83             Thread.yield();
84             System.err.println("<DEBUGGER>: " + o);
85         }
86     }
87
88     /**
89      * Start an empty debugger, mainly for testing...
90      */

91     public Debugger() {
92         this(new DebuggerAdapter());
93     }
94
95     /**
96      * Use the application passed in to start and start the debugger.
97      *
98      * @param app The DebuggerApp that will drive the application.
99      */

100     public Debugger(DebuggerApp app) {
101         super();
102         me();
103         this.app = app;
104         app.outln("Initializing ajdb...");
105         new Checker(this).check();
106         spinner = new EventSpinner(this);
107         threads = new Threads(this);
108         parser = new Parser(this);
109         sourceManager = new SourceManager(this);
110         evaluator = new Evaluator(this);
111         requestActions = new Vector();
112         monitorList = new Vector();
113         excludes = new Vector();
114         importPaths = new Vector();
115         filePaths = new Vector();
116         addImportPath("");
117     }
118
119     /**
120      * Returns a VM for the arguments.
121      *
122      * @param vmArgs arguments sent to the VM.
123      * @param className name of the class to invoke.
124      * @param commandLine commandline arguments as a String.
125      * @return a new VM.
126      */

127     private void getVM(final String JavaDoc vmArgs,
128                        final String JavaDoc className,
129                        final String JavaDoc commandLine) {
130         if (vm != null) {
131             vm = null;
132         }
133         if (Modes.isJBuilder() || Modes.isForte()) {
134             vm = safeConnect(vmArgs, className, commandLine);
135         } else {
136             vm = findVM(vmArgs, className, commandLine);
137         }
138     }
139
140     /**
141      * Safely connects the VM and handles any errors
142      * that arise.
143      *
144      * @param vmArgs arguments sent to the VM.
145      * @param className name of the class to invoke.
146      * @param commandLine commandline arguments as a String.
147      * @return a new VM.
148      */

149     private VirtualMachine safeConnect(String JavaDoc vmArgs,
150                                        String JavaDoc className,
151                                        String JavaDoc commandLine) {
152         try {
153             return connectCommand(vmArgs, className, commandLine);
154         } catch (DebuggerException de) {
155             app.handleDebuggerException(de);
156         } catch (Throwable JavaDoc t) {
157             app.handleInternalException(t);
158         }
159         return null;
160     }
161
162     private void saveClassName(String JavaDoc oldClassName) {
163         this.oldClass = oldClassName;
164     }
165
166     private static boolean empty(String JavaDoc str) {
167         return str == null || str.length() == 0 || str.trim().equals("");
168     }
169     
170     /**
171      * Starts up the debugger.
172      *
173      * @param className name of the class to load, this can
174      * be null.
175      * @param vmArgs arguments going directly to the VM.
176      * @param commandLine command line arguments as a String.
177      * @param isSuspended true is we should wait at main(String[]).
178      * @param debugTraceMode true is we should use tracing mode.
179      */

180     protected void go(String JavaDoc className,
181                       String JavaDoc vmArgs,
182                       String JavaDoc commandLine,
183                       boolean isSuspended,
184                       int debugTraceMode) {
185
186         // get rid of the old Threads
187
(threads = new Threads(this)).flush();
188
189         // Save the previous run...
190
if (empty(className)) className = oldClass;
191         if (className != null) oldClass = className;
192         if (empty(vmArgs)) vmArgs = oldVmArgs;
193         if (vmArgs != null) oldVmArgs = vmArgs;
194         if (empty(commandLine)) commandLine = oldCommandLine;
195         if (commandLine != null) oldCommandLine = commandLine;
196         if (Modes.isJBuilder() || Modes.isForte() ||
197             (className != null && !className.trim().equals(""))) {
198             getVM(vmArgs, className, commandLine);
199         }
200
201         String JavaDoc error =
202             "The class '" + className + "', args '" + vmArgs + "'" +
203             "\n, and/or command line '" + commandLine + "' are invalid";
204
205         // try to start the VM
206
try {
207             startUpVM(vm, error, className, debugTraceMode, isSuspended);
208         } catch (ClassNotFoundException JavaDoc cnfe) {
209             handleClassNotFound(cnfe);
210         } catch (NoClassDefFoundError JavaDoc ncdfe) {
211             handleClassNotFound(ncdfe);
212         }
213
214         // tell the listeners we've started
215
fireStartEvent();
216         return;
217     }
218
219     private void handleClassNotFound(Throwable JavaDoc cnfe) {
220         cnfe.printStackTrace();
221     }
222
223     private final static String JavaDoc NO_ERROR = "default.error";
224     private final static String JavaDoc NO_CLASS = "default.class";
225     private void startUpVM (VirtualMachine newVm)
226         throws ClassNotFoundException JavaDoc,
227                NoClassDefFoundError JavaDoc {
228         startUpVM(newVm, NO_ERROR, NO_CLASS,
229                   VirtualMachine.TRACE_NONE, false);
230     }
231
232     /**
233      * Starts up the passed in VM.
234      *
235      * @param newVm the new VM to use and start up.
236      * @param error error message to print if problems
237      * arise -- this can be null.
238      * @param debugTraceMode trace mode to use.
239      * @param isSuspended true to stop at main(String[]).
240      */

241     private void startUpVM(VirtualMachine newVm,
242                            String JavaDoc error,
243                            String JavaDoc className,
244                            int debugTraceMode,
245                            boolean isSuspended)
246         throws ClassNotFoundException JavaDoc,
247                NoClassDefFoundError JavaDoc {
248         this.vm = newVm;
249         if (vm == null) {
250             if (!Modes.isJBuilder() && !Modes.isForte()) {
251                 error("The VM is null.\n" + error);
252             }
253             return;
254         }
255         Process JavaDoc process = vm.process();
256         redirect(process.getErrorStream(), "error-dumper");
257         redirect(process.getInputStream(), "input-dumper");
258         vm.setDebugTraceMode(debugTraceMode);
259         spinner.start();
260         wakeUpRequests();
261         if (isSuspended) {
262             try {
263                 stopInCommand(className, "main(java.lang.String[])");
264             } catch (NoVMException nvme) {
265                 app.handleInternalException(nvme);
266                 return;
267             } catch (DebuggerException de) {
268                 app.handleInternalException(de);
269                 return;
270             }
271         }
272
273         EventRequestManager em = vm.eventRequestManager();
274         ClassPrepareRequest cpr = em.createClassPrepareRequest();
275         cpr.setSuspendPolicy(EventRequest.SUSPEND_ALL);
276         cpr.enable();
277
278         ClassUnloadRequest cur = em.createClassUnloadRequest();
279         cur.setSuspendPolicy(EventRequest.SUSPEND_ALL);
280         cur.enable();
281
282         ThreadStartRequest tsr = em.createThreadStartRequest();
283         tsr.setSuspendPolicy(EventRequest.SUSPEND_ALL);
284         tsr.enable();
285
286         ThreadDeathRequest tdr = em.createThreadDeathRequest();
287         tdr.setSuspendPolicy(EventRequest.SUSPEND_ALL);
288         tdr.enable();
289
290         ExceptionRequest er = em.createExceptionRequest(null, false, true);
291         er.setSuspendPolicy(EventRequest.SUSPEND_ALL);
292         er.enable();
293
294         vm.resume();
295     }
296
297     public void setOptions(Options options) {
298         this.options = options;
299         if (options.isSet("sourcepath")) {
300             use(options.getOpt("sourcepath"));
301         }
302     }
303
304     public void log(Object JavaDoc o) {
305         if (!getOptions().isSet("nologging")) {
306             app.log(o);
307         }
308     }
309
310     public Options getOptions() {
311         return options;
312     }
313
314     /**
315      * Resumes all the threads until the wait count
316      * is back to zero.
317      */

318     public void resumeUntilZero() throws DebuggerException {
319         resumeUntilZero(getVM().allThreads(), 1);
320         getVM().resume();
321     }
322
323     /**
324      * Resumes all the threads.
325      */

326     public void resume() throws DebuggerException {
327         resume(getVM().allThreads());
328     }
329
330     /**
331      * Resumes the list of threads until their
332      * wait count is down to 0.
333      *
334      * @param threads List of threads to resume.
335      */

336     public void resumeUntilZero(List threads) throws DebuggerException {
337         resumeUntilZero(threads, 0);
338     }
339
340     /**
341      * Resumes all the threads until their wait count is
342      * <code>num</code>.
343      *
344      * @param threads Threads to resume.
345      * @param num bottom limit on the wait count.
346      */

347     public void resumeUntilZero(List threads, int num) throws DebuggerException {
348         Iterator iter = threads.iterator();
349         while (iter.hasNext()) {
350             ThreadReference threadRef = (ThreadReference) iter.next();
351             resumeUntilZero(threadRef, num);
352         }
353
354     }
355
356     /**
357      * Resumes the list of threads.
358      *
359      * @param threads Threads to resume.
360      */

361     public void resume(List threads) {
362         Iterator iter = threads.iterator();
363         while (iter.hasNext()) {
364             resume((ThreadReference) iter.next());
365         }
366     }
367
368     /**
369      * Resumes single thread until wait count is 0.
370      *
371      * @param threadRef Thread to resume to 0.
372      */

373     public void resumeUntilZero(ThreadReference threadRef) {
374         resumeUntilZero(threadRef, 0);
375     }
376
377     /**
378      * Resumes single thread to <code>num</code>.
379      *
380      * @param threadRef Thread to resume.
381      * @param num bottom limit wait count.
382      */

383     public void resumeUntilZero(ThreadReference threadRef, int num) {
384         int n = threadRef.suspendCount();
385         while ((n--) > num) {
386             threadRef.resume();
387         }
388     }
389
390     /**
391      * Resumes single thread.
392      */

393     public void resume(ThreadReference threadRef) {
394         threadRef.resume();
395     }
396
397     public Evaluator getEvaluator() {
398         return evaluator;
399     }
400
401     /**
402      * Gets the value for <code>o</code> in the default frame.
403      *
404      * @param o Object whose Value we're after.
405      * @return Value of <code>o</code>.
406      */

407     public Value getValue(Object JavaDoc o)
408         throws NoVMException, DebuggerException {
409         return getValue(o, getDefaultFrame());
410     }
411
412     /**
413      * Gets the value for <code>o</code> in <code>frame</code>
414      *
415      * @param o Object whose Value we're after.
416      * @param frame StackFrame in which to for the value.
417      * @return Value of <code>o</code>.
418      */

419     public Value getValue(Object JavaDoc o, StackFrame frame)
420         throws NoVMException, DebuggerException {
421         return getEvaluator().getValue(o, frame);
422     }
423
424     /**
425      * Returns a RefernceType for the given <code>className</code>
426      * in the current VM. This will be null if there is
427      * no running VM, or the className is shit.
428      *
429      * @param className name of the class.
430      * @return ReferenceType for <code>className</code> in
431      * the running VM.
432      */

433     public ReferenceType getReferenceTypeFromToken(String JavaDoc className)
434         throws NoVMException {
435         ReferenceType refType = null;
436         Iterator iter = getVM().allClasses().iterator();
437         while (iter.hasNext()) {
438             refType = (ReferenceType) iter.next();
439             if (refType.name().equals(className)) {
440                 return refType;
441             }
442         }
443         return null;
444     }
445
446     /**
447      * Returns a ThreadReference for the given <code>threadName</code>
448      * in the current VM. This will be null if there is
449      * no running VM, or the threadName is shit. If the passed
450      * in value is the empty string the default thread is returned.
451      *
452      * @param threadName name of the thread
453      * @return ThreadReference for <code>className</code> in
454      * the running VM.
455      */

456     public ThreadReference getThread(String JavaDoc threadName)
457         throws DebuggerException {
458         if (threadName.equals("")) {
459             return getDefaultThread();
460         }
461         Iterator iter = vm().allThreads().iterator();
462         while (iter.hasNext()) {
463             ThreadReference threadRef = (ThreadReference) iter.next();
464             if (threadRef.name().equals(threadName)) {
465                 return threadRef;
466             } else {
467                 try {
468                     long ourID = Long.parseLong(threadName);
469                     long refID = threadRef.uniqueID();
470                     if (ourID == refID) {
471                         return threadRef;
472                     }
473                 } catch (NumberFormatException JavaDoc e) {
474                 }
475             }
476         }
477         throw new ThreadNotFoundException(threadName);
478     }
479
480     public void outln(Object JavaDoc o) {
481         app.outln(o);
482     }
483
484     public DebuggerApp app() {
485         return app;
486     }
487
488     public String JavaDoc getRunningClass() {
489         return runningClass;
490     }
491
492     /**
493      * Returns a ReferenceType for <code>className</code>.
494      *
495      * @param className name of the class.
496      * @return ReferenceType for <code>className</code>, the
497      * returned value will not be null, but
498      * an exception may be thrown if things don't
499      * work out all that well.
500      */

501     public ReferenceType classByName(String JavaDoc className)
502         throws AmbiguousClassException,
503                InvalidClassException {
504         try {
505             Iterator iter = importPaths.iterator();
506             while (iter.hasNext()) {
507                 String JavaDoc fullName = iter.next() + "";
508                 if (!fullName.equals("")) {
509                     fullName += ".";
510                 }
511                 fullName += className;
512                 List classes = getVM().classesByName(fullName);
513                 if (classes.size() > 1) {
514                     throw new AmbiguousClassException(className, classes);
515                 } else if (classes.size() == 1) {
516                     ReferenceType refType = (ReferenceType) classes.get(0);
517                     return (ReferenceType) refType;
518                 }
519             }
520         } catch (NoVMException nvme) {
521         }
522         throw new InvalidClassException(className);
523     }
524
525     public void addImportPath(String JavaDoc importPath) {
526         importPaths.add(importPath);
527         filePaths.add(fileFromPath(importPath));
528     }
529
530     private String JavaDoc fileFromPath(String JavaDoc importPath) {
531         return importPath.replace('.', File.separatorChar);
532     }
533
534     public boolean removeImportPath(String JavaDoc importPath) {
535         filePaths.remove(fileFromPath(importPath));
536         return importPaths.remove(importPath);
537     }
538
539     public boolean addRequest(Request ra) {
540         if (!requestActions.contains(ra)) {
541             requestActions.add(ra);
542             fireRequestSetEvent(new RequestEvent(ra, true));
543             return true;
544         }
545         return false;
546     }
547
548     public EventRequest toggleBreakpoint(String JavaDoc source, int line) {
549         BreakpointRequestAction ba = null;
550         try {
551             ba = createSourceLineEvent(source, line, true);
552         } catch (DebuggerException de) {
553             return null;
554         }
555         if (ba == null) return null;
556         try {
557             if (!requestActions.contains(ba)) {
558                 return stopOnCommand(source, line);
559             } else {
560                 return clearOnCommand(source, line);
561             }
562         } catch (DebuggerException de) {}
563         return null;
564     }
565
566     public RequestAction removeRequest(Request ra) {
567         int i = 0;
568         RequestAction req = null;
569         while ((i = requestActions.indexOf(ra)) > -1) {
570             if (i != -1) {
571                 req = (RequestAction)requestActions.remove(i);
572                 SourceManager.SourceLine sl = null;
573                 if (req != null) {
574                     req.removeFromDebugger(this);
575                     sl = req.getSourceLine();
576                     fireRequestClearEvent(new RequestEvent(req, true));
577                 }
578                 if (sl != null) {
579                     sl.clear();
580                 }
581                 EventRequest er = req.getRequest();
582                 if (er != null && vm() != null) {
583                     vm().eventRequestManager().deleteEventRequest(er);
584                 }
585             }
586         }
587         return req;
588     }
589
590     public List getRequests() {
591         return requestActions;
592     }
593
594     private void wakeUpRequests() {
595         Iterator iter = getRequests().iterator();
596         try {
597             while (iter.hasNext()) {
598                 RequestAction request = (RequestAction)iter.next();
599                 if (request.isEnabled()) request.go();
600             }
601         } catch (DebuggerException de) {
602         }
603     }
604
605     public String JavaDoc help() {
606         String JavaDoc s = "** command list **\n";
607         s += "run [class [args]] -- start execution of application's main class\n";
608         s += "\n";
609         s += "threads [threadgroup] -- list threads\n";
610         s += "thread <thread id> -- set default thread\n";
611         s += "suspend [thread id(s)] -- suspend threads (default: all)\n";
612         s += "resume [thread id(s)] -- resume threads (default: all)\n";
613         s += "where [thread id] | all -- dump a thread's stack\n";
614         s += "wherei [thread id] | all -- dump a thread's stack, with pc info\n";
615         s += "up [n frames] -- move up a thread's stack\n";
616         s += "down [n frames] -- move down a thread's stack\n";
617         s += "kill <thread> <expr> -- kill a thread with the given exception object\n";
618         s += "interrupt <thread> -- interrupt a thread\n";
619         s += "\n";
620         s += "print <expr> -- print value of expression\n";
621         s += "dump <expr> -- print all object information\n";
622         s += "eval <expr> -- evaluate expression (same as print)\n";
623         s += "set <lvalue> = <expr> -- assign new value to field/variable/array element\n";
624         s += "locals -- print all local variables in current stack frame\n";
625         s += "\n";
626         s += "classes -- list currently known classes\n";
627         s += "class <class id> -- show details of named class\n";
628         s += "methods <class id> -- list a class's methods\n";
629         s += "fields <class id> -- list a class's fields\n";
630         s += "\n";
631         s += "threadgroups -- list threadgroups\n";
632         s += "threadgroup <name> -- set current threadgroup\n";
633         s += "\n";
634         s += "stop in <class id>.<method>[(argument_type,...)]\n";
635         s += " -- set a breakpoint in a method\n";
636         s += "stop at <class id>:<line> -- set a breakpoint at a line\n";
637         s += "clear <class id>.<method>[(argument_type,...)]\n";
638         s += " -- clear a breakpoint in a method\n";
639         s += "clear <class id>:<line> -- clear a breakpoint at a line\n";
640         s += "clear -- list breakpoints\n";
641         s += "catch <class id> -- break when specified exception thrown\n";
642         s += "ignore <class id> -- cancel 'catch' for the specified exception\n";
643         s += "watch [access|all] <class id>.<field name>\n";
644         s += " -- watch access/modifications to a field\n";
645         s += "unwatch [access|all] <class id>.<field name>\n";
646         s += " -- discontinue watching access/modifications to a field\n";
647         s += "trace methods [thread] -- trace method entry and exit\n";
648         s += "untrace methods [thread] -- stop tracing method entry and exit\n";
649         s += "step -- execute current line\n";
650         s += "step up -- execute until the current method returns to its caller\n";
651         s += "stepi -- execute current instruction\n";
652         s += "next -- step one line (step OVER calls)\n";
653         s += "cont -- continue execution from breakpoint\n";
654         s += "\n";
655         s += "list [line number|method] -- print source code\n";
656         s += "use (or sourcepath) [source file path]\n";
657         s += " -- display or change the source path\n";
658         s += "exclude [class id ... | \"none\"]\n";
659         s += " -- do not report step or method events for specified classes\n";
660         s += "classpath -- print classpath info from target VM\n";
661         s += "\n";
662         s += "monitor <command> -- execute command each time the program stops\n";
663         s += "monitor -- list monitors\n";
664         s += "unmonitor <monitor#> -- delete a monitor\n";
665         s += "read <filename> -- read and execute a command file\n";
666         s += "\n";
667         s += "lock <expr> -- print lock info for an object\n";
668         s += "threadlocks [thread id] -- print lock info for a thread\n";
669         s += "\n";
670         s += "disablegc <expr> -- prevent garbage collection of an object\n";
671         s += "enablegc <expr> -- permit garbage collection of an object\n";
672         s += "\n";
673         s += "!! -- repeat last command\n";
674         s += "<n> <command> -- repeat command n times\n";
675         s += "help (or ?) -- list commands\n";
676         s += "version -- print version information\n";
677         s += "exit (or quit) -- exit debugger\n";
678         s += "workingdir <dir> -- set the user's workingdir to <dir>\n";
679         s += "\n";
680         s += "<class id>: full class name with package qualifiers or a\n";
681         s += "pattern with a leading or trailing wildcard ('*').\n";
682         s += "<thread id>: thread number as reported in the 'threads' command\n";
683         s += "<expr>: a Java(tm) Programming Language expression.\n";
684         s += "Most common syntax is supported.\n";
685         s += "\n";
686         s += "Startup commands can be placed in either \"ajdb.ini\" or \".ajdbrc\"\n";
687         s += "in user.home or user.dir\n";
688         return s;
689     }
690
691     /****************************** Empty Mapping ******************************/
692
693     public String JavaDoc sourceName(Location loc) throws AbsentInformationException {
694         return loc.sourceName();
695     }
696
697     public int lineNumber(Location loc) {
698         return loc.lineNumber();
699     }
700
701     public long codeIndex(Location loc) {
702         return loc.codeIndex();
703     }
704
705     public String JavaDoc method(Location loc) {
706         return loc.method() + "";
707     }
708
709     public String JavaDoc name(Method method) {
710         return method.name();
711     }
712
713     /****************************** Misc. ******************************/
714
715     public void loadMainClass(Options options) {
716         //getVM(options.getJavaArgs(), options.getFullCommandLine());
717
getVM(options.getJavaArgs(), options.getClassName(), options.getCommandLine());
718     }
719
720     public List getRequest(RequestComparator rc) {
721         Vector v = new Vector();
722         Iterator iter = requestActions.iterator();
723         while (iter.hasNext()) {
724             Object JavaDoc o = iter.next();
725             if (rc.wantsRequest(o)) {
726                 v.add(o);
727             }
728         }
729         return v;
730     }
731
732     interface RequestComparator {
733         public boolean wantsRequest(Object JavaDoc o);
734     }
735
736     public List getBreakpointRequests() {
737         return getRequest(new RequestComparator() {
738                 public boolean wantsRequest(Object JavaDoc o) {
739                     return
740                         (o instanceof StopOnRequest) ||
741                         (o instanceof StopAtRequest) ||
742                         (o instanceof StopInRequest);
743             }});
744     }
745
746     public List getAccessWatchpointRequests() {
747         return getRequest(new RequestComparator() {
748                 public boolean wantsRequest(Object JavaDoc o) {
749                     return (o instanceof WatchAccessRequest);
750             }});
751     }
752
753     public List getModificationWatchpointRequests() {
754         return getRequest(new RequestComparator() {
755                 public boolean wantsRequest(Object JavaDoc o) {
756                     return (o instanceof WatchAllRequest);
757             }});
758     }
759
760     public List getExceptionRequests() {
761         return getRequest(new RequestComparator() {
762                 public boolean wantsRequest(Object JavaDoc o) {
763                     return (o instanceof CatchRequest);
764             }});
765     }
766
767     public void addMonitorRequest(MonitorRequest request) {
768         if (!monitorList.contains(request)) {
769             monitorList.add(request);
770             addStopListener(request);
771         }
772     }
773
774     public boolean removeMonitorRequest(MonitorRequest request) {
775         removeStopListener(request);
776         return monitorList.remove(request);
777     }
778
779     public MonitorRequest removeMonitorRequest(int number) {
780         MonitorRequest request = null;
781         Iterator iter = monitorList.iterator();
782         while (iter.hasNext()) {
783             request = (MonitorRequest) iter.next();
784             if (request.getNumber() == number) {
785                 monitorList.remove(request);
786                 break;
787             }
788             request = null;
789         }
790         if (request != null) {
791             removeStopListener(request);
792         }
793         return request;
794     }
795
796     public List getMonitorRequests() {
797         return monitorList;
798     }
799
800     public List getImportPaths() {
801         return importPaths;
802     }
803
804     public List getFilePaths() {
805         return filePaths;
806     }
807
808     public void addExclude(String JavaDoc className) {
809         if (!excludes.contains(className)) {
810             excludes.add(className);
811         }
812     }
813
814     public void addExcludesTo(StepRequest request) {
815         Iterator iter = excludes.iterator();
816         while (iter.hasNext()) {
817             request.addClassExclusionFilter(iter.next() + "");
818         }
819     }
820
821     public void addExcludesTo(MethodEntryRequest request) {
822         Iterator iter = excludes.iterator();
823         while (iter.hasNext()) {
824             request.addClassExclusionFilter(iter.next() + "");
825         }
826     }
827
828     public void addExcludesTo(MethodExitRequest request) {
829         Iterator iter = excludes.iterator();
830         while (iter.hasNext()) {
831             request.addClassExclusionFilter(iter.next() + "");
832         }
833     }
834
835     public void clearExcludes() {
836         excludes.clear();
837     }
838
839     public void shutDown() {
840         spinner.shutDown();
841         try {
842             // This may stop some of the memory exceptions being
843
// thrown under windoze
844
try {
845                 getVM().resume();
846             } catch (Throwable JavaDoc t) {
847             }
848             try {
849                 getVM().exit(0);
850             } catch (VMDisconnectedException vmde) {
851             }
852             try {
853                 getVM().dispose();
854             } catch (VMDisconnectedException vmde) {
855             }
856         } catch (NoVMException nvme) {
857         } finally {
858             vm = null;
859         }
860     }
861
862     public void exit() {
863         exit(true);
864     }
865
866     public void exit(boolean exit) {
867         shutDown();
868         if (exit && app.wantsToExit()) {
869             System.exit(0);
870         }
871     }
872
873     public void quit() {
874         //shutDown();
875
exit();
876         //System.exit(0);
877
}
878
879     public String JavaDoc version() {
880         return version + (vm() != null
881                             ? "\n" + vm().description()
882                             : "");
883     }
884
885     public void setStatus(Object JavaDoc o) {
886         status = o + "";
887     }
888
889     public String JavaDoc getStatus() {
890         return status;
891     }
892
893     public ThreadReference getDefaultThread() throws NoVMException {
894         return threads.getThread();
895     }
896
897     public ThreadGroupReference getDefaultThreadGroup() throws NoVMException {
898         return threads.getThreadGroup();
899     }
900
901     public StackFrame getDefaultFrame() throws NoVMException {
902         return threads.getStackFrame();
903     }
904
905     public ObjectReference getDefaultThisObject() throws NoVMException {
906         return getDefaultFrame().thisObject();
907     }
908
909     public int getFrame() {
910         return threads.getFrame();
911     }
912
913     public int getCurrentStoppedLine() {
914         return currentStoppedLine;
915     }
916
917     public String JavaDoc getCurrentStoppedSource() {
918         return currentStoppedSource;
919     }
920
921     public boolean isStopped(SourceManager.SourceLine sl) {
922         return
923             sl.getSourceName().equals(getCurrentStoppedSource()) &&
924             sl.getLineNumber() == getCurrentStoppedLine();
925     }
926
927     protected boolean isSame(ThreadReference threadRef, String JavaDoc threadName) {
928         if (threadRef.name().equals(threadName)) {
929             return true;
930         } else {
931             try {
932                 long ourID = Long.parseLong(threadName);
933                 long refID = threadRef.uniqueID();
934                 if (ourID == refID) {
935                     return true;
936                 }
937             } catch (NumberFormatException JavaDoc e) {
938             }
939         }
940         return false;
941     }
942
943     public ThreadReference getStoppedThread() throws NoVMException {
944         return threads.getStoppedThread();
945     }
946
947     public String JavaDoc getPrompt() {
948         return prompt;
949     }
950
951     private void setPrompt() {
952         try {
953             setPrompt(getDefaultThread(), getFrame());
954         } catch (NoVMException nvme) {
955         }
956     }
957
958     private void setPrompt(ThreadReference threadRef, int frame) {
959         this.prompt = threadRef.name() + "[" + (frame+1) + "]";
960         fireResetPrompt();
961     }
962
963     private void resetPrompt(boolean isRunning) {
964         this.isRunning = isRunning;
965         this.prompt = ">";
966     }
967
968     public boolean isRunning() {
969         return isRunning && (vm != null);
970     }
971
972     public void setRunning(boolean isRunning) {
973         this.isRunning = isRunning;
974     }
975
976     public boolean isAtBreakpoint() {
977         try {
978             return getDefaultThread().isAtBreakpoint();
979         } catch (Exception JavaDoc e) {
980         }
981         return false;
982     }
983
984     public boolean isExtra() {
985         return getOptions().isSet("extra");
986     }
987
988     public boolean isStopped() {
989         return isStopped;
990     }
991
992     private void stop() {
993         isStopped = true;
994     }
995
996     private void unstop() {
997         isStopped = false;
998     }
999
1000    public ThreadReference setDefaultThread(ThreadReference threadRef) {
1001        return threads.setThread(threadRef);
1002    }
1003
1004    public ThreadGroupReference setDefaultThreadGroup(ThreadGroupReference threadGroupRef) {
1005        return threads.setThreadGroup(threadGroupRef);
1006    }
1007
1008    public int setDefaultFrame(int frame) {
1009        return threads.setFrame(frame);
1010    }
1011
1012    public int setFrame(int frame) {
1013        return threads.setFrame(frame);
1014    }
1015
1016    public StackFrame up(int frames) {
1017        setFrame(getFrame() + frames);
1018        try {
1019            return getDefaultFrame();
1020        } catch (NoVMException e) {
1021        }
1022        return null;
1023    }
1024
1025    public StackFrame down(int frames) {
1026        setFrame(getFrame() - frames);
1027        try {
1028            return getDefaultFrame();
1029        } catch (NoVMException e) {
1030        }
1031        return null;
1032    }
1033
1034    public void use(String JavaDoc sourcePath) {
1035        sourceManager.setSourcePath(sourcePath);
1036        fireSourcePathChanged();
1037    }
1038
1039    public SourceManager getSourceManager() {
1040        return sourceManager;
1041    }
1042
1043    public String JavaDoc getSourcePath() {
1044        return sourceManager.getSourcePath();
1045    }
1046
1047    public void resumeAllThreads() throws NoVMException {
1048        Iterator iter = getVM().allThreads().iterator();
1049        while (iter.hasNext()) {
1050            ((ThreadReference) iter.next()).resume();
1051        }
1052    }
1053
1054    private ThreadReference setStoppedThread(ThreadReference threadRef) {
1055        return threads.setStoppedThread(threadRef);
1056    }
1057
1058    private void setDefaults(LocatableEvent le) {
1059        stop();
1060        ThreadReference threadRef = le.thread();
1061        setDefaultThread(threadRef);
1062        setStoppedThread(threadRef);
1063        setDefaultThreadGroup(threadRef.threadGroup());
1064        setDefaultFrame(0);
1065        setStopped(le);
1066    }
1067
1068    private void setStopped(LocatableEvent le) {
1069        currentStoppedLine = lineNumber(le.location());
1070        try {
1071            currentStoppedSource = sourceName(le.location());
1072        } catch (AbsentInformationException aie) {
1073        }
1074    }
1075
1076    public void fatal(String JavaDoc str) {
1077        System.err.println("FATAL ERROR:");
1078        System.err.println(str);
1079        System.exit(1);
1080    }
1081
1082    public void error(String JavaDoc str) {
1083        System.err.println(str);
1084    }
1085
1086    public synchronized VirtualMachine getVM() throws NoVMException {
1087        if (vm == null) {
1088            throw new NoVMException();
1089        } else {
1090            return vm;
1091        }
1092    }
1093
1094    public synchronized VirtualMachine vm() {
1095        return vm;
1096    }
1097
1098    private VirtualMachine findVM(Options options) {
1099        //return findVM(options.getJavaArgs(), options.getCommandLine());
1100
return findVM(options.getJavaArgs(), options.getClassName(), options.getCommandLine());
1101    }
1102
1103    private VirtualMachine findVM(String JavaDoc vmArgs, String JavaDoc className, String JavaDoc commandLine) {
1104        return findLaunchingVM(vmArgs, className, commandLine);
1105    }
1106
1107    private VirtualMachine findLaunchingVM(String JavaDoc vmArgs, String JavaDoc className, String JavaDoc commandLine) {
1108        return findLaunchingVM(vmArgs, className, commandLine, true);
1109    }
1110
1111    private VirtualMachine findLaunchingVM(String JavaDoc vmArgs, String JavaDoc className, String JavaDoc commandLine, boolean recurse) {
1112        Debug.debug("------------- findLaunchingVM -----------");
1113        Debug.debug("commandLine=" + commandLine);
1114        Debug.debug("vmArgs=" + vmArgs);
1115        if (vmArgs == null) vmArgs = "";
1116        if (commandLine == null) commandLine = "";
1117        final LaunchingConnector con = (LaunchingConnector) findConnector("");
1118        final Map args = con.defaultArguments();
1119        //((Connector.Argument) args.get("main")).setValue(commandLine);
1120
((Connector.Argument) args.get("main")).setValue((className + " " + commandLine).trim());
1121        ((Connector.Argument) args.get("options")).setValue(vmArgs);
1122        Debug.debug("args=" + args);
1123        Debug.debug("con=" + con);
1124        Debug.debug("--------------------------------------------------");
1125        vm = null;
1126        try {
1127            Debug.debug("before: vm=" + vm);
1128            //if (true) return vm;
1129
if (false) throw new Exception JavaDoc("foo");
1130            vm = con.launch(args);
1131            Debug.debug("after: vm=" + vm);
1132        } catch (VMDisconnectedException vmde) {
1133            app.handleInternalException(vmde);
1134        } catch (VMStartException vmse) {
1135            if (!recurse) {
1136                app.handleInternalException(vmse);
1137            }
1138        } catch (IllegalConnectorArgumentsException icae) {
1139            if (!recurse) {
1140                app.handleInternalException(icae);
1141            }
1142        } catch (Exception JavaDoc e) {
1143            if (!recurse) {
1144                app.handleInternalException(e);
1145            }
1146        }
1147        Debug.debug("Done vm=" + vm);
1148
1149        if (vm == null) {
1150            if (recurse) {
1151                Debug.debug("Recursing...");
1152                String JavaDoc newCommandLine = findClassName(commandLine);
1153                if (newCommandLine == null) {
1154                    app.handleInternalException
1155                        (new Exception JavaDoc("No class specified on the command line: " + commandLine));
1156                } else {
1157                    app.outln("Cannot support the arguments: " + args);
1158                    return findLaunchingVM(vmArgs, className, newCommandLine, false);
1159                }
1160            } else {
1161                app.handleInternalException(new Exception JavaDoc("VM is null"));
1162            }
1163            return vm;
1164        }
1165
1166// Process process = vm.process();
1167
// if (process != null) {
1168
// redirect(process.getErrorStream(), "error-dumper");
1169
// redirect(process.getInputStream(), "input-dumper");
1170
// }
1171
return vm;
1172    }
1173
1174    private Connector findConnector(String JavaDoc name) {
1175        Debug.debug(this, "Looking for connector " + name);
1176        Iterator iter = Bootstrap.virtualMachineManager().allConnectors().iterator();
1177        while (iter.hasNext()) {
1178            Connector con = (Connector) iter.next();
1179            if (con.name().equals(name)) {
1180                return con;
1181            }
1182        }
1183        return Bootstrap.virtualMachineManager().defaultConnector();
1184    }
1185
1186    private String JavaDoc findClassName(String JavaDoc commandLine) {
1187        StringTokenizer tok = new StringTokenizer(commandLine);
1188        while (tok.hasMoreTokens()) {
1189            String JavaDoc token = tok.nextToken();
1190            if (!tok.hasMoreTokens() && !token.startsWith("-")) {
1191                return token;
1192            }
1193        }
1194        return null;
1195    }
1196
1197    private void redirect(final InputStream in, final String JavaDoc name) {
1198        new Thread JavaDoc(name) {
1199                public void run() {
1200                    dump(in);
1201                }
1202            }.start();
1203    }
1204
1205    private void dump(InputStream stream) {
1206        PrintStream out = app.getOutputStream();
1207        BufferedReader in = new BufferedReader(new InputStreamReader(stream));
1208        String JavaDoc line;
1209        try {
1210            while ((line = in.readLine()) != null) {
1211                out.println(line);
1212            }
1213        } catch (IOException ioe) {
1214            //TODO
1215
ioe.printStackTrace(System.err);
1216        }
1217    }
1218
1219    protected void readStartupFiles() {
1220        try {
1221            readCommand("ajdb.ini");
1222            readCommand(".ajdbrc");
1223        } catch (NoVMException nvme) {
1224        } catch (DebuggerException de) {
1225        }
1226    }
1227
1228
1229     /****************************** Execution *****************************/
1230
1231     public Object JavaDoc execute(String JavaDoc line) {
1232         Object JavaDoc o = null;
1233         db("execute line=" + line);
1234         try {
1235             o = parser.parse(line);
1236         } catch (Exception JavaDoc e) {
1237             handle(e);
1238         }
1239        return o;
1240    }
1241
1242    public void handle(Exception JavaDoc t) {
1243        if (t instanceof ParseException) {
1244            app.handleParseException((ParseException)t);
1245        } else if (t instanceof NoVMException) {
1246            app.handleNoVMException((NoVMException)t);
1247        } else if (t instanceof DebuggerException) {
1248            app.handleDebuggerException((DebuggerException)t);
1249        } else if (t instanceof VMDisconnectedException) {
1250            app.handleVMDisconnectedException((VMDisconnectedException)t);
1251        } else {
1252            app.handleInternalException(t);
1253        }
1254    }
1255
1256    public Object JavaDoc run(String JavaDoc mainClass, String JavaDoc[] args)
1257        throws NoVMException,
1258               DebuggerException {
1259        String JavaDoc str = "";
1260        int N = args.length;
1261        for (int i = 0; i < N; i++) {
1262            str += args[i] + (i<N-1 ? " " : "");
1263        }
1264        return runCommand(mainClass, str);
1265    }
1266
1267    public Object JavaDoc run(String JavaDoc mainClass)
1268        throws NoVMException,
1269               DebuggerException {
1270        return run(mainClass, new String JavaDoc[0]);
1271    }
1272
1273    public Object JavaDoc executeCommand(String JavaDoc line) {
1274        return execute(line);
1275    }
1276
1277    /************************** Creating breakpoints **********************/
1278
1279    public ClassLineBreakpointRequestAction createClassLineEvent(String JavaDoc className,
1280                                                                 int line,
1281                                                                 boolean stop)
1282        throws DebuggerException {
1283        return createClassLineEvent(className, line, stop, null);
1284    }
1285    
1286    public ClassLineBreakpointRequestAction
1287        createClassLineEvent(String JavaDoc className,
1288                             int line,
1289                             boolean stop,
1290                             String JavaDoc text)
1291        throws DebuggerException {
1292        ClassLineBreakpointRequestAction a = null;
1293        if (stop) {
1294            a = new StopAtRequest(this, className, line);
1295            a.setText(text);
1296        } else {
1297            a = new ClearAtRequest(this, className, line);
1298            a.setText(text);
1299        }
1300        return a;
1301    }
1302
1303    public SourceLineBreakpointRequestAction
1304        createSourceLineEvent(String JavaDoc sourceName,
1305                              int line,
1306                              boolean stop)
1307        throws DebuggerException {
1308        return createSourceLineEvent(sourceName, line, stop, null);
1309    }
1310
1311    public SourceLineBreakpointRequestAction
1312        createSourceLineEvent(String JavaDoc sourceName,
1313                              int line,
1314                              boolean stop,
1315                              String JavaDoc text)
1316        throws DebuggerException {
1317        SourceLineBreakpointRequestAction a = null;
1318        if (stop) {
1319            a = new StopOnRequest(this, sourceName, line);
1320            a.setText(text);
1321        } else {
1322            a = new ClearOnRequest(this, sourceName, line);
1323            a.setText(text);
1324        }
1325        return a;
1326    }
1327
1328    /****************************** Commands ******************************/
1329
1330    public Object JavaDoc runCommand() {
1331        try {
1332            return runCommand(getOptions());
1333        } catch (DebuggerException de) {
1334        }
1335        return null;
1336    }
1337
1338    public Object JavaDoc runCommand(Options opts)
1339        throws NoVMException, DebuggerException {
1340        String JavaDoc className = opts.getClassName();
1341        String JavaDoc javaArgs = opts.getJavaArgs();
1342        String JavaDoc commandLine = opts.getCommandLine();
1343        return runCommand(className, javaArgs, commandLine,
1344                          false, VirtualMachine.TRACE_NONE);
1345    }
1346
1347    public Object JavaDoc runCommand(String JavaDoc className, String JavaDoc exArgs)
1348        throws NoVMException, DebuggerException {
1349        return runCommand(className, "", exArgs, false,
1350                          VirtualMachine.TRACE_NONE);
1351    }
1352    
1353    public Object JavaDoc runCommand(String JavaDoc className, String JavaDoc vmArgs, String JavaDoc exArgs,
1354                             boolean isSuspended, int debugTraceMode)
1355        throws NoVMException, DebuggerException {
1356        if (!getOptions().isSet("extra") &&
1357            isRunning() &&
1358            !app.canRestart()) {
1359            app.outln("VM already running. " +
1360                      "Use 'cont' to continue after events.");
1361            return null;
1362        }
1363        unstop();
1364        this.runningClass = className;
1365        if (!Modes.isJBuilder() && !Modes.isForte()) {
1366            app.outln("run " + className);
1367        } else {
1368            app.outln("connect " + className);
1369        }
1370        go(className, vmArgs, exArgs, isSuspended, debugTraceMode);
1371        return null;
1372    }
1373
1374    public EventRequest clearAtCommand(String JavaDoc className, int line)
1375        throws NoVMException, DebuggerException {
1376        EventRequest er = (EventRequest)
1377            (createClassLineEvent(className, line, false).go());
1378        app.clearAtCommand(className, line, er);
1379        return er;
1380    }
1381
1382    public EventRequest clearInCommand(String JavaDoc className, String JavaDoc methodProto)
1383        throws NoVMException, DebuggerException {
1384        EventRequest er = (EventRequest)
1385            (new ClearInRequest(this, className, methodProto).go());
1386        app.clearInCommand(className, methodProto, er);
1387        return er;
1388    }
1389
1390    public EventRequest clearOnCommand(String JavaDoc sourceName, int line)
1391        throws NoVMException, DebuggerException {
1392        EventRequest er = (EventRequest)
1393            (createSourceLineEvent(sourceName, line, false).go());
1394        app.clearOnCommand(sourceName, line, er);
1395        return er;
1396    }
1397
1398    public List clearCommand()
1399        throws NoVMException, DebuggerException {
1400        List breakpoints = (List) (new ClearListRequest(this).go());
1401        app.clearCommand(breakpoints);
1402        return breakpoints;
1403    }
1404
1405    public List clearAllCommand()
1406        throws NoVMException, DebuggerException {
1407        List breakpoints = (List) (new ClearAllRequest(this).go());
1408        app.clearAllCommand(breakpoints);
1409        return breakpoints;
1410    }
1411
1412    public EventRequest stopAtCommand(String JavaDoc className, int line)
1413        throws NoVMException, DebuggerException {
1414        return stopAtCommand(className, line, null);
1415    }
1416
1417    public EventRequest stopAtCommand(String JavaDoc className, int line, String JavaDoc text)
1418        throws NoVMException, DebuggerException {
1419        EventRequest er = (EventRequest)
1420            (createClassLineEvent(className, line, true, text).go());
1421        app.stopAtCommand(className, line, er);
1422        return er;
1423    }
1424
1425    public EventRequest stopInCommand(String JavaDoc className, String JavaDoc methodProto)
1426        throws NoVMException, DebuggerException {
1427        return stopInCommand(className, methodProto, null);
1428    }
1429
1430    public EventRequest stopInCommand(String JavaDoc className, String JavaDoc methodProto, String JavaDoc text)
1431        throws NoVMException, DebuggerException {
1432        EventRequest er = (EventRequest)
1433            (new StopInRequest(this, className, methodProto).setText(text).go());
1434        app.stopInCommand(className, methodProto, er);
1435        return er;
1436    }
1437
1438    public EventRequest stopOnCommand(String JavaDoc sourceName, int line)
1439        throws NoVMException, DebuggerException {
1440        return stopOnCommand(sourceName, line, null);
1441    }
1442
1443    public EventRequest stopOnCommand(String JavaDoc sourceName, int line, String JavaDoc text)
1444        throws NoVMException, DebuggerException {
1445        EventRequest er = (EventRequest)
1446            (createSourceLineEvent(sourceName, line, true, text).go());
1447        app.stopOnCommand(sourceName, line, er);
1448        return er;
1449    }
1450
1451    public List stopCommand()
1452        throws NoVMException, DebuggerException {
1453        List breakpoints = (List) (new StopListRequest(this).go());
1454        app.stopCommand(breakpoints);
1455        return breakpoints;
1456    }
1457
1458    public Object JavaDoc contCommand()
1459        throws NoVMException, DebuggerException {
1460        new ContRequest(this).go();
1461        fireStartEvent();
1462        app.contCommand();
1463        return null;
1464    }
1465
1466    public List threadsCommand(String JavaDoc threadGroupName)
1467        throws NoVMException, DebuggerException {
1468        List threads = (List) (new ThreadsRequest(this, threadGroupName).go());
1469        app.threadsCommand(threadGroupName, threads);
1470        return threads;
1471    }
1472
1473    public List threadGroupsCommand()
1474        throws NoVMException, DebuggerException {
1475        List threadGroups = (List) (new ThreadGroupsRequest(this).go());
1476        app.threadGroupsCommand(threadGroups);
1477        return threadGroups;
1478    }
1479
1480    public List fieldsCommand(String JavaDoc className)
1481        throws NoVMException, DebuggerException {
1482        List fields = (List) (new FieldsRequest(this, className).go());
1483        app.fieldsCommand(className, fields);
1484        return fields;
1485    }
1486
1487    public List methodsCommand(String JavaDoc className)
1488        throws NoVMException, DebuggerException {
1489        List methods = (List) (new MethodsRequest(this, className).go());
1490        app.methodsCommand(className, methods);
1491        return methods;
1492    }
1493
1494    public List classesCommand()
1495        throws NoVMException, DebuggerException {
1496        List classes = (List) (new ClassesRequest(this).go());
1497        app.classesCommand(classes);
1498        return classes;
1499    }
1500
1501    public ReferenceType classCommand(String JavaDoc className)
1502        throws NoVMException, DebuggerException {
1503        ReferenceType refType = (ReferenceType)
1504            (new ClassRequest(this, className).go());
1505        app.classCommand(className, refType);
1506        return refType;
1507    }
1508
1509    public ThreadReference threadCommand(String JavaDoc threadName)
1510        throws NoVMException, DebuggerException {
1511        ThreadReference threadRef =
1512            setDefaultThread((ThreadReference)
1513                             (new ThreadRequest(this, threadName).go()));
1514        app.threadCommand(threadName, threadRef);
1515        return threadRef;
1516    }
1517
1518    public ThreadGroupReference threadGroupCommand(String JavaDoc threadGroupName)
1519        throws NoVMException, DebuggerException {
1520        ThreadGroupReference threadGroupRef =
1521            setDefaultThreadGroup((ThreadGroupReference)
1522                                  (new ThreadGroupRequest
1523                                      (this, threadGroupName).go()));
1524        app.threadGroupCommand(threadGroupName, threadGroupRef);
1525        return threadGroupRef;
1526    }
1527
1528    public List suspendCommand()
1529        throws NoVMException, DebuggerException {
1530        List threads = (List) suspendCommand(new Vector());
1531        fireStopEvent();
1532        return threads;
1533    }
1534
1535    public List suspendCommand(List threadNames)
1536        throws NoVMException, DebuggerException {
1537        List threads = (List) (new SuspendRequest(this, threadNames).go());
1538        fireStopEvent();
1539        app.suspendCommand(threadNames, threads);
1540        return threads;
1541    }
1542
1543    public List resumeCommand(List threadNames)
1544        throws NoVMException, DebuggerException {
1545        List threads = (List) (new ResumeRequest(this, threadNames).go());
1546        fireStartEvent();
1547        app.resumeCommand(threadNames, threads);
1548        return threads;
1549    }
1550
1551    public List resumeCommand()
1552        throws NoVMException, DebuggerException {
1553        List threads = resumeCommand(new Vector());
1554        fireStartEvent();
1555        return threads;
1556    }
1557
1558    public List whereCommand(String JavaDoc threadName)
1559        throws NoVMException, DebuggerException {
1560        List frames = (List) (new WhereRequest(this, threadName).go());
1561        app.whereCommand(threadName, frames);
1562        return frames;
1563    }
1564
1565    public List localsCommand()
1566        throws NoVMException, DebuggerException {
1567        List locals = (List) (new LocalsRequest(this).go());
1568        app.localsCommand(locals);
1569        return locals;
1570    }
1571
1572    public ThreadReference interruptCommand(String JavaDoc threadName)
1573        throws NoVMException, DebuggerException {
1574        ThreadReference threadRef = (ThreadReference)
1575            (new InterruptRequest(this, threadName).go());
1576        fireStopEvent();
1577        app.interruptCommand(threadName, threadRef);
1578        return threadRef;
1579    }
1580
1581    public StackFrame upCommand(int frames)
1582        throws NoVMException, DebuggerException {
1583        StackFrame frame = (StackFrame) (new UpRequest(this, frames).go());
1584        app.upCommand(frames, frame);
1585        return frame;
1586
1587    }
1588
1589    public StackFrame downCommand(int frames)
1590        throws NoVMException, DebuggerException {
1591        StackFrame frame = (StackFrame) (new DownRequest(this, frames).go());
1592        app.downCommand(frames, frame);
1593        return frame;
1594    }
1595
1596    public StepRequest stepCommand()
1597        throws NoVMException, DebuggerException {
1598        unstop();
1599        StepRequest request = (StepRequest) (new StepIntoRequest(this).go());
1600        fireStartEvent();
1601        app.stepCommand(request);
1602        return request;
1603    }
1604
1605    public StepRequest stepUpCommand()
1606        throws NoVMException, DebuggerException {
1607        unstop();
1608        StepRequest request = (StepRequest) (new StepUpRequest(this).go());
1609        fireStartEvent();
1610        app.stepUpCommand(request);
1611        return request;
1612    }
1613
1614    public StepRequest stepiCommand()
1615        throws NoVMException, DebuggerException {
1616        unstop();
1617        StepRequest request = (StepRequest) (new StepIRequest(this).go());
1618        fireStartEvent();
1619        app.stepiCommand(request);
1620        return request;
1621    }
1622
1623    public StepRequest nextCommand()
1624        throws NoVMException, DebuggerException {
1625        unstop();
1626        StepRequest request = (StepRequest) (new NextRequest(this).go());
1627        fireStartEvent();
1628        app.nextCommand(request);
1629        return request;
1630    }
1631
1632    public Value printCommand(Object JavaDoc valueRep)
1633        throws NoVMException, DebuggerException {
1634        Value value = (Value) (new PrintRequest(this, valueRep).go());
1635        app.printCommand(valueRep, value);
1636        return value;
1637    }
1638
1639    public Value dumpCommand(Object JavaDoc valueRep)
1640        throws NoVMException, DebuggerException {
1641        Value value = (Value) (new DumpRequest(this, valueRep).go());
1642        app.dumpCommand(valueRep, value);
1643        return value;
1644    }
1645
1646    public Value evalCommand(Object JavaDoc valueRep)
1647        throws NoVMException, DebuggerException {
1648        Value value = (Value) (new EvalRequest(this, valueRep).go());
1649        app.evalCommand(valueRep, value);
1650        return value;
1651    }
1652
1653    public Value setCommand(Object JavaDoc lvalue, Object JavaDoc rvalue)
1654        throws NoVMException, DebuggerException {
1655        Value oldValue = (Value) (new DumpRequest(this, lvalue).go());
1656        Value newValue = (Value) (new SetRequest(this, lvalue, rvalue).go());
1657        app.setCommand(lvalue, rvalue, oldValue, newValue);
1658        return newValue;
1659    }
1660
1661    public ClasspathRequest.Package classpathCommand()
1662        throws NoVMException, DebuggerException {
1663        ClasspathRequest.Package pkg = (ClasspathRequest.Package)
1664            (new ClasspathRequest(this).go());
1665        app.classpathCommand(pkg.baseDirectory, pkg.paths);
1666        return pkg;
1667    }
1668
1669    public LockInformation lockCommand(Object JavaDoc valueRep)
1670        throws NoVMException, DebuggerException {
1671        LockInformation lockInfo = (LockInformation)
1672            (new LockRequest(this, valueRep).go());
1673        app.lockCommand(valueRep, lockInfo);
1674        return lockInfo;
1675    }
1676
1677    public ThreadLockInformation threadlocksCommand(String JavaDoc threadName)
1678        throws NoVMException, DebuggerException {
1679        ThreadLockInformation threadLockInfo =
1680            (ThreadLockInformation)
1681            (new ThreadLocksRequest(this, threadName).go());
1682        app.threadlocksCommand(threadName, threadLockInfo);
1683        return threadLockInfo;
1684    }
1685
1686    public WatchpointRequest watchAccessCommand(String JavaDoc className,
1687                                                String JavaDoc fieldName)
1688        throws NoVMException, DebuggerException {
1689        return watchAccessCommand(className, fieldName, null);
1690    }
1691
1692    public WatchpointRequest watchAccessCommand(String JavaDoc className,
1693                                                String JavaDoc fieldName,
1694                                                String JavaDoc text)
1695        throws NoVMException, DebuggerException {
1696        WatchpointRequest request =
1697            (WatchpointRequest) (new WatchAccessRequest(this, className, fieldName).setText(text).go());
1698        app.watchAccessCommand(className, fieldName, request);
1699        return request;
1700    }
1701
1702    public WatchpointRequest watchAllCommand(String JavaDoc className,
1703                                             String JavaDoc fieldName)
1704        throws NoVMException, DebuggerException {
1705        return watchAllCommand(className, fieldName, null);
1706    }
1707
1708    public WatchpointRequest watchAllCommand(String JavaDoc className,
1709                                             String JavaDoc fieldName,
1710                                             String JavaDoc text)
1711        throws NoVMException, DebuggerException {
1712        WatchpointRequest request =
1713            (WatchpointRequest)
1714            (new WatchAllRequest(this, className, fieldName).setText(text).go());
1715        app.watchAllCommand(className, fieldName, request);
1716        return request;
1717    }
1718
1719    public WatchpointRequest unwatchAccessCommand(String JavaDoc className, String JavaDoc fieldName)
1720        throws NoVMException, DebuggerException {
1721        WatchpointRequest request =
1722            (WatchpointRequest)
1723            (new UnwatchAccessRequest(this, className, fieldName).go());
1724        app.unwatchAccessCommand(className, fieldName, request);
1725        return request;
1726    }
1727
1728    public WatchpointRequest unwatchAllCommand(String JavaDoc className, String JavaDoc fieldName)
1729        throws NoVMException, DebuggerException {
1730        WatchpointRequest request =
1731            (WatchpointRequest)
1732            (new UnwatchAllRequest(this, className, fieldName).go());
1733        app.unwatchAllCommand(className, fieldName, request);
1734        return request;
1735    }
1736
1737    public ExceptionRequest catchCommand(String JavaDoc className)
1738        throws NoVMException, DebuggerException {
1739        return catchCommand(className, null);
1740    }
1741
1742    public ExceptionRequest catchCommand(String JavaDoc className, String JavaDoc text)
1743        throws NoVMException, DebuggerException {
1744        ExceptionRequest request = (ExceptionRequest)
1745            (new CatchRequest(this, className).setText(text).go());
1746        app.catchCommand(className, request);
1747        return request;
1748    }
1749
1750    public ExceptionRequest ignoreCommand(String JavaDoc className)
1751        throws NoVMException, DebuggerException {
1752        ExceptionRequest request = (ExceptionRequest)
1753            (new IgnoreRequest(this, className).go());
1754        app.ignoreCommand(className, request);
1755        return request;
1756    }
1757
1758    public TraceMethodsRequest.EntryExitPair
1759        traceMethodsCommand(String JavaDoc threadName)
1760        throws NoVMException, DebuggerException {
1761        TraceMethodsRequest.EntryExitPair pair =
1762            (TraceMethodsRequest.EntryExitPair)
1763            (new TraceMethodsRequest(this, threadName).go());
1764        app.traceMethodsCommand(threadName, pair);
1765        return pair;
1766    }
1767
1768    public UntraceMethodsRequest.EntryExitPair
1769        untraceMethodsCommand(String JavaDoc threadName)
1770        throws NoVMException, DebuggerException {
1771        UntraceMethodsRequest.EntryExitPair pair =
1772            (UntraceMethodsRequest.EntryExitPair)
1773            (new UntraceMethodsRequest(this, threadName).go());
1774        app.untraceMethodsCommand(threadName, pair);
1775        return pair;
1776    }
1777
1778    public List excludeCommand(List classNames)
1779        throws NoVMException, DebuggerException {
1780        List classes = (List) (new ExcludeRequest(this, classNames).go());
1781        app.excludeCommand(classNames, classes);
1782        return classes;
1783    }
1784
1785    public Object JavaDoc quitCommand()
1786        throws NoVMException, DebuggerException {
1787        fireStopEvent();
1788        app.quitCommand();
1789        return (new QuitRequest(this).go());
1790    }
1791
1792    public Object JavaDoc helpCommand()
1793        throws NoVMException, DebuggerException {
1794        String JavaDoc helpString = (String JavaDoc) (new HelpRequest(this).go());
1795        app.helpCommand(helpString);
1796        return helpString;
1797    }
1798
1799    public Object JavaDoc versionCommand()
1800        throws NoVMException, DebuggerException {
1801        Object JavaDoc version = (new VersionRequest(this).go());
1802        app.versionCommand(version);
1803        return version;
1804    }
1805
1806    public ThreadReference killCommand(String JavaDoc threadName,
1807                                       String JavaDoc valueRep)
1808        throws NoVMException, DebuggerException {
1809        ThreadReference threadRef = (ThreadReference)
1810            (new KillRequest(this, threadName, valueRep).go());
1811        app.killCommand(threadName, valueRep, threadRef);
1812        return threadRef;
1813    }
1814
1815    public String JavaDoc useCommand(String JavaDoc sourcePath)
1816        throws NoVMException, DebuggerException {
1817        String JavaDoc newSourcePath = (String JavaDoc)
1818            (new UseRequest(this, sourcePath).go());
1819        app.useCommand(sourcePath, newSourcePath);
1820        return newSourcePath;
1821    }
1822
1823    public String JavaDoc workingdirCommand(String JavaDoc workingdirPath)
1824        throws NoVMException, DebuggerException {
1825        String JavaDoc newWorkingdirPath = (String JavaDoc)
1826            (new WorkingdirRequest(this, workingdirPath).go());
1827        app.workingdirCommand(workingdirPath, newWorkingdirPath);
1828        return newWorkingdirPath;
1829    }
1830
1831    public List listCommand()
1832        throws NoVMException, DebuggerException {
1833        ListRequest.SourceAndLines sal =
1834            (ListRequest.SourceAndLines) (new ListRequest(this).go());
1835        app.listCommand(sal.getSourceName(), sal.getLines());
1836        return sal.getLines();
1837    }
1838
1839    public List listCommand(String JavaDoc sourceName)
1840        throws NoVMException, DebuggerException {
1841        ListRequest.SourceAndLines sal =
1842            (ListRequest.SourceAndLines)
1843            (new ListRequest(this, sourceName).go());
1844        app.listCommand(sal.getSourceName(), sal.getLines());
1845        return sal.getLines();
1846    }
1847
1848    public SourceManager.SourceLine listCommand(String JavaDoc sourceName, int lineNumber)
1849        throws NoVMException, DebuggerException {
1850        ListRequest.SourceAndLines sal =
1851            (ListRequest.SourceAndLines)
1852            (new ListRequest(this, sourceName, lineNumber).go());
1853        SourceManager.SourceLine sl = (SourceManager.SourceLine)
1854            sal.getLines().get(0);
1855        app.listCommand(sal.getSourceName(), sl.lineNumber, sl);
1856        return sl;
1857    }
1858
1859    public List listCommand(String JavaDoc sourceName, int startLine, int endLine)
1860        throws NoVMException, DebuggerException {
1861        ListRequest.SourceAndLines sal =
1862            (ListRequest.SourceAndLines)
1863            (new ListRequest(this, sourceName, startLine, endLine).go());
1864        app.listCommand(sal.getSourceName(), startLine, endLine, sal.getLines());
1865        return sal.getLines();
1866    }
1867
1868    public String JavaDoc monitorCommand(String JavaDoc command)
1869        throws NoVMException, DebuggerException {
1870        String JavaDoc result = (String JavaDoc) (new MonitorRequest(this, command,
1871                                                     (monitors++)).go());
1872        app.monitorCommand(command, result);
1873        return result;
1874    }
1875
1876    public List monitorCommand()
1877        throws NoVMException, DebuggerException {
1878        List monitors = (List) (new MonitorListRequest(this).go());
1879        app.monitorCommand(monitors);
1880        return monitors;
1881    }
1882
1883    public MonitorRequest unmonitorCommand(int number)
1884        throws NoVMException, DebuggerException {
1885        MonitorRequest request = (MonitorRequest)
1886            (new UnmonitorRequest(this, number).go());
1887        app.unmonitorCommand(number, request);
1888        return request;
1889    }
1890
1891    public List readCommand(String JavaDoc sourceName)
1892        throws NoVMException, DebuggerException {
1893        return readCommand(sourceName, false);
1894    }
1895
1896    public List readCommand(String JavaDoc sourceName, boolean silent)
1897        throws NoVMException, DebuggerException {
1898        List commands = (List) (new ReadRequest(this, sourceName, silent).go());
1899        app.readCommand(sourceName, commands);
1900        return commands;
1901    }
1902
1903    public VirtualMachine connectCommand()
1904        throws NoVMException, DebuggerException {
1905        return connectCommand("", "", "");
1906    }
1907    
1908    public VirtualMachine connectCommand(String JavaDoc vmArgs,
1909                                         String JavaDoc className,
1910                                         String JavaDoc commandLine)
1911        throws NoVMException, DebuggerException {
1912        try {
1913            startUpVM((VirtualMachine)
1914                      (new ConnectRequest(this, vmArgs, className,
1915                                          commandLine).go()));
1916        } catch (ClassNotFoundException JavaDoc cnfe) {
1917            handleClassNotFound(cnfe);
1918            return null;
1919        } catch (NoClassDefFoundError JavaDoc ncdfe) {
1920            handleClassNotFound(ncdfe);
1921            return null;
1922        }
1923        app.connectCommand(vm);
1924        return vm;
1925    }
1926
1927    //TODO: Implement the 'app' commands
1928

1929    public Object JavaDoc bangBangCommand(String JavaDoc lastCommand)
1930        throws NoVMException, DebuggerException {
1931        Object JavaDoc result = (new BangBangRequest(this, lastCommand).go());
1932        return result;
1933    }
1934
1935    public Object JavaDoc importCommand(String JavaDoc importPath)
1936        throws NoVMException, DebuggerException {
1937        Object JavaDoc path = (new ImportRequest(this, importPath).go());
1938        return path;
1939    }
1940
1941    public Object JavaDoc deportCommand(String JavaDoc importPath)
1942        throws NoVMException, DebuggerException {
1943        Object JavaDoc path = (new DeportRequest(this, importPath).go());
1944        return path;
1945    }
1946
1947    public List viewCommand(String JavaDoc source)
1948        throws NoVMException, DebuggerException {
1949        ListRequest.SourceAndLines sal =
1950            (ListRequest.SourceAndLines) (new ViewRequest(this, source).go());
1951        app.listCommand(sal.getSourceName(), sal.getLines());
1952        return sal.getLines();
1953    }
1954
1955    public String JavaDoc tostringCommand()
1956        throws NoVMException, DebuggerException {
1957        String JavaDoc tostring = (String JavaDoc) (new TostringRequest(this).go());
1958        app.tostringCommand(tostring);
1959        return tostring;
1960    }
1961
1962    public File pwdCommand()
1963        throws NoVMException, DebuggerException {
1964        File pwd = (File)(new PwdRequest(this).go());
1965        app.pwdCommand(pwd);
1966        return pwd;
1967    }
1968
1969    public List lsCommand(String JavaDoc fileName)
1970        throws NoVMException, DebuggerException {
1971        List files = (List)(new LsRequest(this, fileName).go());
1972        app.lsCommand(fileName, files);
1973        return files;
1974    }
1975
1976    // end-commands
1977

1978
1979    protected VirtualMachine vm;
1980    public boolean handle(Event event) {
1981        if (event == null) return false;
1982        if (event instanceof AccessWatchpointEvent) {
1983            handleAccessWatchpointEvent((AccessWatchpointEvent) event);
1984            return true;
1985        } else if (event instanceof BreakpointEvent) {
1986            handleBreakpointEvent((BreakpointEvent) event);
1987            return false; ///true;
1988
} else if (event instanceof ClassPrepareEvent) {
1989            handleClassPrepareEvent((ClassPrepareEvent) event);
1990            return true;
1991        } else if (event instanceof ClassUnloadEvent) {
1992            handleClassUnloadEvent((ClassUnloadEvent) event);
1993            return true;
1994        } else if (event instanceof ExceptionEvent) {
1995            handleExceptionEvent((ExceptionEvent) event);
1996            return true;
1997        } else if (event instanceof MethodEntryEvent) {
1998            handleMethodEntryEvent((MethodEntryEvent) event);
1999            return true;
2000        } else if (event instanceof MethodExitEvent) {
2001            handleMethodExitEvent((MethodExitEvent) event);
2002            return true;
2003        } else if (event instanceof ModificationWatchpointEvent) {
2004            handleModificationWatchpointEvent((ModificationWatchpointEvent) event);
2005            return true;
2006        } else if (event instanceof StepEvent) {
2007            handleStepEvent((StepEvent) event);
2008            return false; //true;
2009
} else if (event instanceof ThreadDeathEvent) {
2010            handleThreadDeathEvent((ThreadDeathEvent) event);
2011            return true;
2012        } else if (event instanceof ThreadStartEvent) {
2013            handleThreadStartEvent((ThreadStartEvent) event);
2014            return true;
2015        } else if (event instanceof VMDeathEvent) {
2016            handleVMDeathEvent((VMDeathEvent) event);
2017            return false;
2018        } else if (event instanceof VMDisconnectEvent) {
2019            handleVMDisconnectEvent((VMDisconnectEvent) event);
2020            return false;
2021        } else if (event instanceof VMStartEvent) {
2022            handleVMStartEvent((VMStartEvent) event);
2023            return false;
2024        }
2025        return false;
2026    }
2027
2028    public List locals() {
2029        try {
2030            StackFrame frame = getDefaultFrame();
2031            if (frame != null) {
2032                return frame.visibleVariables();
2033            }
2034        } catch (InvalidStackFrameException e0) {
2035        } catch (AbsentInformationException e1) {
2036            error(Messages.NO_LOCALS_MSG);
2037        } catch (NoVMException e2) {
2038        }
2039        return new Vector();
2040    }
2041
2042
2043    /* ------------------------------------------------------------
2044     * Events
2045     * ------------------------------------------------------------
2046     */

2047
2048    /* VM listners */
2049    void handleVMStartEvent(VMStartEvent event) {
2050        resetPrompt(true);
2051        for (int i = 0; i < vmListeners.size(); i++) {
2052            ((VMListener) vmListeners.get(i)).
2053                vmStartEvent((VMStartEvent) event);
2054        }
2055    }
2056
2057    void handleVMDeathEvent(VMDeathEvent event) {
2058        resetPrompt(false);
2059        for (int i = 0; i < vmListeners.size(); i++) {
2060            ((VMListener) vmListeners.get(i)).
2061                vmDeathEvent((VMDeathEvent) event);
2062        }
2063    }
2064
2065    void handleVMDisconnectEvent(VMDisconnectEvent event) {
2066        resetPrompt(false);
2067        for (int i = 0; i < vmListeners.size(); i++) {
2068            ((VMListener) vmListeners.get(i)).
2069                vmDisconnectEvent((VMDisconnectEvent) event);
2070        }
2071    }
2072
2073
2074    /* Thread listeners */
2075    void handleThreadStartEvent(ThreadStartEvent event) {
2076        for (int i = 0; i < threadListeners.size(); i++) {
2077            ((ThreadListener) threadListeners.get(i)).
2078                threadStartEvent((ThreadStartEvent) event);
2079        }
2080    }
2081
2082    void handleThreadDeathEvent(ThreadDeathEvent event) {
2083        for (int i = 0; i < threadListeners.size(); i++) {
2084            ((ThreadListener) threadListeners.get(i)).
2085                threadDeathEvent((ThreadDeathEvent) event);
2086        }
2087    }
2088
2089
2090    /* Class listeners */
2091    void handleClassPrepareEvent(ClassPrepareEvent event) {
2092        for (int i = 0; i < classListeners.size(); i++) {
2093            ((ClassListener) classListeners.get(i)).
2094                classPrepareEvent((ClassPrepareEvent) event);
2095        }
2096    }
2097
2098    void handleClassUnloadEvent(ClassUnloadEvent event) {
2099        for (int i = 0; i < classListeners.size(); i++) {
2100            ((ClassListener) classListeners.get(i)).
2101                classUnloadEvent((ClassUnloadEvent) event);
2102        }
2103    }
2104
2105
2106    /* Stop listeners */
2107    void handleBreakpointEvent(BreakpointEvent event) {
2108        Thread.yield();
2109        setDefaults((LocatableEvent) event);
2110        for (int i = 0; i < stopListeners.size(); i++) {
2111            ((StopListener) stopListeners.get(i)).
2112                breakpointEvent((BreakpointEvent) event);
2113        }
2114        setPrompt();
2115        fireStopEvent();
2116    }
2117
2118    void handleAccessWatchpointEvent(AccessWatchpointEvent event) {
2119        Thread.yield();
2120        setDefaults((LocatableEvent) event);
2121        for (int i = 0; i < stopListeners.size(); i++) {
2122            ((StopListener) stopListeners.get(i)).
2123                accessWatchpointEvent((AccessWatchpointEvent) event);
2124        }
2125        setPrompt();
2126        fireStopEvent();
2127    }
2128
2129    void handleModificationWatchpointEvent(ModificationWatchpointEvent event) {
2130        Thread.yield();
2131        setDefaults((LocatableEvent) event);
2132        for (int i = 0; i < stopListeners.size(); i++) {
2133            ((StopListener) stopListeners.get(i)).
2134                modificationWatchpointEvent((ModificationWatchpointEvent) event);
2135        }
2136        setPrompt();
2137        fireStopEvent();
2138    }
2139
2140    void handleStepEvent(StepEvent event) {
2141        Thread.yield();
2142        setDefaults((LocatableEvent) event);
2143        for (int i = 0; i < stopListeners.size(); i++) {
2144            ((StopListener) stopListeners.get(i)).
2145                stepEvent((StepEvent) event);
2146        }
2147        setPrompt();
2148        fireStopEvent();
2149    }
2150
2151    void handleExceptionEvent(ExceptionEvent event) {
2152        setDefaults((LocatableEvent) event);
2153        for (int i = 0; i < stopListeners.size(); i++) {
2154            ((StopListener) stopListeners.get(i)).
2155                exceptionEvent((ExceptionEvent) event);
2156        }
2157        if (event.location() == null) {
2158            try {
2159                suspendCommand();
2160            } catch (DebuggerException de) {
2161            }
2162        }
2163        setPrompt();
2164        fireStopEvent();
2165    }
2166
2167    /* Method listeners */
2168    void handleMethodEntryEvent(MethodEntryEvent event) {
2169        for (int i = 0; i < methodListeners.size(); i++) {
2170            ((MethodListener) methodListeners.get(i)).
2171                methodEntryEvent((MethodEntryEvent) event);
2172        }
2173    }
2174
2175    void handleMethodExitEvent(MethodExitEvent event) {
2176        for (int i = 0; i < methodListeners.size(); i++) {
2177            ((MethodListener) methodListeners.get(i)).
2178                methodExitEvent((MethodExitEvent) event);
2179        }
2180    }
2181
2182    /* Debugger listeners */
2183    public void fireRequestSetEvent(RequestEvent re) {
2184        for (int i = 0; i < debuggerListeners.size(); i++) {
2185            ((DebuggerListener) debuggerListeners.get(i)).
2186                requestSetEvent(re);
2187        }
2188    }
2189
2190    public void fireRequestClearEvent(RequestEvent re) {
2191        for (int i = 0; i < debuggerListeners.size(); i++) {
2192            ((DebuggerListener) debuggerListeners.get(i)).
2193                requestClearEvent(re);
2194        }
2195    }
2196
2197    public void fireRequestDeferredEvent(RequestEvent re) {
2198        for (int i = 0; i < debuggerListeners.size(); i++) {
2199            ((DebuggerListener) debuggerListeners.get(i)).
2200                requestDeferredEvent(re);
2201        }
2202    }
2203
2204    public void fireRequestFailedEvent(RequestEvent re) {
2205        for (int i = 0; i < debuggerListeners.size(); i++) {
2206            ((DebuggerListener) debuggerListeners.get(i)).
2207                requestFailedEvent(re);
2208        }
2209    }
2210
2211    /* Prompt listeners */
2212    public void fireResetPrompt() {
2213        for (int i = 0; i < promptListeners.size(); i++) {
2214            ((PromptListener) promptListeners.get(i)).
2215                resetPrompt();
2216        }
2217    }
2218
2219    /* Source listeners */
2220    public void fireSourcePathChanged() {
2221        for (int i = 0; i < sourcePathListeners.size(); i++) {
2222            ((SourcePathListener) sourcePathListeners.get(i)).
2223                sourcePathChanged();
2224        }
2225    }
2226
2227    /* Progress listeners */
2228    public void fireStartEvent() {
2229    if (vm() == null) return;
2230        for (int i = 0; i < progressListeners.size(); i++) {
2231            ((ProgressListener) progressListeners.get(i)).
2232                startEvent();
2233        }
2234    }
2235
2236    public void fireStopEvent() {
2237        if (vm() == null) return;
2238        for (int i = 0; i < progressListeners.size(); i++) {
2239            ((ProgressListener) progressListeners.get(i)).
2240                stopEvent();
2241        }
2242    }
2243
2244    /****************************** Support ******************************/
2245
2246    static class AppVector extends Vector {
2247        public boolean add(Object JavaDoc o) {
2248            if (o instanceof DebuggerApp) {
2249                add(0, o);
2250                return true;
2251            } else {
2252                return super.add(o);
2253            }
2254        }
2255    }
2256
2257    protected Vector classListeners = new AppVector();
2258    protected Vector stopListeners = new AppVector();
2259    protected Vector methodListeners = new AppVector();
2260    protected Vector threadListeners = new AppVector();
2261    protected Vector vmListeners = new AppVector();
2262    protected Vector debuggerListeners = new AppVector();
2263    protected Vector promptListeners = new AppVector();
2264    protected Vector sourcePathListeners = new AppVector();
2265    protected Vector progressListeners = new AppVector();
2266
2267    /* Add listeners */
2268    public void addClassListener(ClassListener listener) {
2269        if (!classListeners.contains(listener)) {
2270            classListeners.add(listener);
2271        }
2272    }
2273
2274    public void addStopListener(StopListener listener) {
2275        if (!stopListeners.contains(listener)) {
2276            stopListeners.add(listener);
2277        }
2278    }
2279
2280    public void addMethodListener(MethodListener listener) {
2281        if (!methodListeners.contains(listener)) {
2282            methodListeners.add(listener);
2283        }
2284    }
2285
2286    public void addThreadListener(ThreadListener listener) {
2287        if (!threadListeners.contains(listener)) {
2288            threadListeners.add(listener);
2289        }
2290    }
2291
2292    public void addVMListener(VMListener listener) {
2293        if (!vmListeners.contains(listener)) {
2294            vmListeners.add(listener);
2295        }
2296    }
2297
2298    public void addDebuggerListener(DebuggerListener listener) {
2299        if (!debuggerListeners.contains(listener)) {
2300            debuggerListeners.add(listener);
2301        }
2302    }
2303
2304    public void addPromptListener(PromptListener listener) {
2305        if (!promptListeners.contains(listener)) {
2306            promptListeners.add(listener);
2307        }
2308    }
2309
2310    public void addSourcePathListener(SourcePathListener listener) {
2311        if (!sourcePathListeners.contains(listener)) {
2312            sourcePathListeners.add(listener);
2313        }
2314    }
2315
2316    public void addProgressListener(ProgressListener listener) {
2317        if (!progressListeners.contains(listener)) {
2318            progressListeners.add(listener);
2319        }
2320    }
2321
2322    /* Remove listeners */
2323    public boolean removeClassListener(ClassListener listener) {
2324        return classListeners.remove(listener);
2325    }
2326
2327    public boolean removeStopListener(StopListener listener) {
2328        return stopListeners.remove(listener);
2329    }
2330
2331    public boolean removeMethodListener(MethodListener listener) {
2332        return methodListeners.remove(listener);
2333    }
2334
2335    public boolean removeThreadListener(ThreadListener listener) {
2336        return threadListeners.remove(listener);
2337    }
2338
2339    public boolean removeVMListener(VMListener listener) {
2340        return vmListeners.remove(listener);
2341    }
2342
2343    public boolean removeDebuggerListener(DebuggerListener listener) {
2344        return debuggerListeners.remove(listener);
2345    }
2346
2347    public boolean removePromptListener(PromptListener listener) {
2348        return promptListeners.remove(listener);
2349    }
2350
2351    public boolean removeSourcePathListener(SourcePathListener listener) {
2352        return sourcePathListeners.remove(listener);
2353    }
2354
2355    public boolean removeProgressListener(ProgressListener listener) {
2356        return progressListeners.remove(listener);
2357    }
2358
2359    private final boolean shipping = false;
2360    private final void me() {
2361        if (shipping) return;
2362        String JavaDoc user = System.getProperty("user.name");
2363        if (user != null && user.equals("palm") &&
2364            System.getProperty("no.logger") != null) {
2365            System.out.println("Setting options for me...");
2366            getOptions().set("debugging-for-jeff");
2367            getOptions().set("nodemangle");
2368            getOptions().set("extra");
2369        }
2370    }
2371
2372    public String JavaDoc toLongString() { return toString(); }
2373
2374    // ------------------- Exception stuff -----------------------
2375
public void exception(String JavaDoc msg) {
2376        exception(msg, null);
2377    }
2378    public void exception(Throwable JavaDoc t) {
2379        exception(null, t);
2380    }
2381    public void exception(String JavaDoc msg, Throwable JavaDoc t) {
2382        error((msg != null ? msg : "") + (t != null ? ":" + t.getMessage() : ""));
2383    }
2384    public void classNotPreparedException(ClassNotPreparedException e,
2385                                          String JavaDoc className) {
2386        exception("The class " + className + " was not prepared", e);
2387    }
2388    public void objectCollectedException(ObjectCollectedException e,
2389                                         String JavaDoc object) {
2390        exception("The object " + object + " was collected", e);
2391    }
2392    public void invalidLineNumberException(InvalidLineNumberException e,
2393                                           String JavaDoc className, int line) {
2394        exception("The line " + line + " is invalid in class " + className, e);
2395    }
2396}
2397
2398class Threads {
2399
2400    private ThreadReference threadRef;
2401    private ThreadGroupReference threadGroupRef;
2402    private int frame;
2403    private Debugger debugger;
2404    private ThreadReference stoppedThreadRef;
2405
2406    Threads(Debugger debugger) {
2407        this.debugger = debugger;
2408    }
2409
2410    void flush() {
2411        threadRef = null;
2412        threadGroupRef = null;
2413        frame = 0;
2414        stoppedThreadRef = null;
2415    }
2416
2417    ThreadReference setThread(ThreadReference threadRef) {
2418        return (this.threadRef = threadRef);
2419    }
2420
2421    ThreadGroupReference setThreadGroup(ThreadGroupReference threadGroupRef) {
2422        return (this.threadGroupRef = threadGroupRef);
2423    }
2424
2425    int setFrame(int frame) {
2426        return (this.frame = frame);
2427    }
2428
2429    ThreadReference setStoppedThread(ThreadReference stoppedThreadRef) {
2430        return (this.stoppedThreadRef = stoppedThreadRef);
2431    }
2432
2433    ThreadReference getThread() throws NoVMException {
2434        if (threadRef == null) {
2435            Iterator iter = debugger.getVM().allThreads().iterator();
2436            while (iter.hasNext()) {
2437                return (threadRef = (ThreadReference) iter.next());
2438            }
2439        }
2440        return threadRef;
2441    }
2442
2443    ThreadGroupReference getThreadGroup() throws NoVMException {
2444        if (threadGroupRef == null) {
2445            Iterator iter = debugger.getVM().topLevelThreadGroups().iterator();
2446            while (iter.hasNext()) {
2447                return (threadGroupRef = (ThreadGroupReference) iter.next());
2448            }
2449        }
2450        return threadGroupRef;
2451    }
2452
2453    int getFrame() {
2454        return frame;
2455    }
2456
2457    StackFrame getStackFrame() throws NoVMException {
2458        StackFrame stackFrame = null;
2459        try {
2460            stackFrame = getThread().frame(frame);
2461        } catch (IncompatibleThreadStateException itse) {
2462        }
2463        return stackFrame;
2464    }
2465
2466    ThreadReference getStoppedThread() throws NoVMException {
2467        if (stoppedThreadRef == null) {
2468            Iterator iter = debugger.getVM().allThreads().iterator();
2469            while (iter.hasNext()) {
2470                ThreadReference threadRef = (ThreadReference) iter.next();
2471                if (threadRef.isAtBreakpoint()) {
2472                    return (stoppedThreadRef = threadRef);
2473                }
2474            }
2475        }
2476        return stoppedThreadRef;
2477    }
2478}
2479
Popular Tags