Java/JDK 6/Script Engines — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 06:11, 1 июня 2010
Содержание
- 1 Any script have to be compiled into intermediate code.
- 2 Call a JavaScript function three times
- 3 Catch ScriptException
- 4 Compresses a String containing JavaScript by removing comments and whitespace.
- 5 Escape and unescape javascript code
- 6 Execute Javascript script in a file
- 7 Executing Scripts from Java Programs
- 8 Get a ScriptEngine by MIME type
- 9 Get Script engine by extension name
- 10 Get the value in JavaScript from Java Code by reference the variable name
- 11 Invoke an function
- 12 Java Language Binding with JavaScript
- 13 Listing All Script Engines
- 14 List the script engines
- 15 Pass or retrieve values from a scripting engine (jdk1.6)
- 16 Pass parameter to JavaScript through Java code
- 17 Read and execute a script source file
- 18 Retrieving Script Engines by Name
- 19 Retrieving the Metadata of Script Engines
- 20 Retrieving the Registered Name of a Scripting Engine
- 21 Retrieving the Supported File Extensions of a Scripting Engine
- 22 Retrieving the Supported Mime Types of a Scripting Engine
- 23 Run JavaScript and get the result by using Java
- 24 Run Javascript function with ScriptEngine
- 25 Running Scripts with Java Script Engine
- 26 Save the compiled JavaScript to CompiledScript object
- 27 Use an external file containing the javascript code
- 28 Use an external file containing the javascript code. The .JS file is loaded from the classpath.
- 29 Use Java scripting engine
- 30 Use Java scripting engine (JDK 1.6)
- 31 Using Java Objects in JavaScript
- 32 Using thread to run JavaScript by Java
- 33 Utility to take xml string and convert it to a javascript based tree within html.
- 34 Variables bound through ScriptEngine
- 35 With Compilable interface you store the intermediate code of an entire script
- 36 Working with Compilable Scripts
Any script have to be compiled into intermediate code.
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class InvocableDemo {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.eval("function add (a, b) {c = a + b; return c; }");
Invocable jsInvoke = (Invocable) engine;
Object result1 = jsInvoke.invokeFunction("add", new Object[] { 10, 5 });
System.out.println(result1);
Adder adder = jsInvoke.getInterface(Adder.class);
int result2 = adder.add(10, 5);
System.out.println(result2);
}
}
interface Adder {
int add(int a, int b);
}
Call a JavaScript function three times
import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JDK6CompileTest {
public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.put("counter", 0);
if (engine instanceof Compilable) {
Compilable compEngine = (Compilable) engine;
try {
CompiledScript script = compEngine.rupile("function count(){counter=counter+1;return counter;}; count();");
System.out.println(script.eval());
System.out.println(script.eval());
System.out.println(script.eval());
} catch (ScriptException e) {
System.err.println(e);
}
} else {
System.err.println("Engine can"t compile code");
}
}
}
/*1.0
2.0
3.0*/
Catch ScriptException
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class BindingDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.put("a", 1);
engine.put("b", 5);
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
Object a = bindings.get("a");
Object b = bindings.get("b");
System.out.println("a = " + a);
System.out.println("b = " + b);
Object result;
try {
result = engine.eval("c = aaaa + bbbb;");
System.out.println("a + b = " + result);
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*a = 1
b = 5
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "aaaa" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:110)
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:124)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247)
at BindingDemo.main(BindingDemo.java:22)
*/
Compresses a String containing JavaScript by removing comments and whitespace.
/*
* This file is part of the Echo Web Application Framework (hereinafter "Echo").
* Copyright (C) 2002-2009 NextApp, Inc.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or the
* GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which
* case the provisions of the GPL or the LGPL are applicable instead of those
* above. If you wish to allow use of your version of this file only under the
* terms of either the GPL or the LGPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and other
* provisions required by the GPL or the LGPL. If you do not delete the
* provisions above, a recipient may use your version of this file under the
* terms of any one of the MPL, the GPL or the LGPL.
*/
/**
* Compresses a String containing JavaScript by removing comments and
* whitespace.
*/
public class JavaScriptCompressor {
private static final char LINE_FEED = "\n";
private static final char CARRIAGE_RETURN = "\r";
private static final char SPACE = " ";
private static final char TAB = "\t";
/**
* Compresses a String containing JavaScript by removing comments and
* whitespace.
*
* @param script the String to compress
* @return a compressed version
*/
public static String compress(String script) {
JavaScriptCompressor jsc = new JavaScriptCompressor(script);
return jsc.outputBuffer.toString();
}
/** Original JavaScript text. */
private String script;
/**
* Compressed output buffer.
* This buffer may only be modified by invoking the <code>append()</code>
* method.
*/
private StringBuffer outputBuffer;
/** Current parser cursor position in original text. */
private int pos;
/** Character at parser cursor position. */
private char ch;
/** Last character appended to buffer. */
private char lastAppend;
/** Flag indicating if end-of-buffer has been reached. */
private boolean endReached;
/** Flag indicating whether content has been appended after last identifier. */
private boolean contentAppendedAfterLastIdentifier = true;
/**
* Creates a new <code>JavaScriptCompressor</code> instance.
*
* @param script
*/
private JavaScriptCompressor(String script) {
this.script = script;
outputBuffer = new StringBuffer(script.length());
nextChar();
while (!endReached) {
if (Character.isJavaIdentifierStart(ch)) {
renderIdentifier();
} else if (ch == " ") {
skipWhiteSpace();
} else if (isWhitespace()) {
// Compress whitespace
skipWhiteSpace();
} else if ((ch == """) || (ch == "\"")) {
// Handle strings
renderString();
} else if (ch == "/") {
// Handle comments
nextChar();
if (ch == "/") {
nextChar();
skipLineComment();
} else if (ch == "*") {
nextChar();
skipBlockComment();
} else {
append("/");
}
} else {
append(ch);
nextChar();
}
}
}
/**
* Append character to output.
*
* @param ch the character to append
*/
private void append(char ch) {
lastAppend = ch;
outputBuffer.append(ch);
contentAppendedAfterLastIdentifier = true;
}
/**
* Determines if current character is whitespace.
*
* @return true if the character is whitespace
*/
private boolean isWhitespace() {
return ch == CARRIAGE_RETURN || ch == SPACE || ch == TAB || ch == LINE_FEED;
}
/**
* Load next character.
*/
private void nextChar() {
if (!endReached) {
if (pos < script.length()) {
ch = script.charAt(pos++);
} else {
endReached = true;
ch = 0;
}
}
}
/**
* Adds an identifier to output.
*/
private void renderIdentifier() {
if (!contentAppendedAfterLastIdentifier)
append(SPACE);
append(ch);
nextChar();
while (Character.isJavaIdentifierPart(ch)) {
append(ch);
nextChar();
}
contentAppendedAfterLastIdentifier = false;
}
/**
* Adds quoted String starting at current character to output.
*/
private void renderString() {
char startCh = ch; // Save quote char
append(ch);
nextChar();
while (true) {
if ((ch == LINE_FEED) || (ch == CARRIAGE_RETURN) || (endReached)) {
// JavaScript error: string not terminated
return;
} else {
if (ch == "\\") {
append(ch);
nextChar();
if ((ch == LINE_FEED) || (ch == CARRIAGE_RETURN) || (endReached)) {
// JavaScript error: string not terminated
return;
}
append(ch);
nextChar();
} else {
append(ch);
if (ch == startCh) {
nextChar();
return;
}
nextChar();
}
}
}
}
/**
* Moves cursor past a line comment.
*/
private void skipLineComment() {
while ((ch != CARRIAGE_RETURN) && (ch != LINE_FEED)) {
if (endReached) {
return;
}
nextChar();
}
}
/**
* Moves cursor past a block comment.
*/
private void skipBlockComment() {
while (true) {
if (endReached) {
return;
}
if (ch == "*") {
nextChar();
if (ch == "/") {
nextChar();
return;
}
} else
nextChar();
}
}
/**
* Renders a new line character, provided previously rendered character
* is not a newline.
*/
private void renderNewLine() {
if (lastAppend != "\n" && lastAppend != "\r") {
append("\n");
}
}
/**
* Moves cursor past white space (including newlines).
*/
private void skipWhiteSpace() {
if (ch == LINE_FEED || ch == CARRIAGE_RETURN) {
renderNewLine();
} else {
append(ch);
}
nextChar();
while (ch == LINE_FEED || ch == CARRIAGE_RETURN || ch == SPACE || ch == TAB) {
if (ch == LINE_FEED || ch == CARRIAGE_RETURN) {
renderNewLine();
}
nextChar();
}
}
}
Escape and unescape javascript code
/*
* Copyright 2005 Joe Walker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Arrays;
import java.util.Locale;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* Various Javascript code utilities.
* The escape classes were taken from jakarta-commons-lang which in turn
* borrowed from Turbine and other projects. The list of authors below is almost
* certainly far too long, but I"m not sure who really wrote these methods.
* @author Joe Walker [joe at getahead dot ltd dot uk]
* @author Henri Yandell
* @author Alexander Day Chaffee
* @author Antony Riley
* @author Helge Tesgaard
* @author Sean Brown
* @author Gary Gregory
* @author Phil Steitz
* @author Pete Gieser
*/
public class JavascriptUtil
{
/**
* <p>Escapes the characters in a <code>String</code> using JavaScript String rules.</p>
* <p>Escapes any values it finds into their JavaScript String form.
* Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
*
* <p>So a tab becomes the characters <code>"\\"</code> and
* <code>"t"</code>.</p>
*
* <p>The only difference between Java strings and JavaScript strings
* is that in JavaScript, a single quote must be escaped.</p>
*
* <p>Example:
* <pre>
* input string: He didn"t say, "Stop!"
* output string: He didn\"t say, \"Stop!\"
* </pre>
* </p>
*
* @param str String to escape values in, may be null
* @return String with escaped values, <code>null</code> if null string input
*/
public static String escapeJavaScript(String str)
{
if (str == null)
{
return null;
}
StringBuffer writer = new StringBuffer(str.length() * 2);
int sz = str.length();
for (int i = 0; i < sz; i++)
{
char ch = str.charAt(i);
// handle unicode
if (ch > 0xfff)
{
writer.append("\\u");
writer.append(hex(ch));
}
else if (ch > 0xff)
{
writer.append("\\u0");
writer.append(hex(ch));
}
else if (ch > 0x7f)
{
writer.append("\\u00");
writer.append(hex(ch));
}
else if (ch < 32)
{
switch (ch)
{
case "\b":
writer.append("\\");
writer.append("b");
break;
case "\n":
writer.append("\\");
writer.append("n");
break;
case "\t":
writer.append("\\");
writer.append("t");
break;
case "\f":
writer.append("\\");
writer.append("f");
break;
case "\r":
writer.append("\\");
writer.append("r");
break;
default:
if (ch > 0xf)
{
writer.append("\\u00");
writer.append(hex(ch));
}
else
{
writer.append("\\u000");
writer.append(hex(ch));
}
break;
}
}
else
{
switch (ch)
{
case "\"":
// If we wanted to escape for Java strings then we would
// not need this next line.
writer.append("\\");
writer.append("\"");
break;
case """:
writer.append("\\");
writer.append(""");
break;
case "\\":
writer.append("\\");
writer.append("\\");
break;
default:
writer.append(ch);
break;
}
}
}
return writer.toString();
}
/**
* <p>Returns an upper case hexadecimal <code>String</code> for the given
* character.</p>
* @param ch The character to convert.
* @return An upper case hexadecimal <code>String</code>
*/
private static String hex(char ch)
{
return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);
}
/**
* <p>Unescapes any JavaScript literals found in the <code>String</code>.</p>
* <p>For example, it will turn a sequence of <code>"\"</code> and <code>"n"</code>
* into a newline character, unless the <code>"\"</code> is preceded by another
* <code>"\"</code>.</p>
* @param str the <code>String</code> to unescape, may be null
* @return A new unescaped <code>String</code>, <code>null</code> if null string input
*/
public static String unescapeJavaScript(String str)
{
if (str == null)
{
return null;
}
StringBuffer writer = new StringBuffer(str.length());
int sz = str.length();
StringBuffer unicode = new StringBuffer(4);
boolean hadSlash = false;
boolean inUnicode = false;
for (int i = 0; i < sz; i++)
{
char ch = str.charAt(i);
if (inUnicode)
{
// if in unicode, then we"re reading unicode
// values in somehow
unicode.append(ch);
if (unicode.length() == 4)
{
// unicode now contains the four hex digits
// which represents our unicode character
try
{
int value = Integer.parseInt(unicode.toString(), 16);
writer.append((char) value);
unicode.setLength(0);
inUnicode = false;
hadSlash = false;
}
catch (NumberFormatException nfe)
{
throw new IllegalArgumentException("Unable to parse unicode value: " + unicode + " cause: " + nfe);
}
}
continue;
}
if (hadSlash)
{
// handle an escaped value
hadSlash = false;
switch (ch)
{
case "\\":
writer.append("\\");
break;
case "\"":
writer.append("\"");
break;
case "\"":
writer.append(""");
break;
case "r":
writer.append("\r");
break;
case "f":
writer.append("\f");
break;
case "t":
writer.append("\t");
break;
case "n":
writer.append("\n");
break;
case "b":
writer.append("\b");
break;
case "u":
// uh-oh, we"re in unicode country....
inUnicode = true;
break;
default:
writer.append(ch);
break;
}
continue;
}
else if (ch == "\\")
{
hadSlash = true;
continue;
}
writer.append(ch);
}
if (hadSlash)
{
// then we"re in the weird case of a \ at the end of the
// string, let"s output it anyway.
writer.append("\\");
}
return writer.toString();
}
/**
* Check to see if the given word is reserved or a bad idea in any known
* version of JavaScript.
* @param name The word to check
* @return false if the word is not reserved
*/
public static boolean isReservedWord(String name)
{
return reserved.contains(name);
}
/**
* The array of javascript reserved words
*/
private static final String[] RESERVED_ARRAY = new String[]
{
// Reserved and used at ECMAScript 4
"as",
"break",
"case",
"catch",
"class",
"const",
"continue",
"default",
"delete",
"do",
"else",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"import",
"in",
"instanceof",
"is",
"namespace",
"new",
"null",
"package",
"private",
"public",
"return",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"use",
"var",
"void",
"while",
"with",
// Reserved for future use at ECMAScript 4
"abstract",
"debugger",
"enum",
"goto",
"implements",
"interface",
"native",
"protected",
"synchronized",
"throws",
"transient",
"volatile",
// Reserved in ECMAScript 3, unreserved at 4 best to avoid anyway
"boolean",
"byte",
"char",
"double",
"final",
"float",
"int",
"long",
"short",
"static",
// I have seen the following list as "best avoided for function names"
// but it seems way to all encompassing, so I"m not going to include it
/*
"alert", "anchor", "area", "arguments", "array", "assign", "blur",
"boolean", "button", "callee", "caller", "captureevents", "checkbox",
"clearinterval", "cleartimeout", "close", "closed", "confirm",
"constructor", "date", "defaultstatus", "document", "element", "escape",
"eval", "fileupload", "find", "focus", "form", "frame", "frames",
"getclass", "hidden", "history", "home", "image", "infinity",
"innerheight", "isfinite", "innerwidth", "isnan", "java", "javaarray",
"javaclass", "javaobject", "javapackage", "length", "link", "location",
"locationbar", "math", "menubar", "mimetype", "moveby", "moveto",
"name", "nan", "navigate", "navigator", "netscape", "number", "object",
"onblur", "onerror", "onfocus", "onload", "onunload", "open", "opener",
"option", "outerheight", "outerwidth", "packages", "pagexoffset",
"pageyoffset", "parent", "parsefloat", "parseint", "password",
"personalbar", "plugin", "print", "prompt", "prototype", "radio", "ref",
"regexp", "releaseevents", "reset", "resizeby", "resizeto",
"routeevent", "scroll", "scrollbars", "scrollby", "scrollto", "select",
"self", "setinterval", "settimeout", "status", "statusbar", "stop",
"string", "submit", "sun", "taint", "text", "textarea", "toolbar",
"top", "tostring", "unescape", "untaint", "unwatch", "valueof", "watch",
"window",
*/
};
/**
* The list of reserved words
*/
private static SortedSet<String> reserved = new TreeSet<String>();
/**
* For easy access ...
*/
static
{
// The Javascript reserved words array so we don"t generate illegal javascript
reserved.addAll(Arrays.asList(RESERVED_ARRAY));
}
}
Execute Javascript script in a file
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class RunScriptFileDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
FileReader reader = new FileReader("yourFile.js");
engine.eval(reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/* File: yourFile.js
*
function add(a, b) {
c = a + b;
return c;
}
result = add (10, 5);
print ("Result = " + result);
*/
Executing Scripts from Java Programs
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class ScriptExecutionDemo {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine jsEngine = manager.getEngineByExtension("js");
jsEngine.eval("println ("Hello! JavaScript executed from a Java program.")");
}
}
Get a ScriptEngine by MIME type
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class GetEngineByMimeDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
/* Retrieve a ScriptEngine that supports the text/javascript MIME type */
ScriptEngine jsEngine = manager.getEngineByMimeType("text/javascript");
if (!(jsEngine == null)) {
System.out.println("text/javascript MIME type retrieved:" + jsEngine);
}
ScriptEngine jsEngine2 = manager.getEngineByMimeType("text/vbscript");
if (jsEngine2 == null)
System.out.println("\nNo supported script engine found for text/vbscript MIME type.");
}
}
Get Script engine by extension name
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class GetEngineByExtensionDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
/* Retrieve a ScriptEngine that supports scripts with .js extension */
ScriptEngine jsEngine = manager.getEngineByExtension("js");
System.out.println(jsEngine);
}
}
Get the value in JavaScript from Java Code by reference the variable name
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class RunJavaScript {
public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try {
engine.put("name", "abcde");
engine.eval("var output = "";for (i = 0; i <= name.length; i++) {"
+ " output = name.charAt(i)+"-" + output" + "}");
String name = (String) engine.get("output");
System.out.println(name);
} catch (ScriptException e) {
System.err.println(e);
}
}
}
//-e-d-c-b-a-
Invoke an function
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InvocableTest {
public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try {
engine.eval("function myFunction(name){var output = "";"
+ " for (i = 0; i <= name.length; i++) {output = name.charAt(i)+"-"+ output"
+ " } return output;}");
Invocable invokeEngine = (Invocable) engine;
Object o = invokeEngine.invokeFunction("myFunction", "abcde");
System.out.println(o);
} catch (NoSuchMethodException e) {
System.err.println(e);
} catch (ScriptException e) {
System.err.println(e);
}
}
}
Java Language Binding with JavaScript
//The Rhino scripting engine of Java SE 6 allows you to use the Java programming language in scripts.
importPackage(javax.swing);
importPackage(java.lang);
importPackage(java.awt.event);
jFrame1 = new JFrame("Greeting");
jLabel1 = new JLabel("Name:");
jTextField1 = JTextField();
jLabel2 = new JLabel();
jButton1 = new JButton("Click");
jFrame1.setSize(400, 400);
listener1 = {
actionPerformed:function(e)
{
jLabel2.setText("Hello "+jTextField1.getText()+ " !");
}
}
alistener = new ActionListener(listener1);
jButton1.addActionListener(alistener);
jFrame1.getContentPane().setLayout(null);
jFrame1.getContentPane().add(jLabel1);
jFrame1.getContentPane().add(jTextField1);
jFrame1.getContentPane().add(jLabel2);
jFrame1.getContentPane().add(jButton1);
jLabel1.setBounds(10, 50, 40, 20);
jTextField1.setBounds(50, 50, 220, 20);
jLabel2.setBounds(10, 100, 220, 20);
jButton1.setBounds(280, 50, 120, 23);
jFrame1.setDefaultCloseOperation(jFrame1.EXIT_ON_CLOSE);
jFrame1.setVisible(true);
for(;;)
{
}
Listing All Script Engines
import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ListEngineFactoryDemo {
public static void main(String[] args) {
// create ScriptEngineManager
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factoryList = manager.getEngineFactories();
for (ScriptEngineFactory factory : factoryList) {
System.out.println(factory.getEngineName());
System.out.println(factory.getLanguageName());
}
}
}
//Mozilla Rhino
//ECMAScript
List the script engines
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ListEngines {
public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factories = manager.getEngineFactories();
for (ScriptEngineFactory factory : factories) {
System.out.println(factory.getEngineName());
System.out.println(factory.getEngineVersion());
System.out.println(factory.getLanguageName());
System.out.println(factory.getLanguageVersion());
System.out.println(factory.getExtensions());
System.out.println(factory.getMimeTypes());
System.out.println(factory.getNames());
}
}
}
/*Mozilla Rhino
1.6 release 2
ECMAScript
1.6
[js]
[application/javascript, application/ecmascript, text/javascript, text/ecmascript]
[js, rhino, JavaScript, javascript, ECMAScript, ecmascript]
*/
Pass or retrieve values from a scripting engine (jdk1.6)
import java.util.Arrays;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("javascript");
List<String> list1 = Arrays.asList("A", "B", "C", "D", "E");
engine.put("list1", list1);
String jsCode = "var index; var values =list1.toArray();"
+ "println("Java to Javascript");for(index in values) {"
+ " println(values[index]);}";
engine.eval(jsCode);
jsCode = "importPackage(java.util);var list2 = Arrays.asList(["A", "B", "C"]); ";
engine.eval(jsCode);
List<String> list2 = (List<String>) engine.get("list2");
for (String val : list2) {
System.out.println(val);
}
}
}
Pass parameter to JavaScript through Java code
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class RunJavaScript {
public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try {
engine.put("name", "abcde");
engine.eval("var output = "";for (i = 0; i <= name.length; i++) {"
+ " output = name.charAt(i)+"-" + output" + "}");
String name = (String) engine.get("output");
System.out.println(name);
} catch (ScriptException e) {
System.err.println(e);
}
}
}
//-e-d-c-b-a-
Read and execute a script source file
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class ScriptExecutionReaderDemo {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine jsEengine = manager.getEngineByExtension("js");
Reader reader = new InputStreamReader(new FileInputStream("yourJavaScript.js"));
jsEengine.eval(reader);
}
}
//File yourJavaScript.js
/*
importPackage(java.lang);
function getName(name)
{
if ((name != "")&&(name !=null))
{
System.out.println("Hello "+name+"!")
}
else
{
System.out.println("Hello!")
}
}
getName("TOM");
*/
Retrieving Script Engines by Name
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class GetEngineByName {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
/* Retrieve a ScriptEngine registered with the rhino name */
ScriptEngine jsEngine = manager.getEngineByName("rhino");
if (!(jsEngine == null)) {
System.out.println(jsEngine);
} else {
System.out.println("\nNo supported script engine foundregistered as Rhino.");
}
}
}
Retrieving the Metadata of Script Engines
import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class MetadataDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factories = manager.getEngineFactories();
for (ScriptEngineFactory factory : factories) {
System.out.println("Full name = " + factory.getEngineName());
System.out.println("\nVersion = " + factory.getEngineVersion());
System.out.println("\nSupported language version = " + factory.getLanguageVersion());
}
}
}
/*Full name = Mozilla Rhino
Version = 1.6 release 2
Supported language version = 1.6
*/
Retrieving the Registered Name of a Scripting Engine
import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class RegisteredNameDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factories = manager.getEngineFactories();
for (ScriptEngineFactory factory : factories) {
List<String> regNames = factory.getNames();
for (int i = 0; i < regNames.size(); i++) {
System.out.printf("Registered name " + i + " " + (String) regNames.get(i) + "\n");
}
}
}
}
Retrieving the Supported File Extensions of a Scripting Engine
import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class FileExtensionsDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factories = manager.getEngineFactories();
for (ScriptEngineFactory factory : factories) {
List<String> ext = factory.getExtensions();
for (int i = 0; i < ext.size(); i++) {
System.out.printf("Supported file extension: " + (String) ext.get(i) + "\n");
}
}
}
}
Retrieving the Supported Mime Types of a Scripting Engine
import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class MimeTypesDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factories = manager.getEngineFactories();
for (ScriptEngineFactory factory : factories) {
List<String> mimeTypes = factory.getMimeTypes();
for (int i = 0; i < mimeTypes.size(); i++) {
System.out.printf("Supported MIME type " + i + " " + (String) mimeTypes.get(i) + "\n");
}
}
}
}
Run JavaScript and get the result by using Java
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class RunJavaScript {
public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try {
Double hour = (Double) engine.eval("var date = new Date();" + "date.getHours();");
String msg;
if (hour < 10) {
msg = "Good morning";
} else if (hour < 16) {
msg = "Good afternoon";
} else if (hour < 20) {
msg = "Good evening";
} else {
msg = "Good night";
}
System.out.println(hour);
System.out.println(msg);
} catch (ScriptException e) {
System.err.println(e);
}
}
}
/*10.0
Good afternoon
*/
Run Javascript function with ScriptEngine
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] argv) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String myJSCode = "function myFunction(){return (40 + 2);}myFunction();";
System.out.println(engine.eval(myJSCode));
}
}
Running Scripts with Java Script Engine
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class RunScriptDemo {
public static void main (String[] args) {
ScriptEngineManager manager = new ScriptEngineManager ();
ScriptEngine engine = manager.getEngineByName ("js");
String script = "print ("www.jexp.ru")";
try {
engine.eval (script);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
//www.jexp.ru
Save the compiled JavaScript to CompiledScript object
import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class CompileTest {
public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.put("counter", 0);
if (engine instanceof Compilable) {
Compilable compEngine = (Compilable) engine;
try {
CompiledScript script = compEngine.rupile("function count(){counter=counter+1;return counter;}; count();");
System.out.println(script.eval());
System.out.println(script.eval());
System.out.println(script.eval());
} catch (ScriptException e) {
System.err.println(e);
}
} else {
System.err.println("Engine can"t compile code");
}
}
}
Use an external file containing the javascript code
import java.io.InputStreamReader;
import java.util.List;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("javascript");
engine.eval(new InputStreamReader
(Main.class.getResourceAsStream("s.js")));
List <String> list1 = (List <String>)engine.get("list1");
if (list1 != null) {
for (String s : (List<String>) list1) {
System.out.println(s);
}
}
if (engine instanceof Invocable){
Invocable engineInv = (Invocable)engine;
Object obj = engine.get("listObject");
Object list2 = engineInv.invokeMethod(obj, "getList2");
if (list2 != null) {
for (String s : (List<String>) list2) {
System.out.println(s);
}
}
}
}
}
Use an external file containing the javascript code. The .JS file is loaded from the classpath.
import java.io.InputStreamReader;
import java.util.List;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("javascript");
engine.eval(new InputStreamReader(Main.class.getResourceAsStream("scripting.js")));
List<String> list1 = (List<String>) engine.get("list1");
if (list1 != null) {
for (String s : (List<String>) list1) {
System.out.println(s);
}
}
Invocable engineInv = (Invocable) engine;
Object obj = engine.get("listObject");
Object list2 = engineInv.invokeMethod(obj, "getList2");
if (list2 != null) {
for (String s : (List<String>) list2) {
System.out.println(s);
}
}
}
}
Use Java scripting engine
import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
List<ScriptEngineFactory> engines = mgr.getEngineFactories();
for (ScriptEngineFactory engine : engines) {
System.out.println(engine.getEngineName());
for (String n : engine.getNames()) {
System.out.println("Short name : " + n);
}
}
}
}
Use Java scripting engine (JDK 1.6)
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args)throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
List<ScriptEngineFactory> engines = mgr.getEngineFactories();
for (ScriptEngineFactory engine : engines) {
System.out.println(engine.getEngineName());
for (String n : engine.getNames()) {
System.out.println("Short name : " + n);
}
}
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String myJSCode = "function myFunction(){return (4+2);}myFunction();";
System.out.println(engine.eval(myJSCode));
}
}
Using Java Objects in JavaScript
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class JavaObjectDemo
{
public static void main(String[] args) throws Exception
{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine jsEngine;
jsEngine = manager.getEngineByExtension("js");
jsEngine.eval("importPackage(javax.swing);var optionPane =JOptionPane.showMessageDialog(null, "Hello!);");
}
}
Using thread to run JavaScript by Java
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InterfaceTest {
public static void main(String args[]) throws Exception{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval("function run() {print("www.jexp.ru");}");
Invocable invokeEngine = (Invocable) engine;
Runnable runner = invokeEngine.getInterface(Runnable.class);
Thread t = new Thread(runner);
t.start();
t.join();
}
}
Utility to take xml string and convert it to a javascript based tree within html.
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.Iterator;
import java.util.List;
/**
* Utility to take xml string and convert it to a javascript based tree within html.
*
* @author </p>";
}
private static String convertEjbModule(Document jndiXml)
{
StringBuffer html = new StringBuffer();
Element jndiRoot = jndiXml.getRootElement();
List ejbModules = jndiRoot.elements("ejbmodule");
int globalCounter = 0;
if (ejbModules.size() > 0)
{
html.append(createTreeCommandLinks("ejbTree"));
// create tree and add root node
html.append("<script type=\"text/javascript\">\n<!--\n");
html.append("ejbTree = new dTree("ejbTree");\n");
html.append("ejbTree.add(" + globalCounter++ + ",-1,"EJB Modules");\n");
int parentId = 0;
Iterator itr = ejbModules.iterator();
while (itr.hasNext())
{
Element ejbElm = (Element) itr.next();
String ejbElmName = ejbElm.getName();
//html.append("ejbTree.add(" + globalCounter++ + ", " + parentId + "," + ejbElmName + ");");
html.append(add("ejbTree", globalCounter++, parentId, ejbElmName));
parentId++;
String[] searchNames = new String[]{"context", "leaf"};
globalCounter = buildTree(ejbElm, searchNames, html, globalCounter, parentId, "ejbTree");
}
html.append("document.write(ejbTree);");
html.append("\n//-->\n</script>");
}
return html.toString();
}
private static int buildTree(Element ejbElm, String[] searchNames, StringBuffer html,
int globalCounter, int parentId, String treeName)
{
if (searchNames != null)
{
for (int x = 0; x < searchNames.length; x++)
{
String searchName = searchNames[x];
List contextElms = ejbElm.elements(searchName);
Iterator elmItr = contextElms.iterator();
while (elmItr.hasNext())
{
Element contextElm = (Element) elmItr.next();
String name = "";
String type = "";
String typeValue = "";
// check for context name
Element nameElm = contextElm.element("name");
if (nameElm != null)
{
name = nameElm.getText();
}
Element attrElem = contextElm.element("attribute");
if (attrElem != null)
{
type = attrElem.attributeValue("name");
typeValue = attrElem.getText();
}
//html.append("treeName.add(" + globalCounter++ + ", " + parentId + ", "" + name + " -- " + type + "[" + typeValue + "]");");
html.append(add(treeName, globalCounter++, parentId, name + " -- " + type + "[" + typeValue + "]"));
// now recurse
globalCounter = buildTree(contextElm, searchNames, html, globalCounter, globalCounter - 1, treeName);
}
}
}
return globalCounter;
}
private static String add(String tree, int global, int parent, String name)
{
return tree + ".add(" + global + ", " + parent + ", "" + name + "");\n";
}
public static void main(String[] args)
{
String xml = "<jndi>\n" +
"\t<ejbmodule>\n" +
"\t\t<file>null</file>\n" +
"\t\t<context>\n" +
"\t\t\t<name>java:comp</name>\n" +
"\t\t\t<attribute name=\"bean\">MEJB</attribute>\n" +
"\t\t\t<context>\n" +
"\t\t\t\t<name>env</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t\t<leaf>\n" +
"\t\t\t\t\t<name>Server-Name</name>\n" +
"\t\t\t\t\t<attribute name=\"class\">java.lang.String</attribute>\n" +
"\t\t\t\t</leaf>\n" +
"\t\t\t</context>\n" +
"\t\t</context>\n" +
"\t</ejbmodule>\n" +
"\t<context>\n" +
"\t\t<name>java:</name>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>XAConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyXAConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>DefaultDS</name>\n" +
"\t\t\t<attribute name=\"class\">javax.sql.DataSource</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>SecurityProxyFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.security.SubjectSecurityProxyFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>DefaultJMSProvider</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.jms.jndi.JBossMQProvider</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<context>\n" +
"\t\t\t<name>comp</name>\n" +
"\t\t\t<attribute name=\"class\">javax.naming.Context</attribute>\n" +
"\t\t</context>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>ConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>JmsXA</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.resource.adapter.jms.JmsConnectionFactoryImpl</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<context>\n" +
"\t\t\t<name>jaas</name>\n" +
"\t\t\t<attribute name=\"class\">javax.naming.Context</attribute>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>JmsXARealm</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.security.plugins.SecurityDomainContext</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>jbossmq</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.security.plugins.SecurityDomainContext</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>HsqlDbRealm</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.security.plugins.SecurityDomainContext</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t</context>\n" +
"\t\t<context>\n" +
"\t\t\t<name>timedCacheFactory</name>\n" +
"\t\t\t<attribute name=\"class\">javax.naming.Context</attribute>\n" +
"\t\t\t<error>\n" +
"\t\t\t\t<message>Failed to list contents of: timedCacheFactory, errmsg=null</message>\n" +
"\t\t\t</error>\n" +
"\t\t</context>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>TransactionPropagationContextExporter</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.tm.TransactionPropagationContextFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>Mail</name>\n" +
"\t\t\t<attribute name=\"class\">javax.mail.Session</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>StdJMSPool</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.jms.asf.StdServerSessionPoolFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>TransactionPropagationContextImporter</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.tm.TransactionPropagationContextImporter</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>TransactionManager</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.tm.TxManager</attribute>\n" +
"\t\t</leaf>\n" +
"\t</context>\n" +
"\t<context>\n" +
"\t\t<name>Global</name>\n" +
"\t\t<context>\n" +
"\t\t\t<name>jmx</name>\n" +
"\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t<context>\n" +
"\t\t\t\t<name>invoker</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t\t<leaf>\n" +
"\t\t\t\t\t<name>RMIAdaptor</name>\n" +
"\t\t\t\t\t<attribute name=\"class\">$Proxy38</attribute>\n" +
"\t\t\t\t</leaf>\n" +
"\t\t\t</context>\n" +
"\t\t\t<context>\n" +
"\t\t\t\t<name>rmi</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t\t<link-ref>\n" +
"\t\t\t\t\t<name>RMIAdaptor</name>\n" +
"\t\t\t\t\t<link>jmx/invoker/RMIAdaptor</link>\n" +
"\t\t\t\t\t<attribute name=\"class\">javax.naming.LinkRef</attribute>\n" +
"\t\t\t\t</link-ref>\n" +
"\t\t\t</context>\n" +
"\t\t</context>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>OIL2XAConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyXAConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>HTTPXAConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyXAConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>ConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>UserTransactionSessionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">$Proxy13</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>HTTPConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>XAConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyXAConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<context>\n" +
"\t\t\t<name>invokers</name>\n" +
"\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t<context>\n" +
"\t\t\t\t<name>TCK3</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t\t<leaf>\n" +
"\t\t\t\t\t<name>pooled</name>\n" +
"\t\t\t\t\t<attribute name=\"class\">org.jboss.invocation.pooled.interfaces.PooledInvokerProxy</attribute>\n" +
"\t\t\t\t</leaf>\n" +
"\t\t\t\t<leaf>\n" +
"\t\t\t\t\t<name>jrmp</name>\n" +
"\t\t\t\t\t<attribute name=\"class\">org.jboss.invocation.jrmp.interfaces.JRMPInvokerProxy</attribute>\n" +
"\t\t\t\t</leaf>\n" +
"\t\t\t\t<leaf>\n" +
"\t\t\t\t\t<name>http</name>\n" +
"\t\t\t\t\t<attribute name=\"class\">org.jboss.invocation.http.interfaces.HttpInvokerProxy</attribute>\n" +
"\t\t\t\t</leaf>\n" +
"\t\t\t</context>\n" +
"\t\t</context>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>UserTransaction</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.tm.usertx.client.ClientUserTransaction</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>RMIXAConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyXAConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>UIL2XAConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyXAConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<context>\n" +
"\t\t\t<name>queue</name>\n" +
"\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>A</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyQueue</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>testQueue</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyQueue</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>ex</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyQueue</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>DLQ</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyQueue</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>D</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyQueue</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>C</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyQueue</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>B</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyQueue</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t</context>\n" +
"\t\t<context>\n" +
"\t\t\t<name>topic</name>\n" +
"\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>testDurableTopic</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyTopic</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>testTopic</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyTopic</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>securedTopic</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jboss.mq.SpyTopic</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t</context>\n" +
"\t\t<context>\n" +
"\t\t\t<name>console</name>\n" +
"\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t<leaf>\n" +
"\t\t\t\t<name>PluginManager</name>\n" +
"\t\t\t\t<attribute name=\"class\">$Proxy39</attribute>\n" +
"\t\t\t</leaf>\n" +
"\t\t</context>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>UIL2ConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>HiLoKeyGeneratorFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.ejb.plugins.keygenerator.hilo.HiLoKeyGeneratorFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>RMIConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<context>\n" +
"\t\t\t<name>ejb</name>\n" +
"\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t<context>\n" +
"\t\t\t\t<name>mgmt</name>\n" +
"\t\t\t\t<attribute name=\"class\">org.jnp.interfaces.NamingContext</attribute>\n" +
"\t\t\t\t<leaf>\n" +
"\t\t\t\t\t<name>MEJB</name>\n" +
"\t\t\t\t\t<attribute name=\"class\">$Proxy44</attribute>\n" +
"\t\t\t\t</leaf>\n" +
"\t\t\t</context>\n" +
"\t\t</context>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>OIL2ConnectionFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.mq.SpyConnectionFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t\t<leaf>\n" +
"\t\t\t<name>UUIDKeyGeneratorFactory</name>\n" +
"\t\t\t<attribute name=\"class\">org.jboss.ejb.plugins.keygenerator.uuid.UUIDKeyGeneratorFactory</attribute>\n" +
"\t\t</leaf>\n" +
"\t</context>\n" +
"</jndi>";
String html = null;
try
{
html = XMLToHTMLTreeBuilder.convertJNDIXML(xml);
}
catch (DocumentException e)
{
e.printStackTrace();
}
System.out.println("HTML output:\n\n" + html);
}
}
Variables bound through ScriptEngine
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class BindingDemo {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.put("a", 1);
engine.put("b", 5);
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
Object a = bindings.get("a");
Object b = bindings.get("b");
System.out.println("a = " + a);
System.out.println("b = " + b);
Object result = engine.eval("c = a + b;");
System.out.println("a + b = " + result);
}
}
With Compilable interface you store the intermediate code of an entire script
import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class CompilableDemo {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Compilable jsCompile = (Compilable) engine;
CompiledScript script = jsCompile.rupile("function hi () {print ("www.jexp.ru !"); }; hi ();");
for (int i = 0; i < 5; i++) {
script.eval();
}
}
}
//www.jexp.ru !www.jexp.ru !www.jexp.ru !www.jexp.ru !www.jexp.ru !
Working with Compilable Scripts
import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JDK6TabSample {
public static void main(String args[]) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.put("counter", 0);
if (engine instanceof Compilable) {
Compilable compEngine = (Compilable) engine;
try {
CompiledScript script = compEngine.rupile("function count(){counter=counter+1;return counter;}; count();");
System.out.println(script.eval());
System.out.println(script.eval());
System.out.println(script.eval());
} catch (ScriptException e) {
System.err.println(e);
}
} else {
System.err.println("Engine can"t compile code");
}
}
}
/*1.0
2.0
3.0*/