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

The following examples show how to use javax.script.ScriptEngine#put() . 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: ScriptEngineTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void argumentsTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    final String[] args = new String[] { "hello", "world" };
    try {
        e.put("arguments", args);
        final Object arg0 = e.eval("arguments[0]");
        final Object arg1 = e.eval("arguments[1]");
        assertEquals(args[0], arg0);
        assertEquals(args[1], arg1);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 2
Source File: ScriptEngineTest.java    From hottub 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 3
Source File: PluggableJSObjectTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
// array-like indexed access for a JSObject
public void indexedAccessTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final BufferObject buf = new BufferObject(2);
        e.put("buf", buf);

        // array-like access on BufferObject objects
        assertEquals(e.eval("buf.length"), buf.getBuffer().capacity());
        e.eval("buf[0] = 23");
        assertEquals(buf.getBuffer().get(0), 23);
        assertEquals(e.eval("buf[0]"), 23);
        assertEquals(e.eval("buf[1]"), 0);
        buf.getBuffer().put(1, 42);
        assertEquals(e.eval("buf[1]"), 42);
        assertEquals(e.eval("Array.isArray(buf)"), Boolean.TRUE);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 4
Source File: ScriptEngineTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void argumentsTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    final String[] args = new String[] { "hello", "world" };
    try {
        e.put("arguments", args);
        final Object arg0 = e.eval("arguments[0]");
        final Object arg1 = e.eval("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 openjdk-jdk8u 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: ScriptEngineTest.java    From openjdk-jdk8u-backup 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 7
Source File: ScriptEngineTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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", ""));
}
 
Example 8
Source File: PluggableJSObjectTest.java    From openjdk-8 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 9
Source File: MainTestCase.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void check(ScriptEngine scriptEngine, String evalString, String expectedResult, int resultLength) {
	try {
		if (evalString.length() == 0 && expectedResult.length() == 0) {
			return;
		}
		// scriptEngine.put("STEPWISE",Boolean.TRUE);
		scriptEngine.put("RELAXED_SYNTAX", Boolean.TRUE);
		scriptEngine.put("ENABLE_HISTORY", Boolean.TRUE);

		String evaledResult = (String) scriptEngine.eval(evalString);

		assertEquals(expectedResult, evaledResult);
	} catch (Exception e) {
		e.printStackTrace();
		assertEquals(e.getMessage(), "");
	}
}
 
Example 10
Source File: ScriptExecutor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Construct a new script executors
 *
 * @param engine
 *            the script engine to use, must not be <code>null</code>
 * @param command
 *            the command to execute, may be <code>null</code>
 * @param classLoader
 *            the class loader to use when executing, may be
 *            <code>null</code>
 * @throws ScriptException
 */
public ScriptExecutor ( final ScriptEngine engine, final String command, final ClassLoader classLoader, final String sourceName ) throws Exception
{
    this.engine = engine;
    this.command = command;
    this.commandUrl = null;
    this.classLoader = classLoader;
    this.sourceName = sourceName;

    if ( command != null && engine instanceof Compilable && !Boolean.getBoolean ( PROP_NAME_DISABLE_COMPILE ) )
    {
        if ( sourceName != null )
        {
            engine.put ( ScriptEngine.FILENAME, sourceName );
        }

        Scripts.executeWithClassLoader ( classLoader, new Callable<Void> () {
            @Override
            public Void call () throws Exception
            {
                ScriptExecutor.this.compiledScript = ( (Compilable)engine ).compile ( command );
                return null;
            }
        } );
    }
}
 
Example 11
Source File: JavaAdapterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public static void testReturnsListAdapter() throws ScriptException {
    final ScriptEngine e = createEngine();
    e.put("TestListAdapterClass", TestListAdapter.class);
    final TestListAdapter tla = (TestListAdapter)e.eval(
            "new TestListAdapterClass.static({\n" +
            "  getList: function() { return [ 'List' ] },\n" +
            "  getCollection: function() { return [ 'Collection' ] },\n" +
            "  getQueue: function() { return [ 'Queue' ] },\n" +
            "  getDequeue: function() { return [ 'Dequeue' ] } })\n");
    Assert.assertEquals(tla.getList().get(0), "List");
    Assert.assertEquals(tla.getCollection().iterator().next(), "Collection");
    Assert.assertEquals(tla.getQueue().peek(), "Queue");
    Assert.assertEquals(tla.getDequeue().peek(), "Dequeue");
}
 
Example 12
Source File: LuaInterpreter.java    From claudb with MIT License 5 votes vote down vote up
public RedisToken execute(SafeString script, List<SafeString> keys, List<SafeString> params) {
  try {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("luaj");
    engine.put("redis", createBinding(redis));
    engine.put("KEYS", toArray(keys));
    engine.put("ARGV", toArray(params));
    return convert(engine.eval(script.toString()));
  } catch (ScriptException e) {
    return error(e.getMessage());
  }
}
 
Example 13
Source File: ScriptEngineTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void windowAlertTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Window window = new Window();

    try {
        e.put("window", window);
        e.eval("print(window.alert)");
        e.eval("window.alert('calling window.alert...')");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
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 throwTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    e.put(ScriptEngine.FILENAME, "throwtest.js");

    try {
        e.eval("throw 'foo'");
    } catch (final ScriptException exp) {
        log(exp.getMessage());
        assertEquals(exp.getMessage(), "foo in throwtest.js at line number 1 at column number 0");
        assertEquals(exp.getFileName(), "throwtest.js");
        assertEquals(exp.getLineNumber(), 1);
    }
}
 
Example 15
Source File: ScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void windowAlertTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Window window = new Window();

    try {
        e.put("window", window);
        e.eval("print(window.alert)");
        e.eval("window.alert('calling window.alert...')");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 16
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public static void contextOverwriteInScriptTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    e.put("foo", 32);

    assertEquals(((Number)e.eval("foo")).intValue(), 32);
    assertEquals(e.eval("context = 'bar'"), "bar");
    assertEquals(((Number)e.eval("foo")).intValue(), 32);
}
 
Example 17
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public static void contextOverwriteInScriptTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    e.put("foo", 32);

    assertEquals(((Number)e.eval("foo")).intValue(), 32);
    assertEquals(e.eval("context = 'bar'"), "bar");
    assertEquals(((Number)e.eval("foo")).intValue(), 32);
}
 
Example 18
Source File: DataDrivenValueScript.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private @Nullable Object executeScript(Function<DataDrivenValue, @Nullable Object> function, IAnalysisDataContainer container) {
    Object result = null;
    ScriptEngine engine = null;
    engine = container.getScriptEngine(fScriptEngine);
    if (engine == null) {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName(fScriptEngine);
        if (engine != null) {
            container.setScriptengine(fScriptEngine, engine);
        }
    }
    if (engine == null) {
        Activator.logWarning("Unknown script engine: " + fScriptEngine); //$NON-NLS-1$
        return null;
    }

    for (Entry<String, DataDrivenValue> entry : fValues.entrySet()) {
        String stateValueId = Objects.requireNonNull(entry.getKey());
        DataDrivenValue stateValue = Objects.requireNonNull(entry.getValue());
        Object value = function.apply(stateValue);
        engine.put(stateValueId, value);
    }

    try {
        result = engine.eval(fScript);
    } catch (ScriptException e) {
        Activator.logError("Script execution failed", e); //$NON-NLS-1$
        return TmfStateValue.nullValue();
    }

    return result;
}
 
Example 19
Source File: NPCScriptManager.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
public void start(MapleClient c, int npcId, String npcMode) {
    try {
        if (c.getPlayer().isAdmin()) {
            c.getPlayer().dropMessage(5, "对话NPC:" + npcId + " 模式:" + npcMode);
        }
        if (this.cms.containsKey(c)) {
            dispose(c);
            return;
        }
        Invocable iv;
        if (npcMode == null) {
            iv = getInvocable("npc/" + npcId + ".js", c, true);
        } else {
            iv = getInvocable("特殊/" + npcMode + ".js", c, true);
        }
        ScriptEngine scriptengine = (ScriptEngine) iv;
        NPCConversationManager cm = new NPCConversationManager(c, npcId, npcMode, ScriptType.NPC, iv);
        if ((iv == null) || (getInstance() == null)) {
            if (iv == null) {
                c.getPlayer().dropMessage(5,"找不到NPC脚本(ID:" + npcId + "), 特殊模式(" + npcMode + "),所在地图(ID:" + c.getPlayer().getMapId() + ")");
            }
            dispose(c);
            return;
        }
        this.cms.put(c, cm);
        scriptengine.put("cm", cm);
        c.getPlayer().setConversation(1);
        c.setClickedNPC();
        try {
            iv.invokeFunction("start", new Object[0]);
        } catch (NoSuchMethodException nsme) {
            iv.invokeFunction("action", new Object[]{(byte) 1, (byte) 0, (int) (byte) 0});
        }
    } catch (NoSuchMethodException | ScriptException e) {
        System.err.println("NPC脚本出错(ID : " + npcId + ")模式:" + npcMode + "错误内容: " + e);
        FileoutputUtil.log(FileoutputUtil.ScriptEx_Log, "NPC脚本出错(ID : " + npcId + ")模式" + npcMode + ".\r\n错误信息:" + e);
        dispose(c);
        notice(c, npcId, npcMode);
    }
}
 
Example 20
Source File: ScriptVars.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 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");

    final File f = new File("test.txt");
    // expose File object as variable to script
    engine.put("file", f);

    // evaluate a script string. The script accesses "file"
    // variable and calls method on it
    engine.eval("print(file.getAbsolutePath())");
}