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

The following examples show how to use javax.script.ScriptEngine#setContext() . 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: InvocableTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that we can get interface out of a script object even after
 * switching to use different ScriptContext.
 */
public void getInterfaceDifferentContext() {
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine e = m.getEngineByName("nashorn");
    try {
        Object obj = e.eval("({ run: function() { } })");

        // change script context
        ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        Runnable r = ((Invocable) e).getInterface(obj, Runnable.class);
        r.run();
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 2
Source File: InvocableTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that invokeFunction calls functions only from current context's
 * Bindings.
 */
public void invokeFunctionDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        e.eval("function hello() { return 'Hello World!'; }");
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        // change engine's current context
        e.setContext(ctxt);

        ((Invocable) e).invokeFunction("hello"); // no 'hello' in new context!
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example 3
Source File: InvocableTest.java    From hottub 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 4
Source File: InvocableTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example 5
Source File: InvocableTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that invokeFunction calls functions only from current context's
 * Bindings.
 */
public void invokeFunctionDifferentContextTest() {
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        Object obj = e.eval("function hello() { return 'Hello World!'; }");
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        // change engine's current context
        e.setContext(ctxt);

        ((Invocable) e).invokeFunction("hello"); // no 'hello' in new context!
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example 6
Source File: InvocableTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example 7
Source File: ConfigurationValidator.java    From revapi with Apache License 2.0 6 votes vote down vote up
private ScriptEngine getJsEngine(Writer output) throws IOException, ScriptException {
    ScriptEngine ret = null;

    if (jsEngine != null) {
        ret = jsEngine.get();
    }

    if (ret == null) {
        ret = new ScriptEngineManager().getEngineByName("javascript");
        ScriptContext ctx = new SimpleScriptContext();

        Bindings globalScope = ret.createBindings();
        ctx.setBindings(globalScope, ScriptContext.GLOBAL_SCOPE);

        initTv4(ret, globalScope);

        ret.setContext(ctx);

        jsEngine = new WeakReference<>(ret);
    }

    ret.getContext().setWriter(output);
    ret.getContext().setErrorWriter(output);

    return ret;
}
 
Example 8
Source File: InvocableTest.java    From jdk8u60 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 9
Source File: InvocableTest.java    From jdk8u_nashorn 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 10
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 5 votes vote down vote up
@Test
public void test_eval_writer_unicode() throws Exception {
    ScriptEngine engine = new BshScriptEngineFactory().getScriptEngine();
    ScriptContext ctx = new SimpleScriptContext();
    StringWriter sw = new StringWriter();
    ctx.setWriter(sw);
    engine.setContext(ctx);
    engine.eval("print('\\u3456');");
    assertEquals(new String("\u3456".getBytes(), "UTF-8").charAt(0),
            new String(sw.toString().getBytes(), "UTF-8").charAt(0));
}
 
Example 11
Source File: ScopeTest.java    From openjdk-jdk9 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 12
Source File: ScopeTest.java    From openjdk-jdk8u 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 13
Source File: ScopeTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public static void engineOverwriteTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = new SimpleBindings();
    b.put("engine", "hello");
    b.put("foo", 32);
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    e.setContext(newCtxt);
    assertEquals(e.eval("engine"), "hello");
    assertEquals(((Number)e.eval("foo")).intValue(), 32);
}
 
Example 14
Source File: DataFactoryScriptingSupport.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object eval( final String script, final String scriptLanguage ) throws ScriptException {
  final ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName( scriptLanguage );
  if ( scriptEngine == null ) {
    throw new ScriptException( String.format(
        "DataFactoryScriptingSupport: Failed to locate scripting engine for language '%s'.", scriptLanguage ) );
  }

  scriptEngine.setContext( context );
  return scriptEngine.eval( script );
}
 
Example 15
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invokeFunctionInGlobalScopeTest2() throws Exception {
     final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

     // create a new ScriptContext instance
     final ScriptContext ctxt = new SimpleScriptContext();
     // set it as 'default' ScriptContext
     engine.setContext(ctxt);

     // create a new Bindings and set as ENGINE_SCOPE
     ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

     // define a function called "func"
     engine.eval("func = function() { return 42 }");

     // move ENGINE_SCOPE Bindings to GLOBAL_SCOPE
     ctxt.setBindings(ctxt.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.GLOBAL_SCOPE);

     // create a new Bindings and set as ENGINE_SCOPE
     ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

     // define new function that calls "func" now in GLOBAL_SCOPE
     engine.eval("newfunc = function() { return func() }");

     // call "newfunc" and check the return value
     final Object value = ((Invocable)engine).invokeFunction("newfunc");
     assertTrue(((Number)value).intValue() == 42);
}
 
Example 16
Source File: ScopeTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invokeFunctionInGlobalScopeTest2() throws Exception {
     final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

     // create a new ScriptContext instance
     final ScriptContext ctxt = new SimpleScriptContext();
     // set it as 'default' ScriptContext
     engine.setContext(ctxt);

     // create a new Bindings and set as ENGINE_SCOPE
     ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

     // define a function called "func"
     engine.eval("func = function() { return 42 }");

     // move ENGINE_SCOPE Bindings to GLOBAL_SCOPE
     ctxt.setBindings(ctxt.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.GLOBAL_SCOPE);

     // create a new Bindings and set as ENGINE_SCOPE
     ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

     // define new function that calls "func" now in GLOBAL_SCOPE
     engine.eval("newfunc = function() { return func() }");

     // call "newfunc" and check the return value
     Object value = ((Invocable)engine).invokeFunction("newfunc");
     assertTrue(((Number)value).intValue() == 42);
}
 
Example 17
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the script at the specified location and returns the result.
 *
 * @param filePath Script path and file name.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @param args Function/method arguments.
 * @return The script result.
 * @throws ScriptException
 * @throws NoSuchMethodException
 * @throws IOException
 * @throws IllegalArgumentException
 */
public static Object executeScript(String filePath, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException, IOException {
    Assert.notNull("filePath", filePath, "scriptContext", scriptContext);
    scriptContext.setAttribute(ScriptEngine.FILENAME, filePath, ScriptContext.ENGINE_SCOPE);
    if (functionName == null) {
        // The Rhino script engine will not work when invoking a function on a compiled script.
        // The test for null can be removed when the engine is fixed.
        CompiledScript script = compileScriptFile(filePath);
        if (script != null) {
            return executeScript(script, functionName, scriptContext, args);
        }
    }
    String fileExtension = getFileExtension(filePath);
    if ("bsh".equalsIgnoreCase(fileExtension)) { // SCIPIO: 2018-09-19: Warn here, there's nowhere else we can do it...
        Debug.logWarning("Deprecated Beanshell script file invoked (" + filePath + "); "
                + "this is a compatibility mode only (runs as Groovy); please convert to Groovy script", module);
        // FIXME?: This does not properly use the GroovyLangVariant.BSH bindings for scripts in filesystem... unclear if should have
        fileExtension = "groovy";
    }
    ScriptEngineManager manager = getScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension(fileExtension);
    if (engine == null) {
        throw new IllegalArgumentException("The script type is not supported for location: " + filePath);
    }
    engine = configureScriptEngineForInvoke(engine); // SCIPIO: 2017-01-27: Custom configurations for the engine
    if (Debug.verboseOn()) {
        Debug.logVerbose("Begin processing script [" + filePath + "] using engine " + engine.getClass().getName(), module);
    }
    engine.setContext(scriptContext);
    URL scriptUrl = FlexibleLocation.resolveLocation(filePath);
    try (
            InputStreamReader reader = new InputStreamReader(new FileInputStream(scriptUrl.getFile()), UtilIO
                    .getUtf8());) {
        Object result = engine.eval(reader);
        if (UtilValidate.isNotEmpty(functionName)) {
            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;
    }
}
 
Example 18
Source File: SpagoBIScriptManager.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
public Object runScript(String script, String language, Map<String, Object> bindings, List imports) {

		Object results;

		logger.debug("IN");

		results = null;
		try {

			if (imports != null) {
				StringBuffer importsBuffer = new StringBuffer();
				for (Object importedScriptReference : imports) {
					if (importedScriptReference instanceof File) {
						importsBuffer.append(this.getImportedScript((File) importedScriptReference) + "\n");
					} else if (importedScriptReference instanceof URL) {
						importsBuffer.append(this.getImportedScript((URL) importedScriptReference) + "\n");
					} else {
						logger.warn("Impossible to resolve import reference of type [" + importedScriptReference.getClass().getName() + "]");
					}

				}
				script = importsBuffer.toString() + script;
			}

			if (isGroovy(language)) {
				return evaluateGroovy(script, bindings);
			}

			final ScriptEngine scriptEngine = getScriptEngine(language);

			if (scriptEngine == null) {
				throw new RuntimeException("No engine available to execute scripts of type [" + language + "]");
			} else {
				logger.debug("Found engine [" + scriptEngine.NAME + "]");
			}

			ScriptContext scriptContext = new SimpleScriptContext();
			if (bindings != null) {
				Bindings scriptBindings = new SimpleBindings(bindings);
				scriptContext.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE);
			}
			scriptEngine.setContext(scriptContext);

			PermissionCollection pc = new Permissions(); // This means no permissions at all
			CodeSource codeSource = scriptEngine.getClass().getProtectionDomain().getCodeSource();
			ProtectionDomain protectionDomain = new ProtectionDomain(codeSource, pc);
			ProtectionDomain[] context = new ProtectionDomain[] { protectionDomain };
			AccessControlContext accessControlContext = new AccessControlContext(context);

			final String _script = script;

			results = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {

				@Override
				public Object run() throws ScriptException {
					return scriptEngine.eval(_script);
				}
			}, accessControlContext);

		} catch (Throwable t) {
			logger.error("Error while executing Javascript:\n" + script, t);
			throw new SpagoBIRuntimeException("An unexpected error occured while executing script", t);
		} finally {
			logger.debug("OUT");
		}

		return results;
	}
 
Example 19
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void multiGlobalTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

    try {
        final Object obj1 = e.eval("Object");
        final Object obj2 = e.eval("Object", newCtxt);
        Assert.assertNotEquals(obj1, obj2);
        Assert.assertNotNull(obj1);
        Assert.assertNotNull(obj2);
        Assert.assertEquals(obj1.toString(), obj2.toString());

        e.eval("x = 'hello'");
        e.eval("x = 'world'", newCtxt);
        Object x1 = e.getContext().getAttribute("x");
        Object x2 = newCtxt.getAttribute("x");
        Assert.assertNotEquals(x1, x2);
        Assert.assertEquals(x1, "hello");
        Assert.assertEquals(x2, "world");

        x1 = e.eval("x");
        x2 = e.eval("x", newCtxt);
        Assert.assertNotEquals(x1, x2);
        Assert.assertEquals(x1, "hello");
        Assert.assertEquals(x2, "world");

        final ScriptContext origCtxt = e.getContext();
        e.setContext(newCtxt);
        e.eval("y = new Object()");
        e.eval("y = new Object()", origCtxt);

        final Object y1 = origCtxt.getAttribute("y");
        final Object y2 = newCtxt.getAttribute("y");
        Assert.assertNotEquals(y1, y2);
        final Object yeval1 = e.eval("y");
        final Object yeval2 = e.eval("y", origCtxt);
        Assert.assertNotEquals(yeval1, yeval2);
        Assert.assertEquals("[object Object]", y1.toString());
        Assert.assertEquals("[object Object]", y2.toString());
    } catch (final ScriptException se) {
        se.printStackTrace();
        fail(se.getMessage());
    }
}
 
Example 20
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void multiGlobalTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

    try {
        final Object obj1 = e.eval("Object");
        final Object obj2 = e.eval("Object", newCtxt);
        Assert.assertNotEquals(obj1, obj2);
        Assert.assertNotNull(obj1);
        Assert.assertNotNull(obj2);
        Assert.assertEquals(obj1.toString(), obj2.toString());

        e.eval("x = 'hello'");
        e.eval("x = 'world'", newCtxt);
        Object x1 = e.getContext().getAttribute("x");
        Object x2 = newCtxt.getAttribute("x");
        Assert.assertNotEquals(x1, x2);
        Assert.assertEquals(x1, "hello");
        Assert.assertEquals(x2, "world");

        x1 = e.eval("x");
        x2 = e.eval("x", newCtxt);
        Assert.assertNotEquals(x1, x2);
        Assert.assertEquals(x1, "hello");
        Assert.assertEquals(x2, "world");

        final ScriptContext origCtxt = e.getContext();
        e.setContext(newCtxt);
        e.eval("y = new Object()");
        e.eval("y = new Object()", origCtxt);

        final Object y1 = origCtxt.getAttribute("y");
        final Object y2 = newCtxt.getAttribute("y");
        Assert.assertNotEquals(y1, y2);
        final Object yeval1 = e.eval("y");
        final Object yeval2 = e.eval("y", origCtxt);
        Assert.assertNotEquals(yeval1, yeval2);
        Assert.assertEquals("[object Object]", y1.toString());
        Assert.assertEquals("[object Object]", y2.toString());
    } catch (final ScriptException se) {
        se.printStackTrace();
        fail(se.getMessage());
    }
}