下面列出了javax.script.AbstractScriptEngine#javax.script.ScriptEngine 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
/**
* Check that getInterface on non-script object 'thiz' results in
* IllegalArgumentException.
*/
public void getInterfaceNonScriptObjectThizTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
try {
((Invocable) e).getInterface(new Object(), Runnable.class);
fail("should have thrown IllegalArgumentException");
} catch (final Exception exp) {
if (!(exp instanceof IllegalArgumentException)) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
}
@Test
public void fakeProxySubclassAccessCheckTest2() throws ScriptException {
if (System.getSecurityManager() == null) {
// pass vacuously
return;
}
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
e.put("name", ScriptEngineSecurityTest.class.getName());
e.put("cl", ScriptEngineSecurityTest.class.getClassLoader());
e.put("intfs", new Class[] { Runnable.class });
String getClass = "Java.type(name + '$FakeProxy').makeProxyClass(cl, intfs);";
// Should not be able to call static methods of Proxy via fake subclass
try {
Class c = (Class)e.eval(getClass);
fail("should have thrown SecurityException");
} catch (final Exception exp) {
if (! (exp instanceof SecurityException)) {
fail("SecurityException expected, got " + exp);
}
}
}
@Test
public void functionalInterfaceObjectTest() throws Exception {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine e = manager.getEngineByName("nashorn");
final AtomicBoolean invoked = new AtomicBoolean(false);
e.put("c", new Consumer<Object>() {
@Override
public void accept(Object t) {
assertTrue(t instanceof ScriptObjectMirror);
assertEquals(((ScriptObjectMirror)t).get("a"), "xyz");
invoked.set(true);
}
});
e.eval("var x = 'xy'; x += 'z';c({a:x})");
assertTrue(invoked.get());
}
@Test
public void currentGlobalMissingTest() throws Exception {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine e = manager.getEngineByName("nashorn");
final Context ctx = new Context();
e.put("ctx", ctx);
e.eval("var obj = { foo: function(str) { return str.toUpperCase() } }");
e.eval("ctx.set(obj)");
final Invocable inv = (Invocable)e;
assertEquals("HELLO", inv.invokeMethod(ctx.get(), "foo", "hello"));
// try object literal
e.eval("ctx.set({ bar: function(str) { return str.toLowerCase() } })");
assertEquals("hello", inv.invokeMethod(ctx.get(), "bar", "HELLO"));
// try array literal
e.eval("var arr = [ 'hello', 'world' ]");
e.eval("ctx.set(arr)");
assertEquals("helloworld", inv.invokeMethod(ctx.get(), "join", ""));
}
@Test
// a factory JSObject
public void factoryJSObjectTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
try {
e.put("Factory", new Factory());
// check new on Factory
assertEquals(e.eval("typeof Factory"), "function");
assertEquals(e.eval("typeof new Factory()"), "object");
assertEquals(e.eval("(new Factory()) instanceof java.util.Map"), Boolean.TRUE);
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
@Test
/**
* Check that we can get interface out of a script object even after
* switching to use different ScriptContext.
*/
public void getInterfaceDifferentContext() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
try {
final Object obj = e.eval("({ run: function() { } })");
// change script context
final ScriptContext ctxt = new SimpleScriptContext();
ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
e.setContext(ctxt);
final Runnable r = ((Invocable) e).getInterface(obj, Runnable.class);
r.run();
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
@Test
public void indexPropertiesExternalBufferTest() throws ScriptException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
final ScriptObjectMirror obj = (ScriptObjectMirror)e.eval("var obj = {}; obj");
final ByteBuffer buf = ByteBuffer.allocate(5);
int i;
for (i = 0; i < 5; i++) {
buf.put(i, (byte)(i+10));
}
obj.setIndexedPropertiesToExternalArrayData(buf);
for (i = 0; i < 5; i++) {
assertEquals((byte)(i+10), ((Number)e.eval("obj[" + i + "]")).byteValue());
}
e.eval("for (i = 0; i < 5; i++) obj[i] = 0");
for (i = 0; i < 5; i++) {
assertEquals((byte)0, ((Number)e.eval("obj[" + i + "]")).byteValue());
assertEquals((byte)0, buf.get(i));
}
}
public static void main(final String[] args) throws Exception {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("nashorn");
// JavaScript code in a String. This code defines a script object 'obj'
// with one method called 'hello'.
final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
// evaluate script
engine.eval(script);
// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
final Invocable inv = (Invocable) engine;
// get script object on which we want to call the method
final Object obj = engine.get("obj");
// invoke the method named "hello" on the script object "obj"
inv.invokeMethod(obj, "hello", "Script Method !!" );
}
public Object evaluate(String expression, Map<String, Object> bindings)
throws ExecutionException {
try {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
if (engine == null)
engine = factory.getEngineByName("Rhino JavaScript"); // ServiceMix
for (String bindName : bindings.keySet()) {
engine.put(bindName, bindings.get(bindName));
}
return engine.eval(expression);
}
catch (ScriptException ex) {
throw new ExecutionException("Error executing JavaScript: " + ex.getMessage(), ex);
}
}
public static void main(final String[] args) throws Exception {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("nashorn");
// JavaScript code in a String. This code defines a script object 'obj'
// with one method called 'hello'.
final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
// evaluate script
engine.eval(script);
// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
final Invocable inv = (Invocable) engine;
// get script object on which we want to call the method
final Object obj = engine.get("obj");
// invoke the method named "hello" on the script object "obj"
inv.invokeMethod(obj, "hello", "Script Method !!" );
}
@Test
public void fakeProxySubclassAccessCheckTest() {
if (System.getSecurityManager() == null) {
// pass vacuously
return;
}
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
e.put("name", ScriptEngineSecurityTest.class.getName());
e.put("cl", ScriptEngineSecurityTest.class.getClassLoader());
e.put("intfs", new Class[] { Runnable.class });
final String getClass = "Java.type(name + '$FakeProxy').getProxyClass(cl, intfs);";
// Should not be able to call static methods of Proxy via fake subclass
try {
e.eval(getClass);
fail("should have thrown SecurityException");
} catch (final Exception exp) {
if (! (exp instanceof SecurityException)) {
fail("SecurityException expected, got " + exp);
}
}
}
public Object getParameter(String key) {
if (ScriptEngine.NAME.equals(key)) {
return SHORT_NAME;
} else if (ScriptEngine.ENGINE.equals(key)) {
return getEngineName();
} else if (ScriptEngine.ENGINE_VERSION.equals(key)) {
return VERSION;
} else if (ScriptEngine.LANGUAGE.equals(key)) {
return LANGUAGE_NAME;
} else if (ScriptEngine.LANGUAGE_VERSION.equals(key)) {
return GroovySystem.getVersion();
} else if ("THREADING".equals(key)) {
return "MULTITHREADED";
} else {
throw new IllegalArgumentException("Invalid key");
}
}
public static Object getNextWorkingDay( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
// (Date dIn){
if ( ArgList.length == 1 ) {
try {
if ( isNull( ArgList[ 0 ] ) ) {
return null;
} else if ( isUndefined( ArgList[ 0 ] ) ) {
return undefinedValue;
}
java.util.Date dIn = (java.util.Date) ArgList[ 0 ];
Calendar startDate = Calendar.getInstance();
startDate.setTime( dIn );
startDate.add( Calendar.DATE, 1 );
while ( startDate.get( Calendar.DAY_OF_WEEK ) == Calendar.SATURDAY
|| startDate.get( Calendar.DAY_OF_WEEK ) == Calendar.SUNDAY ) {
startDate.add( Calendar.DATE, 1 );
}
return startDate.getTime();
} catch ( Exception e ) {
throw new RuntimeException( e.toString() );
}
} else {
throw new RuntimeException( "The function call getNextWorkingDay requires 1 argument." );
}
}
/**
* Ensure that the old behaviour (every object is a Map) is unchanged.
*/
@Test
public void testNonWrapping() throws ScriptException {
final ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine();
final Object val = engine.eval("({x: [1, {y: [2, {z: [3]}]}, [4, 5]]})");
final Map<String, Object> root = asMap(val);
final Map<String, Object> x = asMap(root.get("x"));
assertEquals(x.get("0"), 1);
final Map<String, Object> x1 = asMap(x.get("1"));
final Map<String, Object> y = asMap(x1.get("y"));
assertEquals(y.get("0"), 2);
final Map<String, Object> y1 = asMap(y.get("1"));
final Map<String, Object> z = asMap(y1.get("z"));
assertEquals(z.get("0"), 3);
final Map<String, Object> x2 = asMap(x.get("2"));
assertEquals(x2.get("0"), 4);
assertEquals(x2.get("1"), 5);
}
public static String rtrim( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
try {
if ( ArgList.length == 1 ) {
if ( isNull( ArgList[ 0 ] ) ) {
return null;
} else if ( isUndefined( ArgList[ 0 ] ) ) {
return (String) undefinedValue;
}
String strValueToTrim = (String) ArgList[ 0 ];
return strValueToTrim.replaceAll( "\\s+$", "" );
} else {
throw new RuntimeException( "The function call rtrim requires 1 argument." );
}
} catch ( Exception e ) {
throw new RuntimeException( "The function call rtrim is not valid : " + e.getMessage() );
}
}
@Test
// a factory JSObject
public void factoryJSObjectTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
try {
e.put("Factory", new Factory());
// check new on Factory
assertEquals(e.eval("typeof Factory"), "function");
assertEquals(e.eval("typeof new Factory()"), "object");
assertEquals(e.eval("(new Factory()) instanceof java.util.Map"), Boolean.TRUE);
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
@Test
public void windowItemTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
final Window window = new Window();
try {
e.put("window", window);
final String item1 = (String)e.eval("window.item(65535)");
assertEquals(item1, "ffff");
final String item2 = (String)e.eval("window.item(255)");
assertEquals(item2, "ff");
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
public static Object isNum( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
if ( ArgList.length == 1 ) {
try {
if ( isNull( ArgList[0] ) ) {
return null;
} else if ( isUndefined( ArgList[0] ) ) {
return undefinedValue;
}
double sArg1 = (Double) ArgList[0];
if ( Double.isNaN( sArg1 ) ) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
} catch ( Exception e ) {
return Boolean.FALSE;
}
} else {
throw new RuntimeException( "The function call isNum requires 1 argument." );
}
}
protected ScriptEngine getEngine() {
if (Boolean.FALSE.equals(this.sharedEngine)) {
Map<Object, ScriptEngine> engines = enginesHolder.get();
if (engines == null) {
engines = new HashMap<Object, ScriptEngine>(4);
enginesHolder.set(engines);
}
Object engineKey = (!ObjectUtils.isEmpty(this.scripts) ?
new EngineKey(this.engineName, this.scripts) : this.engineName);
ScriptEngine engine = engines.get(engineKey);
if (engine == null) {
engine = createEngineFromName();
engines.put(engineKey, engine);
}
return engine;
}
else {
// Simply return the configured ScriptEngine...
return this.engine;
}
}
@Test
/**
* Check that calling getInterface on mirror created by another engine
* results in IllegalArgumentException.
*/
public void getInterfaceMixEnginesTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine engine1 = m.getEngineByName("nashorn");
final ScriptEngine engine2 = m.getEngineByName("nashorn");
try {
final Object obj = engine1.eval("({ run: function() {} })");
// pass object from engine1 to engine2 as 'thiz' for getInterface
((Invocable) engine2).getInterface(obj, Runnable.class);
fail("should have thrown IllegalArgumentException");
} catch (final Exception exp) {
if (!(exp instanceof IllegalArgumentException)) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
}
public static void main(final String[] args) throws Exception {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("nashorn");
// JavaScript code in a String
final String script = "function run() { print('run called'); }";
// evaluate script
engine.eval(script);
final Invocable inv = (Invocable) engine;
// get Runnable interface object from engine. This interface methods
// are implemented by script functions with the matching name.
final Runnable r = inv.getInterface(Runnable.class);
// start a new thread that runs the script implemented
// runnable interface
final Thread th = new Thread(r);
th.start();
th.join();
}
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// create an engine and a ScriptContext, but don't set it as default
final ScriptContext scriptContext = new SimpleScriptContext();
// Set some value in the context
scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);
// Evaluate script with custom context and get back a function
final String script = "function (c) { return myString.indexOf(c); }";
final CompiledScript compiledScript = ((Compilable)engine).compile(script);
final Object func = compiledScript.eval(scriptContext);
// Invoked function should be able to see context it was evaluated with
final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
assertTrue(((Number)result).intValue() == 1);
}
@Test
public void classFilterTest2() throws ScriptException {
final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
final ScriptEngine e = fac.getScriptEngine(new String[0], Thread.currentThread().getContextClassLoader(),
new ClassFilter() {
@Override
public boolean exposeToScripts(final String fullName) {
// don't allow anything that is not "java."
return fullName.startsWith("java.");
}
});
assertEquals(e.eval("typeof javax.script.ScriptEngine"), "object");
assertEquals(e.eval("typeof java.util.Vector"), "function");
try {
e.eval("Java.type('javax.script.ScriptContext')");
fail("should not reach here");
} catch (final ScriptException | RuntimeException se) {
if (! (se.getCause() instanceof ClassNotFoundException)) {
fail("ClassNotFoundException expected");
}
}
}
/**
* Initialize given global scope object.
*
* @param global the global
* @param engine the associated ScriptEngine instance, can be null
* @return the initialized global scope object.
*/
public Global initGlobal(final Global global, final ScriptEngine engine) {
// Need only minimal global object, if we are just compiling.
if (!env._compile_only) {
final Global oldGlobal = Context.getGlobal();
try {
Context.setGlobal(global);
// initialize global scope with builtin global objects
global.initBuiltinObjects(engine);
} finally {
Context.setGlobal(oldGlobal);
}
}
return global;
}
@Test
public void argumentsWithTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
String[] args = new String[] { "hello", "world" };
try {
e.put("arguments", args);
Object arg0 = e.eval("var imports = new JavaImporter(java.io); " +
" with(imports) { arguments[0] }");
Object arg1 = e.eval("var imports = new JavaImporter(java.util, java.io); " +
" with(imports) { arguments[1] }");
assertEquals(args[0], arg0);
assertEquals(args[1], arg1);
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
@Test
// iteration tests
public void iteratingJSObjectTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
try {
final MapWrapperObject obj = new MapWrapperObject();
obj.setMember("foo", "hello");
obj.setMember("bar", "world");
e.put("obj", obj);
// check for..in
Object val = e.eval("var str = ''; for (i in obj) str += i; str");
assertEquals(val.toString(), "foobar");
// check for..each..in
val = e.eval("var str = ''; for each (i in obj) str += i; str");
assertEquals(val.toString(), "helloworld");
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
@Test
/**
* Check that calling getInterface on mirror created by another engine
* results in IllegalArgumentException.
*/
public void getInterfaceMixEnginesTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine engine1 = m.getEngineByName("nashorn");
final ScriptEngine engine2 = m.getEngineByName("nashorn");
try {
final Object obj = engine1.eval("({ run: function() {} })");
// pass object from engine1 to engine2 as 'thiz' for getInterface
((Invocable) engine2).getInterface(obj, Runnable.class);
fail("should have thrown IllegalArgumentException");
} catch (final Exception exp) {
if (!(exp instanceof IllegalArgumentException)) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
}
/**
* Executes a compiled script and returns the result.
*
* @param script Compiled script.
* @param functionName Optional function or method to invoke.
* @param scriptContext Script execution context.
* @return The script result.
* @throws IllegalArgumentException
*/
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
Assert.notNull("script", script, "scriptContext", scriptContext);
Object result = script.eval(scriptContext);
if (UtilValidate.isNotEmpty(functionName)) {
if (Debug.verboseOn()) {
Debug.logVerbose("Invoking function/method " + functionName, module);
}
ScriptEngine engine = script.getEngine();
try {
Invocable invocableEngine = (Invocable) engine;
result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
} catch (ClassCastException e) {
throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
}
}
return result;
}
public static String resolveIP( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
String sRC = "";
if ( ArgList.length == 2 ) {
try {
InetAddress addr = InetAddress.getByName( (String) ArgList[ 0 ] );
if ( ( (String) ArgList[ 1 ] ).equals( "IP" ) ) {
sRC = addr.getHostName();
} else {
sRC = addr.getHostAddress();
}
if ( sRC.equals( ArgList[ 0 ] ) ) {
sRC = "-";
}
} catch ( Exception e ) {
sRC = "-";
}
} else {
throw new RuntimeException( "The function call resolveIP requires 2 arguments." );
}
return sRC;
}
private static void test(final String methodName) throws ScriptException {
final ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine();
final JDK_8081015_TestModel model = new JDK_8081015_TestModel();
engine.put("test", model);
assertNull(model.getLastInvoked());
engine.eval("test." + methodName + "([1, 2, 3.3, 'foo'])");
assertEquals(model.getLastInvoked(), methodName );
}