KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > tools > example > debug > tty > Env


1 /*
2  * @(#)Env.java 1.39 05/11/17
3  *
4  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 /*
8  * Copyright (c) 1997-1999 by Sun Microsystems, Inc. All Rights Reserved.
9  *
10  * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
11  * modify and redistribute this software in source and binary code form,
12  * provided that i) this copyright notice and license appear on all copies of
13  * the software; and ii) Licensee does not utilize the software in a manner
14  * which is disparaging to Sun.
15  *
16  * This software is provided "AS IS," without a warranty of any kind. ALL
17  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
18  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
19  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
20  * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
21  * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
22  * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
23  * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
24  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
25  * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGES.
27  *
28  * This software is not designed or intended for use in on-line control of
29  * aircraft, air traffic, aircraft navigation or aircraft communications; or in
30  * the design, construction, operation or maintenance of any nuclear
31  * facility. Licensee represents and warrants that it will not use or
32  * redistribute the Software for such purposes.
33  */

34
35 package com.sun.tools.example.debug.tty;
36
37 import com.sun.jdi.*;
38 import com.sun.jdi.request.StepRequest;
39 import com.sun.jdi.request.MethodEntryRequest;
40 import com.sun.jdi.request.MethodExitRequest;
41 import com.sun.tools.jdi.*;
42 import java.util.*;
43 import java.io.*;
44
45
46 class Env {
47
48     static EventRequestSpecList specList = new EventRequestSpecList();
49
50     private static VMConnection connection;
51
52     private static SourceMapper sourceMapper = new SourceMapper("");
53     private static List excludes;
54
55     private static final int SOURCE_CACHE_SIZE = 5;
56     private static List sourceCache = new LinkedList();
57
58     private static HashMap savedValues = new HashMap();
59     private static Method atExitMethod;
60
61     static void init(String JavaDoc connectSpec, boolean openNow, int flags) {
62         connection = new VMConnection(connectSpec, flags);
63         if (!connection.isLaunch() || openNow) {
64             connection.open();
65         }
66     }
67
68     static VMConnection connection() {
69         return connection;
70     }
71
72     static VirtualMachine vm() {
73         return connection.vm();
74     }
75
76     static void shutdown() {
77         shutdown(null);
78     }
79
80     static void shutdown(String JavaDoc message) {
81         if (connection != null) {
82             try {
83                 connection.disposeVM();
84             } catch (VMDisconnectedException e) {
85                 // Shutting down after the VM has gone away. This is
86
// not an error, and we just ignore it.
87
}
88         }
89         if (message != null) {
90             MessageOutput.lnprint(message);
91             MessageOutput.println();
92         }
93         System.exit(0);
94     }
95
96     static void setSourcePath(String JavaDoc srcPath) {
97         sourceMapper = new SourceMapper(srcPath);
98         sourceCache.clear();
99     }
100
101     static void setSourcePath(List srcList) {
102         sourceMapper = new SourceMapper(srcList);
103         sourceCache.clear();
104     }
105
106     static String JavaDoc getSourcePath() {
107         return sourceMapper.getSourcePath();
108     }
109
110     static private List excludes() {
111         if (excludes == null) {
112             setExcludes("java.*, javax.*, sun.*, com.sun.*");
113         }
114         return excludes;
115     }
116
117     static String JavaDoc excludesString() {
118         Iterator iter = excludes().iterator();
119         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
120         while (iter.hasNext()) {
121             String JavaDoc pattern = (String JavaDoc)iter.next();
122             buffer.append(pattern);
123             buffer.append(",");
124         }
125         return buffer.toString();
126     }
127
128     static void addExcludes(StepRequest request) {
129         Iterator iter = excludes().iterator();
130         while (iter.hasNext()) {
131             String JavaDoc pattern = (String JavaDoc)iter.next();
132             request.addClassExclusionFilter(pattern);
133         }
134     }
135
136     static void addExcludes(MethodEntryRequest request) {
137         Iterator iter = excludes().iterator();
138         while (iter.hasNext()) {
139             String JavaDoc pattern = (String JavaDoc)iter.next();
140             request.addClassExclusionFilter(pattern);
141         }
142     }
143
144     static void addExcludes(MethodExitRequest request) {
145         Iterator iter = excludes().iterator();
146         while (iter.hasNext()) {
147             String JavaDoc pattern = (String JavaDoc)iter.next();
148             request.addClassExclusionFilter(pattern);
149         }
150     }
151
152     static void setExcludes(String JavaDoc excludeString) {
153         StringTokenizer t = new StringTokenizer(excludeString, " ,;");
154         List list = new ArrayList();
155         while (t.hasMoreTokens()) {
156             list.add(t.nextToken());
157         }
158         excludes = list;
159     }
160
161     static Method atExitMethod() {
162         return atExitMethod;
163     }
164         
165     static void setAtExitMethod(Method mmm) {
166         atExitMethod = mmm;
167     }
168
169     /**
170      * Return a Reader cooresponding to the source of this location.
171      * Return null if not available.
172      * Note: returned reader must be closed.
173      */

174     static BufferedReader sourceReader(Location location) {
175         return sourceMapper.sourceReader(location);
176     }
177
178     static synchronized String JavaDoc sourceLine(Location location, int lineNumber)
179                                           throws IOException {
180         if (lineNumber == -1) {
181             throw new IllegalArgumentException JavaDoc();
182         }
183
184         try {
185             String JavaDoc fileName = location.sourceName();
186     
187             Iterator iter = sourceCache.iterator();
188             SourceCode code = null;
189             while (iter.hasNext()) {
190                 SourceCode candidate = (SourceCode)iter.next();
191                 if (candidate.fileName().equals(fileName)) {
192                     code = candidate;
193                     iter.remove();
194                     break;
195                 }
196             }
197             if (code == null) {
198                 BufferedReader reader = sourceReader(location);
199                 if (reader == null) {
200                     throw new FileNotFoundException(fileName);
201                 }
202                 code = new SourceCode(fileName, reader);
203                 if (sourceCache.size() == SOURCE_CACHE_SIZE) {
204                     sourceCache.remove(sourceCache.size() - 1);
205                 }
206             }
207             sourceCache.add(0, code);
208             return code.sourceLine(lineNumber);
209         } catch (AbsentInformationException e) {
210             throw new IllegalArgumentException JavaDoc();
211         }
212     }
213
214     /** Return a description of an object. */
215     static String JavaDoc description(ObjectReference ref) {
216         ReferenceType clazz = ref.referenceType();
217         long id = ref.uniqueID();
218         if (clazz == null) {
219             return toHex(id);
220         } else {
221             return MessageOutput.format("object description and hex id",
222                                         new Object JavaDoc [] {clazz.name(),
223                                                        toHex(id)});
224         }
225     }
226
227     /** Convert a long to a hexadecimal string. */
228     static String JavaDoc toHex(long n) {
229     char s1[] = new char[16];
230     char s2[] = new char[18];
231
232     /* Store digits in reverse order. */
233     int i = 0;
234     do {
235         long d = n & 0xf;
236         s1[i++] = (char)((d < 10) ? ('0' + d) : ('a' + d - 10));
237     } while ((n >>>= 4) > 0);
238
239     /* Now reverse the array. */
240     s2[0] = '0';
241     s2[1] = 'x';
242     int j = 2;
243     while (--i >= 0) {
244         s2[j++] = s1[i];
245     }
246     return new String JavaDoc(s2, 0, j);
247     }
248
249     /** Convert hexadecimal strings to longs. */
250     static long fromHex(String JavaDoc hexStr) {
251     String JavaDoc str = hexStr.startsWith("0x") ?
252         hexStr.substring(2).toLowerCase() : hexStr.toLowerCase();
253     if (hexStr.length() == 0) {
254         throw new NumberFormatException JavaDoc();
255     }
256     
257     long ret = 0;
258     for (int i = 0; i < str.length(); i++) {
259         int c = str.charAt(i);
260         if (c >= '0' && c <= '9') {
261         ret = (ret * 16) + (c - '0');
262         } else if (c >= 'a' && c <= 'f') {
263         ret = (ret * 16) + (c - 'a' + 10);
264         } else {
265         throw new NumberFormatException JavaDoc();
266         }
267     }
268     return ret;
269     }
270     
271     static ReferenceType getReferenceTypeFromToken(String JavaDoc idToken) {
272         ReferenceType cls = null;
273         if (Character.isDigit(idToken.charAt(0))) {
274             cls = null;
275         } else if (idToken.startsWith("*.")) {
276         // This notation saves typing by letting the user omit leading
277
// package names. The first
278
// loaded class whose name matches this limited regular
279
// expression is selected.
280
idToken = idToken.substring(1);
281         List classes = Env.vm().allClasses();
282         Iterator iter = classes.iterator();
283         while (iter.hasNext()) {
284             ReferenceType type = ((ReferenceType)iter.next());
285             if (type.name().endsWith(idToken)) {
286                 cls = type;
287                 break;
288             }
289         }
290     } else {
291             // It's a class name
292
List classes = Env.vm().classesByName(idToken);
293             if (classes.size() > 0) {
294                 // TO DO: handle multiples
295
cls = (ReferenceType)classes.get(0);
296             }
297         }
298         return cls;
299     }
300
301     static Set getSaveKeys() {
302         return savedValues.keySet();
303     }
304
305     static Value getSavedValue(String JavaDoc key) {
306         return (Value)savedValues.get(key);
307     }
308
309     static void setSavedValue(String JavaDoc key, Value value) {
310         savedValues.put(key, value);
311     }
312
313     static class SourceCode {
314         private String JavaDoc fileName;
315         private List sourceLines = new ArrayList();
316
317         SourceCode(String JavaDoc fileName, BufferedReader reader) throws IOException {
318             this.fileName = fileName;
319             try {
320                 String JavaDoc line = reader.readLine();
321                 while (line != null) {
322                     sourceLines.add(line);
323                     line = reader.readLine();
324                 }
325             } finally {
326                 reader.close();
327             }
328         }
329
330         String JavaDoc fileName() {
331             return fileName;
332         }
333
334         String JavaDoc sourceLine(int number) {
335             int index = number - 1; // list is 0-indexed
336
if (index >= sourceLines.size()) {
337                 return null;
338             } else {
339                 return (String JavaDoc)sourceLines.get(index);
340             }
341         }
342     }
343 }
344
Popular Tags