Java Code Examples for javax.script.ScriptEngine#eval()

The following examples show how to use javax.script.ScriptEngine#eval() . 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: QueryPanel.java    From wandora with GNU General Public License v3.0 6 votes vote down vote up
public static MixedTopicTable getTopicsByQuery(Wandora wandora,String engineName,String scriptStr,Iterator<Topic> contextTopics) throws ScriptException, TopicMapException, Exception {
    TopicMap tm = wandora.getTopicMap();
    WandoraScriptManager sm = new WandoraScriptManager();
    ScriptEngine engine = sm.getScriptEngine(engineName);
    Directive query = null;
    Object o=engine.eval(scriptStr);
    if(o==null) o=engine.get("query");
    if(o!=null && o instanceof Directive) {
        query = (Directive)o;
    }
    
    if(contextTopics==null || !contextTopics.hasNext()){
        // if context is empty just add some (root of a tree chooser) topic
        HashMap<String,TopicTreePanel> trees=wandora.getTopicTreeManager().getTrees();
        TopicTreePanel tree=trees.values().iterator().next();
        Topic t=tm.getTopic(tree.getRootSI());
        ArrayList<Topic> al=new ArrayList<>();
        al.add(t);
        contextTopics=al.iterator();
    }

    return getTopicsByQuery(wandora, wandora.getTopicMap(), query, contextTopics);
}
 
Example 2
Source File: PluggableJSObjectTest.java    From TencentKona-8 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 3
Source File: PluggableJSObjectTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example 4
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 5
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 6
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 7
Source File: TrustedScriptEngineTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void evalFileNameWithSpecialCharsTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine engine = fac.getScriptEngine(new String[] { "--verify-code=true" });
    final ScriptContext ctxt = new SimpleScriptContext();
    // use file name with "dangerous" chars.
    ctxt.setAttribute(ScriptEngine.FILENAME, "<myscript>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var a = 3;");
    ctxt.setAttribute(ScriptEngine.FILENAME, "[myscript]", ScriptContext.ENGINE_SCOPE);
    engine.eval("var h = 'hello';");
    ctxt.setAttribute(ScriptEngine.FILENAME, ";/\\$.", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
    // name used by jjs shell tool for the interactive mode
    ctxt.setAttribute(ScriptEngine.FILENAME, "<shell>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
}
 
Example 8
Source File: ScriptEngineTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void setTimeoutTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Window window = new Window();

    try {
        final Class<?> setTimeoutParamTypes[] = { Window.class, String.class, int.class };
        final Method setTimeout = Window.class.getDeclaredMethod("setTimeout", setTimeoutParamTypes);
        assertNotNull(setTimeout);
        e.put("window", window);
        e.eval("window.setTimeout('foo()', 100)");

        // try to make setTimeout global
        e.put("setTimeout", setTimeout);
        // TODO: java.lang.ClassCastException: required class
        // java.lang.Integer but encountered class java.lang.Double
        // e.eval("setTimeout('foo2()', 200)");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 9
Source File: InvokeScriptMethod.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");

    // 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 !!" );
}
 
Example 10
Source File: TrustedScriptEngineTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Test repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error".
 */
public void noLoaderPerCompilerTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 11
Source File: EvalFile.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    // create a script engine manager
    final ScriptEngineManager factory = new ScriptEngineManager();
    // create JavaScript engine
    final ScriptEngine engine = factory.getEngineByName("nashorn");
    // evaluate JavaScript code from given file - specified by first argument
    engine.eval(new java.io.FileReader(args[0]));
}
 
Example 12
Source File: PluggableJSObjectTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
// ConsString attribute access on a JSObject
public void consStringTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final MapWrapperObject obj = new MapWrapperObject();
        e.put("obj", obj);
        e.put("f", "f");
        e.eval("obj[f + 'oo'] = 'bar';");

        assertEquals(obj.getMap().get("foo"), "bar");
        assertEquals(e.eval("obj[f + 'oo']"), "bar");
        assertEquals(e.eval("obj['foo']"), "bar");
        assertEquals(e.eval("f + 'oo' in obj"), Boolean.TRUE);
        assertEquals(e.eval("'foo' in obj"), Boolean.TRUE);
        e.eval("delete obj[f + 'oo']");
        assertFalse(obj.getMap().containsKey("foo"));
        assertEquals(e.eval("obj[f + 'oo']"), null);
        assertEquals(e.eval("obj['foo']"), null);
        assertEquals(e.eval("f + 'oo' in obj"), Boolean.FALSE);
        assertEquals(e.eval("'foo' in obj"), Boolean.FALSE);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 13
Source File: JDK_8081015_Test.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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 );
}
 
Example 14
Source File: ScriptEngineTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void scriptObjectAutoConversionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    e.eval("obj = { foo: 'hello' }");
    e.put("Window", e.eval("Packages.jdk.nashorn.api.scripting.test.Window"));
    assertEquals(e.eval("Window.funcJSObject(obj)"), "hello");
    assertEquals(e.eval("Window.funcScriptObjectMirror(obj)"), "hello");
    assertEquals(e.eval("Window.funcMap(obj)"), "hello");
    assertEquals(e.eval("Window.funcJSObject(obj)"), "hello");
}
 
Example 15
Source File: EvalFile.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    // create a script engine manager
    final ScriptEngineManager factory = new ScriptEngineManager();
    // create JavaScript engine
    final ScriptEngine engine = factory.getEngineByName("nashorn");
    // evaluate JavaScript code from given file - specified by first argument
    engine.eval(new java.io.FileReader(args[0]));
}
 
Example 16
Source File: InvocableTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void defaultMethodTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Invocable inv = (Invocable) e;

    final Object obj = e.eval("({ apply: function(arg) { return arg.toUpperCase(); }})");
    @SuppressWarnings("unchecked")
    final Function<String, String> func = inv.getInterface(obj, Function.class);
    assertEquals(func.apply("hello"), "HELLO");
}
 
Example 17
Source File: ScriptObjectMirrorTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void topLevelAnonFuncStatement() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine e = engineManager.getEngineByName("nashorn");
    final JSObject func = (JSObject)e.eval("function(x) { return x + ' world' }");
    assertTrue(func.isFunction());
    assertEquals(func.call(e.eval("this"), "hello"), "hello world");
}
 
Example 18
Source File: GraalEnginesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void returnArrayInPython() throws Exception {
    ScriptEngine python = Scripting.createManager().getEngineByMimeType("text/x-python");
    assumeNotNull("Need python", python);
    python.eval("\n"
            + "import math\n"
            + "\n"
            + "def arr(x):\n"
            + "  return [ 1, 2, 'a', math.pi, x ]\n"
            + "\n"
    );

    assertTrue("Engines are invocable: " + python, python instanceof Invocable);
    final Invocable inv = (Invocable)python;

    Sum sum = new Sum();
    Object raw = inv.invokeFunction("arr", sum);

    List<?> list = inv.getInterface(raw, List.class);
    assertNotNull("List " + list, list);
    assertEquals("Length of five", 5, list.size());

    List<?> list2 = inv.getInterface(list, List.class);
    assertNotNull("List 2 " + list2, list2);
    assertEquals("Length 2 of five", 5, list2.size());

    assertEquals(1, list.get(0));
    assertEquals(2, list.get(1));
    assertEquals("a", list.get(2));
    assertEquals(Math.PI, list.get(3));
    assertEquals(sum, list.get(4));
}
 
Example 19
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test
// check that engine.js definitions are visible in all new global instances
public void checkBuiltinsInNewBindingsTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    // check default global instance has engine.js definitions
    final Bindings g = (Bindings) e.eval("this");
    Object value = g.get("__noSuchProperty__");
    assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
    value = g.get("print");
    assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());

    // check new global instance created has engine.js definitions
    final Bindings b = e.createBindings();
    value = b.get("__noSuchProperty__");
    assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
    value = b.get("print");
    assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());

    // put a mapping into GLOBAL_SCOPE
    final Bindings globalScope = e.getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
    globalScope.put("x", "hello");

    // GLOBAL_SCOPE mapping should be visible from default ScriptContext eval
    assertTrue(e.eval("x").equals("hello"));

    final ScriptContext ctx = new SimpleScriptContext();
    ctx.setBindings(globalScope, ScriptContext.GLOBAL_SCOPE);
    ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);

    // GLOBAL_SCOPE mapping should be visible from non-default ScriptContext eval
    assertTrue(e.eval("x", ctx).equals("hello"));

    // try some arbitray Bindings for ENGINE_SCOPE
    final Bindings sb = new SimpleBindings();
    ctx.setBindings(sb, ScriptContext.ENGINE_SCOPE);

    // GLOBAL_SCOPE mapping should be visible from non-default ScriptContext eval
    assertTrue(e.eval("x", ctx).equals("hello"));

    // engine.js builtins are still defined even with arbitrary Bindings
    assertTrue(e.eval("typeof print", ctx).equals("function"));
    assertTrue(e.eval("typeof __noSuchProperty__", ctx).equals("function"));

    // ENGINE_SCOPE definition should 'hide' GLOBAL_SCOPE definition
    sb.put("x", "newX");
    assertTrue(e.eval("x", ctx).equals("newX"));
}
 
Example 20
Source File: ScriptObjectMirrorTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void jsobjectTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        e.eval("var obj = { '1': 'world', func: function() { return this.bar; }, bar: 'hello' }");
        final ScriptObjectMirror obj = (ScriptObjectMirror) e.get("obj");

        // try basic get on existing properties
        if (!obj.getMember("bar").equals("hello")) {
            fail("obj.bar != 'hello'");
        }

        if (!obj.getSlot(1).equals("world")) {
            fail("obj[1] != 'world'");
        }

        if (!obj.callMember("func", new Object[0]).equals("hello")) {
            fail("obj.func() != 'hello'");
        }

        // try setting properties
        obj.setMember("bar", "new-bar");
        obj.setSlot(1, "new-element-1");
        if (!obj.getMember("bar").equals("new-bar")) {
            fail("obj.bar != 'new-bar'");
        }

        if (!obj.getSlot(1).equals("new-element-1")) {
            fail("obj[1] != 'new-element-1'");
        }

        // try adding properties
        obj.setMember("prop", "prop-value");
        obj.setSlot(12, "element-12");
        if (!obj.getMember("prop").equals("prop-value")) {
            fail("obj.prop != 'prop-value'");
        }

        if (!obj.getSlot(12).equals("element-12")) {
            fail("obj[12] != 'element-12'");
        }

        // delete properties
        obj.removeMember("prop");
        if ("prop-value".equals(obj.getMember("prop"))) {
            fail("obj.prop is not deleted!");
        }

        // Simple eval tests
        assertEquals(obj.eval("typeof Object"), "function");
        assertEquals(obj.eval("'nashorn'.substring(3)"), "horn");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}