javax.script.ScriptEngineManager Java Examples

The following examples show how to use javax.script.ScriptEngineManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiScopes.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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"
}
 
Example #2
Source File: PluggableJSObjectTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #3
Source File: PluggableJSObjectTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@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);
        }
    });
}
 
Example #4
Source File: MultiScopes.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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"
}
 
Example #5
Source File: TrustedScriptEngineTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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!");
}
 
Example #6
Source File: InvocableTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #7
Source File: ScriptEngineTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #8
Source File: InvocableTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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());
        }
    }
}
 
Example #9
Source File: InvocableTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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]");
}
 
Example #10
Source File: InvocableTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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());
        }
    }
}
 
Example #11
Source File: RunnableImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #12
Source File: ScriptEngineSecurityTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@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());
        }
    }
}
 
Example #13
Source File: ScriptEngineTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #14
Source File: ScopeTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@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"));
}
 
Example #15
Source File: InvocableTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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());
        }
    }
}
 
Example #16
Source File: ClusterSelectorManagedScriptIntegrationTest.java    From genie with Apache License 2.0 6 votes vote down vote up
@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
    );
}
 
Example #17
Source File: ScriptEngineTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #18
Source File: InvocableTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@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());
        }
    }
}
 
Example #19
Source File: PluggableJSObjectTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #20
Source File: RNPathUtilTest.java    From react-native-console with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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();
        }
    }
 
Example #21
Source File: InvocableTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #22
Source File: ScriptRouter.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #23
Source File: RunScript.java    From common_gui_tools with Apache License 2.0 6 votes vote down vote up
/**
 * 支持的脚本类型.
 */
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;
}
 
Example #24
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void userEngineScopeBindingsTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    e.eval("function func() {}");

    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    // we are using a new bindings - so it should have 'func' defined
    final Object value = e.eval("typeof func", newContext);
    assertTrue(value.equals("undefined"));
}
 
Example #25
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #26
Source File: Test1.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("\nTest1\n");
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine jsengine = Helper.getJsEngine(manager);
    if (jsengine == null) {
             System.out.println("Warning: No js engine found; test vacuously passes.");
             return;
    }
    jsengine.eval(new FileReader(
             new File(System.getProperty("test.src", "."), "Test1.js")));
}
 
Example #27
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public static void contextOverwriteTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = new SimpleBindings();
    b.put("context", "hello");
    b.put("foo", 32);
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    e.setContext(newCtxt);
    assertEquals(e.eval("context"), "hello");
    assertEquals(((Number)e.eval("foo")).intValue(), 32);
}
 
Example #28
Source File: ScriptObjectMirrorTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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")));
}
 
Example #29
Source File: ScriptEngineTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #30
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test multi-threaded access to defined global variables for shared script classes with multiple globals.
 */
@Test
public static void multiThreadedVarTest() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    final ScriptContext origContext = e.getContext();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    final String sharedScript = "foo";

    assertEquals(e.eval("var foo = 'original context';", origContext), null);
    assertEquals(e.eval("var foo = 'new context';", newCtxt), null);

    final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
    t1.start();
    t2.start();
    t1.join();
    t2.join();

    assertEquals(e.eval("var foo = 'newer context';", newCtxt), null);
    final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));

    t3.start();
    t4.start();
    t3.join();
    t4.join();

    assertEquals(e.eval(sharedScript), "original context");
    assertEquals(e.eval(sharedScript, newCtxt), "newer context");
}