KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > demo > scripting > jconsole > ScriptJConsolePlugin


1 /*
2  * @(#)ScriptJConsolePlugin.java 1.4 06/07/19 04:44:52
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 package com.sun.demo.scripting.jconsole;
38
39 import com.sun.tools.jconsole.*;
40 import java.awt.*;
41 import java.awt.event.*;
42 import java.io.*;
43 import java.lang.reflect.*;
44 import java.util.concurrent.CountDownLatch JavaDoc;
45 import javax.script.*;
46 import javax.swing.*;
47 import javax.swing.event.*;
48 import java.util.*;
49
50 /**
51  * This is script console plugin. This class uses javax.script API to create
52  * interactive read-eval-print script shell within the jconsole GUI.
53  */

54 public class ScriptJConsolePlugin extends JConsolePlugin
55                      implements ScriptShellPanel.CommandProcessor {
56     // Panel for our tab
57
private volatile ScriptShellPanel window;
58     // Tabs that we add to jconsole GUI
59
private Map<String JavaDoc, JPanel> tabs;
60
61     // Script engine that evaluates scripts
62
private volatile ScriptEngine engine;
63
64     // script engine initialization occurs in background.
65
// This latch is used to coorrdinate engine init and eval.
66
private CountDownLatch JavaDoc engineReady = new CountDownLatch JavaDoc(1);
67
68     // File extension used for scripts of chosen language.
69
// For eg. ".js" for JavaScript, ".bsh" for BeanShell.
70
private String JavaDoc extension;
71
72     // Prompt to print in the read-eval-print loop. This is
73
// derived from the script file extension.
74
private volatile String JavaDoc prompt;
75
76     /**
77      * Constructor to create this plugin
78      */

79     public ScriptJConsolePlugin() {
80     }
81
82     @Override JavaDoc public Map<String JavaDoc, JPanel> getTabs() {
83         // create ScriptEngine
84
createScriptEngine();
85
86         // create panel for tab
87
window = new ScriptShellPanel(this);
88
89         // add tab to tabs map
90
tabs = new HashMap<String JavaDoc, JPanel>();
91         tabs.put("Script Shell", window);
92
93         new Thread JavaDoc(new Runnable JavaDoc() {
94             public void run() {
95                 // initialize the script engine
96
initScriptEngine();
97                 engineReady.countDown();
98             }
99         }).start();
100         return tabs;
101     }
102
103     @Override JavaDoc public SwingWorker<?,?> newSwingWorker() {
104         return null;
105     }
106     
107     @Override JavaDoc public void dispose() {
108         window.dispose();
109     }
110
111     public String JavaDoc getPrompt() {
112         return prompt;
113     }
114
115     public String JavaDoc executeCommand(String JavaDoc cmd) {
116         String JavaDoc res;
117         try {
118            engineReady.await();
119            Object JavaDoc tmp = engine.eval(cmd);
120            res = (tmp == null)? null : tmp.toString();
121         } catch (InterruptedException JavaDoc ie) {
122            res = ie.getMessage();
123         } catch (ScriptException se) {
124            res = se.getMessage();
125         }
126         return res;
127     }
128
129     //-- Internals only below this point
130
private void createScriptEngine() {
131         ScriptEngineManager manager = new ScriptEngineManager();
132         String JavaDoc language = getScriptLanguage();
133         engine = manager.getEngineByName(language);
134         if (engine == null) {
135             throw new RuntimeException JavaDoc("cannot load " + language + " engine");
136         }
137         extension = engine.getFactory().getExtensions().get(0);
138         prompt = extension + ">";
139         engine.setBindings(createBindings(), ScriptContext.ENGINE_SCOPE);
140     }
141
142     // Name of the System property used to select scripting language
143
private static final String JavaDoc LANGUAGE_KEY = "com.sun.demo.jconsole.console.language";
144
145     private String JavaDoc getScriptLanguage() {
146         // check whether explicit System property is set
147
String JavaDoc lang = System.getProperty(LANGUAGE_KEY);
148         if (lang == null) {
149             // default is JavaScript
150
lang = "JavaScript";
151         }
152         return lang;
153     }
154
155     // create Bindings that is backed by a synchronized HashMap
156
private Bindings createBindings() {
157         Map<String JavaDoc, Object JavaDoc> map =
158                 Collections.synchronizedMap(new HashMap<String JavaDoc, Object JavaDoc>());
159         return new SimpleBindings(map);
160     }
161
162     // create and initialize script engine
163
private void initScriptEngine() {
164         // set pre-defined global variables
165
setGlobals();
166         // load pre-defined initialization file
167
loadInitFile();
168         // load current user's initialization file
169
loadUserInitFile();
170     }
171
172     // set pre-defined global variables for script
173
private void setGlobals() {
174         engine.put("engine", engine);
175         engine.put("window", window);
176         engine.put("plugin", this);
177     }
178
179     // load initial script file (jconsole.<extension>)
180
private void loadInitFile() {
181         String JavaDoc oldFilename = (String JavaDoc) engine.get(ScriptEngine.FILENAME);
182         engine.put(ScriptEngine.FILENAME, "<built-in jconsole." + extension + ">");
183         try {
184             Class JavaDoc myClass = this.getClass();
185             InputStream stream = myClass.getResourceAsStream("/resources/jconsole." +
186                                        extension);
187             if (stream != null) {
188                 engine.eval(new InputStreamReader(new BufferedInputStream(stream)));
189             }
190         } catch (Exception JavaDoc exp) {
191             exp.printStackTrace();
192             // FIXME: What else I can do here??
193
} finally {
194             engine.put(ScriptEngine.FILENAME, oldFilename);
195         }
196     }
197
198     // load user's initial script file (~/jconsole.<extension>)
199
private void loadUserInitFile() {
200         String JavaDoc oldFilename = (String JavaDoc) engine.get(ScriptEngine.FILENAME);
201         String JavaDoc home = System.getProperty("user.home");
202         if (home == null) {
203             // no user.home?? should not happen??
204
return;
205         }
206         String JavaDoc fileName = home + File.separator + "jconsole." + extension;
207         if (! (new File(fileName).exists())) {
208             // user does not have ~/jconsole.<extension>
209
return;
210         }
211         engine.put(ScriptEngine.FILENAME, fileName);
212         try {
213             engine.eval(new FileReader(fileName));
214         } catch (Exception JavaDoc exp) {
215             exp.printStackTrace();
216             // FIXME: What else I can do here??
217
} finally {
218             engine.put(ScriptEngine.FILENAME, oldFilename);
219         }
220     }
221 }
222
Popular Tags