javax.script.ScriptEngineManager源码实例Demo

类javax.script.ScriptEngineManager源码实例Demo

下面列出了javax.script.ScriptEngineManager 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-jdk8u   文件: InvocableTest.java
@Test
/**
 * Check that calling method on null 'thiz' results in
 * IllegalArgumentException.
 */
public void invokeMethodNullThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).invokeMethod(null, "toString");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
源代码2 项目: hottub   文件: MultiScopes.java
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}
 
源代码3 项目: jdk8u_nashorn   文件: PluggableJSObjectTest.java
@Test
public void hidingInternalObjectsForJSObjectTest() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine e = engineManager.getEngineByName("nashorn");

    final String code = "function func(obj) { obj.foo = [5, 5]; obj.bar = {} }";
    e.eval(code);

    // call the exposed function but pass user defined JSObject impl as argument
    ((Invocable)e).invokeFunction("func", new AbstractJSObject() {
        @Override
        public void setMember(final String name, final Object value) {
            // make sure that wrapped objects are passed (and not internal impl. objects)
            assertTrue(value.getClass() == ScriptObjectMirror.class);
        }
    });
}
 
源代码4 项目: openjdk-jdk8u   文件: PluggableJSObjectTest.java
@Test
// Named property access on a JSObject
public void namedAccessTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final MapWrapperObject obj = new MapWrapperObject();
        e.put("obj", obj);
        obj.getMap().put("foo", "bar");

        // property-like access on MapWrapperObject objects
        assertEquals(e.eval("obj.foo"), "bar");
        e.eval("obj.foo = 'hello'");
        assertEquals(e.eval("'foo' in obj"), Boolean.TRUE);
        assertEquals(e.eval("obj.foo"), "hello");
        assertEquals(obj.getMap().get("foo"), "hello");
        e.eval("delete obj.foo");
        assertFalse(obj.getMap().containsKey("foo"));
        assertEquals(e.eval("'foo' in obj"), Boolean.FALSE);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
源代码5 项目: openjdk-jdk9   文件: TrustedScriptEngineTest.java
@Test
public void factoryClassLoaderTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final MyClassLoader loader = new MyClassLoader();
            // set the classloader as app class loader
            final ScriptEngine e = nfac.getScriptEngine(loader);
            try {
                e.eval("Packages.foo");
                // check that the class loader was attempted
                assertTrue(loader.reached(), "did not reach class loader!");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
源代码6 项目: openjdk-jdk9   文件: InvocableTest.java
@Test
/**
 * Check that we can call invokeMethod on an object that we got by
 * evaluating script with different Context set.
 */
public void invokeMethodDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })");

        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        // invoke 'func' on obj - but with current script context changed
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
源代码7 项目: jdk8u_nashorn   文件: ScriptEngineTest.java
@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());
    }
}
 
源代码8 项目: jdk8u60   文件: InvocableTest.java
@Test
/**
 * Check that calling method on non-script object 'thiz' results in
 * IllegalArgumentException.
 */
public void invokeMethodNonScriptObjectThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).invokeMethod(new Object(), "toString");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
源代码9 项目: openjdk-jdk8u-backup   文件: InvocableTest.java
@Test
/**
 * Tests whether invocation of a JavaScript method through a variable arity
 * Java method will pass the vararg array. Both non-vararg and vararg
 * JavaScript methods are tested.
 *
 * @throws ScriptException
 */
public void variableArityInterfaceTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    e.eval(
            "function test1(i, strings) {"
            + "    return 'i == ' + i + ', strings instanceof java.lang.String[] == ' + (strings instanceof Java.type('java.lang.String[]')) + ', strings == ' + java.util.Arrays.toString(strings)"
            + "}"
            + "function test2() {"
            + "    return 'arguments[0] == ' + arguments[0] + ', arguments[1] instanceof java.lang.String[] == ' + (arguments[1] instanceof Java.type('java.lang.String[]')) + ', arguments[1] == ' + java.util.Arrays.toString(arguments[1])"
            + "}");
    final VariableArityTestInterface itf = ((Invocable) e).getInterface(VariableArityTestInterface.class);
    Assert.assertEquals(itf.test1(42, "a", "b"), "i == 42, strings instanceof java.lang.String[] == true, strings == [a, b]");
    Assert.assertEquals(itf.test2(44, "c", "d", "e"), "arguments[0] == 44, arguments[1] instanceof java.lang.String[] == true, arguments[1] == [c, d, e]");
}
 
源代码10 项目: jdk8u60   文件: InvocableTest.java
@Test
/**
 * Check that invokeMethod throws NPE on null method name.
 */
public void invokeMethodNullNameTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, null);
        fail("should have thrown NPE");
    } catch (final Exception exp) {
        if (!(exp instanceof NullPointerException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
源代码11 项目: openjdk-jdk8u   文件: RunnableImpl.java
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();
}
 
源代码12 项目: hottub   文件: ScriptEngineSecurityTest.java
@Test
public void securitySystemLoadLibrary() {
    if (System.getSecurityManager() == null) {
        // pass vacuously
        return;
    }

    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        e.eval("java.lang.System.loadLibrary('foo');");
        fail("should have thrown SecurityException");
    } catch (final Exception exp) {
        if (exp instanceof SecurityException) {
            log("got " + exp + " as expected");
        } else {
            fail(exp.getMessage());
        }
    }
}
 
源代码13 项目: openjdk-8-source   文件: ScriptEngineTest.java
@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());
    }
}
 
源代码14 项目: openjdk-jdk8u   文件: ScopeTest.java
/**
 * Test "slow" scopes involving {@code with} and {@code eval} statements for shared script classes with multiple globals.
 * @throws ScriptException
 * @throws InterruptedException
 */
@Test
public static void testSlowScope() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    for (int i = 0; i < 100; i++) {
        final Bindings b = e.createBindings();
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

        e.eval(new URLReader(ScopeTest.class.getResource("resources/witheval.js")), ctxt);
        assertEquals(e.eval("a", ctxt), 1);
        assertEquals(b.get("a"), 1);
        assertEquals(e.eval("b", ctxt), 3);
        assertEquals(b.get("b"), 3);
        assertEquals(e.eval("c", ctxt), 10);
        assertEquals(b.get("c"), 10);
    }
}
 
源代码15 项目: openjdk-8-source   文件: ScopeTest.java
@Test
public void userEngineScopeBindingsRetentionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // definition retained with user's ENGINE_SCOPE Binding
    assertTrue(e.eval("typeof foo", newContext).equals("function"));

    final Bindings oldBindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
    // but not in another ENGINE_SCOPE binding
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("undefined"));

    // restore ENGINE_SCOPE and check again
    newContext.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("function"));
}
 
源代码16 项目: common_gui_tools   文件: RunScript.java
/**
 * 支持的脚本类型.
 */
private String[] getScriptTypes() {
    ScriptEngineManager sem = new ScriptEngineManager();
    List<ScriptEngineFactory> factorys = sem.getEngineFactories();
    Set<String> languages = new LinkedHashSet<String>();
    for (ScriptEngineFactory factory : factorys) {
        languages.add(factory.getLanguageName());
    }
    String[] types = new String[languages.size()];
    int i = 0;
    for (String name : languages) {
        types[i] = name;
        i++;
    }
    return types;
}
 
源代码17 项目: dubbox-hystrix   文件: ScriptRouter.java
public ScriptRouter(URL url) {
    this.url = url;
    String type = url.getParameter(Constants.TYPE_KEY);
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
    if (type == null || type.length() == 0){
        type = Constants.DEFAULT_SCRIPT_TYPE_KEY;
    }
    if (rule == null || rule.length() == 0){
        throw new IllegalStateException(new IllegalStateException("route rule can not be empty. rule:" + rule));
    }
    ScriptEngine engine = engines.get(type);
    if (engine == null){
        engine = new ScriptEngineManager().getEngineByName(type);
        if (engine == null) {
            throw new IllegalStateException(new IllegalStateException("Unsupported route rule type: " + type + ", rule: " + rule));
        }
        engines.put(type, engine);
    }
    this.engine = engine;
    this.rule = rule;
}
 
源代码18 项目: jdk8u60   文件: InvocableTest.java
@Test
/**
 * Try passing non-interface Class object for interface implementation.
 */
public void getNonInterfaceGetInterfaceTest() {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");
    try {
        log(Objects.toString(((Invocable) engine).getInterface(Object.class)));
        fail("Should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            fail("IllegalArgumentException expected, got " + exp);
        }
    }
}
 
源代码19 项目: react-native-console   文件: RNPathUtilTest.java
@Test
    public void testJS() {
        // https://stackoverflow.com/questions/22492641/java8-js-nashorn-convert-array-to-java-array
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        try {
            engine.put("line", "刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]");
//            engine.put("regex", )
            String regex = "/(.*?) \\((.*?)\\) \\[(.*?)\\]/";
            String[] value = (String[])engine.eval("Java.to(line.match(" + regex + "),\"java.lang.String[]\" );");
            System.out.println(value.length);
            System.out.println(value[1]);
            String[] result = {"刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]",
                    "刘长炯 微信号weblogic", "10.3.2", "46a5432f8fdea99a6186a927e8da5db7a51854ac"};
            Assert.assertArrayEquals("result shold match", result, value);
//            Collection<Object> val = value.values();
//            if(value.isArray()) {
//                System.out.println(value.getMember("1"));
//            }
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
 
@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());
    }
}
 
源代码21 项目: TencentKona-8   文件: InvocableTest.java
@Test
/**
 * Check that invokeMethod throws NPE on null method name.
 */
public void invokeMethodNullNameTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, null);
        fail("should have thrown NPE");
    } catch (final Exception exp) {
        if (!(exp instanceof NullPointerException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
源代码22 项目: hottub   文件: ScriptEngineTest.java
@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());
    }
}
 
@BeforeEach
void setUp() {
    final MeterRegistry meterRegistry = new SimpleMeterRegistry();
    final ScriptManagerProperties scriptManagerProperties = new ScriptManagerProperties();
    final TaskScheduler taskScheduler = new ConcurrentTaskScheduler();
    final ExecutorService executorService = Executors.newCachedThreadPool();
    final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    final ResourceLoader resourceLoader = new DefaultResourceLoader();
    final ScriptManager scriptManager = new ScriptManager(
        scriptManagerProperties,
        taskScheduler,
        executorService,
        scriptEngineManager,
        resourceLoader,
        meterRegistry
    );
    this.scriptProperties = new ClusterSelectorScriptProperties();
    this.clusterSelectorScript = new ClusterSelectorManagedScript(
        scriptManager,
        this.scriptProperties,
        meterRegistry
    );
}
 
源代码24 项目: openjdk-jdk8u-backup   文件: MultiScopes.java
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}
 
源代码25 项目: openjdk-jdk8u-backup   文件: ScriptEngineTest.java
@Test
public void refErrorForUndeclaredAccessTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        e.eval("try { print(foo); throw 'no ref error' } catch (e) { if (!(e instanceof ReferenceError)) throw e; }");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
源代码26 项目: ATest   文件: JavaScriptFunction.java
public String jsFunction(String jsStr) {
	ScriptEngineManager manager = new ScriptEngineManager();
	ScriptEngine engine = manager.getEngineByName("Nashorn");
	try {
		return (String) engine.eval(jsStr);
	} catch (ScriptException e) {
		return "";
	}
}
 
源代码27 项目: jdk8u_nashorn   文件: ScriptObjectMirrorTest.java
@Test
public void checkThisForJSObjectEval() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine e = engineManager.getEngineByName("nashorn");
    final JSObject jsobj = (JSObject)e.eval("({foo: 23, bar: 'hello' })");
    assertEquals(((Number)jsobj.eval("this.foo")).intValue(), 23);
    assertEquals(jsobj.eval("this.bar"), "hello");
    assertEquals(jsobj.eval("String(this)"), "[object Object]");
    final Object global = e.eval("this");
    assertFalse(global.equals(jsobj.eval("this")));
}
 
源代码28 项目: openjdk-8-source   文件: ScriptEngineTest.java
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
源代码29 项目: spring4-understanding   文件: ScriptTemplateView.java
protected ScriptEngine createEngineFromName() {
	if (this.scriptEngineManager == null) {
		this.scriptEngineManager = new ScriptEngineManager(getApplicationContext().getClassLoader());
	}

	ScriptEngine engine = StandardScriptUtils.retrieveEngineByName(this.scriptEngineManager, this.engineName);
	loadScripts(engine);
	return engine;
}
 
源代码30 项目: openjdk-jdk9   文件: ScriptEngineTest.java
@Test
public void accessGlobalTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.eval("var x = 'hello'");
        assertEquals(e.get("x"), "hello");
    } catch (final ScriptException exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}