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

The following examples show how to use javax.script.ScriptEngine#getBindings() . 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: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void megamorphicPropertyReadTest() throws ScriptException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine();
    final Bindings scope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    boolean ret;

    // Why 16 is the upper limit of this loop? The default nashorn dynalink megamorphic threshold is 16.
    // See jdk.nashorn.internal.runtime.linker.Bootstrap.NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD
    // We do, 'eval' of the same in this loop twice. So, 16*2 = 32 times that callsite in the script
    // is exercised - much beyond the default megamorphic threshold.

    for (int i = 0; i < 16; i++) {
        scope.remove(VAR_NAME);
        ret = lookupVar(engine, VAR_NAME);
        assertFalse(ret, "Expected false in iteration " + i);
        scope.put(VAR_NAME, "foo");
        ret = lookupVar(engine, VAR_NAME);
        assertTrue(ret, "Expected true in iteration " + i);
    }
}
 
Example 2
Source File: ScopeTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void megamorphicPropertyReadTest() throws ScriptException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine();
    final Bindings scope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    boolean ret;

    // Why 16 is the upper limit of this loop? The default nashorn dynalink megamorphic threshold is 16.
    // See jdk.nashorn.internal.runtime.linker.Bootstrap.NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD
    // We do, 'eval' of the same in this loop twice. So, 16*2 = 32 times that callsite in the script
    // is exercised - much beyond the default megamorphic threshold.

    for (int i = 0; i < 16; i++) {
        scope.remove(VAR_NAME);
        ret = lookupVar(engine, VAR_NAME);
        assertFalse(ret, "Expected false in iteration " + i);
        scope.put(VAR_NAME, "foo");
        ret = lookupVar(engine, VAR_NAME);
        assertTrue(ret, "Expected true in iteration " + i);
    }
}
 
Example 3
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void megamorphicPropertyReadTest() throws ScriptException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine();
    final Bindings scope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    boolean ret;

    // Why 16 is the upper limit of this loop? The default nashorn dynalink megamorphic threshold is 16.
    // See jdk.nashorn.internal.runtime.linker.Bootstrap.NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD
    // We do, 'eval' of the same in this loop twice. So, 16*2 = 32 times that callsite in the script
    // is exercised - much beyond the default megamorphic threshold.

    for (int i = 0; i < 16; i++) {
        scope.remove(VAR_NAME);
        ret = lookupVar(engine, VAR_NAME);
        assertFalse(ret, "Expected false in iteration " + i);
        scope.put(VAR_NAME, "foo");
        ret = lookupVar(engine, VAR_NAME);
        assertTrue(ret, "Expected true in iteration " + i);
    }
}
 
Example 4
Source File: JsTestUtils.java    From grammaticus with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @return a script engine with an appropriate global context for $Api so that we don't have to revaluate the functions constantly
 * 
 * If you want to add stuff to bindings while running tests, just comment out the if and the closing brace
 */
public static ScriptEngine getScriptEngine() {
    Bindings bindings = BINDINGS.get();
    if (bindings == null) {
        // Create an engine just to compile the $AP
        ScriptEngine compEngine = new ScriptEngineManager().getEngineByName("JavaScript");
        compEngine.put("out", System.out);

        try {
            bindings = compEngine.getBindings(ScriptContext.GLOBAL_SCOPE);
            bindings.put("Grammaticus",  compEngine.eval(Resources.toString(JsTestUtils.class.getResource("grammaticus.js"), Charsets.UTF_8)));
            BINDINGS.set(bindings);
        } catch (ScriptException | IOException x) {
            x.printStackTrace();
        }
    }
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
    return engine;
}
 
Example 5
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void megamorphicPropertyReadTest() throws ScriptException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine();
    final Bindings scope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    boolean ret;

    // Why 16 is the upper limit of this loop? The default nashorn dynalink megamorphic threshold is 16.
    // See jdk.nashorn.internal.runtime.linker.Bootstrap.NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD
    // We do, 'eval' of the same in this loop twice. So, 16*2 = 32 times that callsite in the script
    // is exercised - much beyond the default megamorphic threshold.

    for (int i = 0; i < 16; i++) {
        scope.remove(VAR_NAME);
        ret = lookupVar(engine, VAR_NAME);
        assertFalse(ret, "Expected false in iteration " + i);
        scope.put(VAR_NAME, "foo");
        ret = lookupVar(engine, VAR_NAME);
        assertTrue(ret, "Expected true in iteration " + i);
    }
}
 
Example 6
Source File: Scripting.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ScriptEngine postConfigure(ScriptEngine eng) {
    if (eng == null) {
        return null;
    }
    if (eng.getFactory().getNames().contains("Graal.js")) { // NOI18N
        final Bindings b = eng.getBindings(ScriptContext.ENGINE_SCOPE);
        if (allowAllAccess) {
            b.put("polyglot.js.nashorn-compat", true); // NOI18N
        } else {
            b.put("polyglot.js.allowHostAccess", true); // NOI18N
        }
        b.put("polyglot.js.allowHostClassLookup", (Predicate<String>) (s) -> { // NOI18N
            return allowHostClassLookup(eng, s);
        });
    }
    if (isNashornFactory(eng.getFactory())) {
        return secureEngineEngine(eng);
    }
    return eng;
}
 
Example 7
Source File: MetricsCommon.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 执行js表达式并返回执行后的结果
 * @param express
 * 表达式
 * @param value
 * 原值
 * @return
 * 返回新值或返回原值(执行失败时)
 */
public static Object executeJsExpress(String express, Object value){
    Object newValue = value;
    if(!StringUtils.isEmpty(express)){
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("nashorn");
            engine.put("value", value);
            engine.put("newValue", "");
            engine.getBindings(ScriptContext.ENGINE_SCOPE);
            engine.eval(express);
            newValue = engine.get("newValue");
        } catch (ScriptException e) {
            log.error("执行js表达式错误",e);
        }
    }

    return newValue;
}
 
Example 8
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void megamorphicPropertyReadTest() throws ScriptException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine();
    final Bindings scope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    boolean ret;

    // Why 16 is the upper limit of this loop? The default nashorn dynalink megamorphic threshold is 16.
    // See jdk.nashorn.internal.runtime.linker.Bootstrap.NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD
    // We do, 'eval' of the same in this loop twice. So, 16*2 = 32 times that callsite in the script
    // is exercised - much beyond the default megamorphic threshold.

    for (int i = 0; i < 16; i++) {
        scope.remove(VAR_NAME);
        ret = lookupVar(engine, VAR_NAME);
        assertFalse(ret, "Expected false in iteration " + i);
        scope.put(VAR_NAME, "foo");
        ret = lookupVar(engine, VAR_NAME);
        assertTrue(ret, "Expected true in iteration " + i);
    }
}
 
Example 9
Source File: LuaExpression.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private LuaHolder(ScriptScope scope, String expression) {
    try {
        this.scope = scope.copyScope();
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName(ENGINE_NAME);
        this.attributes = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
        Compilable compilable = (Compilable) engine;
        this.script = compilable.compile(expression);
    } catch (ScriptException exception) {
        throw new ScriptExpressionException(exception);
    }
}
 
Example 10
Source File: Worker.java    From scijava-jupyter-kernel with Apache License 2.0 5 votes vote down vote up
private void syncBindings(ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {

	Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
	this.scriptEngines.forEach((String name, ScriptEngine engine) -> {
	    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
	    currentBindings.keySet().forEach((String key) -> {
		bindings.put(key, scriptLanguage.decode(currentBindings.get(key)));
	    });
	});

    }
 
Example 11
Source File: ScijavaEvaluator.java    From scijava-jupyter-kernel with Apache License 2.0 5 votes vote down vote up
private void initBindings(Bindings bindings, ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {

        Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.keySet().forEach((String key) -> {
            currentBindings.put(key, scriptLanguage.decode(bindings.get(key)));
        });

    }
 
Example 12
Source File: PythonExpression.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private PythonHolder(ScriptScope scope, String expression) {
    try {
        this.scope = scope.copyScope();
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName(ENGINE_NAME);
        this.attributes = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
        Compilable compilable = (Compilable) engine;
        this.script = compilable.compile(expression);
    } catch (ScriptException exception) {
        throw new ScriptExpressionException(exception);
    }
}
 
Example 13
Source File: LuaFunction.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private LuaHolder(ScriptScope scope, String expression) {
    try {
        this.scope = scope.copyScope();
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName(ENGINE_NAME);
        this.attributes = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
        Compilable compilable = (Compilable) engine;
        this.script = compilable.compile(expression);
    } catch (ScriptException exception) {
        throw new ScriptExpressionException(exception);
    }
}
 
Example 14
Source File: GraalEnginesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void accessPolyglotBindings() throws Exception {
    ScriptEngineManager man = Scripting.createManager();
    ScriptEngine js = man.getEngineByName("GraalVM:js");
    ScriptEngine python = man.getEngineByName("GraalVM:python");

    List<Integer> scopes = js.getContext().getScopes();
    assertEquals(1, scopes.size());
    assertEquals(ScriptContext.GLOBAL_SCOPE, scopes.get(0).intValue());

    Bindings bindings = js.getBindings(ScriptContext.GLOBAL_SCOPE);
    bindings.put("x", 42);

    js.eval("\n"
        + "var x = Polyglot.import('x');\n"
        + "Polyglot.export('y', x);\n"
        + ""
    );

    Object y = python.eval("\n"
        + "import polyglot;\n"
        + "polyglot.import_value('y')"
    );

    assertTrue("Expecting number, but was: " + y, y instanceof Number);
    assertEquals(42, ((Number)y).intValue());
}
 
Example 15
Source File: ConsoleLogger.java    From rug-cli with GNU General Public License v3.0 5 votes vote down vote up
public static AbstractFunction1<ScriptEngine, BoxedUnit> consoleLogger(String indent,
        boolean enabled) {
    return new AbstractFunction1<ScriptEngine, BoxedUnit>() {

        @Override
        public BoxedUnit apply(ScriptEngine engine) {
            Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
            bindings.put("console", new ConsoleLogger(indent, enabled));
            engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            return null;
        }
    };
}
 
Example 16
Source File: JsExpression.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private JsHolder(ScriptScope scope, String expression) {
    try {
        this.scope = scope.copyScope();
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName(ENGINE_NAME);
        this.attributes = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
        Compilable compilable = (Compilable) engine;
        this.script = compilable.compile(expression);
    } catch (ScriptException exception) {
        throw new ScriptExpressionException(exception);
    }
}
 
Example 17
Source File: DFActorManagerJs.java    From dfactor with MIT License 5 votes vote down vote up
private boolean _checkScriptFileValid(File f){
	boolean bRet = false;
	do {
		ScriptEngine engineTmp = _engineMgr.getEngineByName("JavaScript");
		try {
			engineTmp.eval(new FileReader(f));
			Set<String> setCur = _jsEngine.getBindings(ScriptContext.ENGINE_SCOPE).keySet();
			Bindings bindTmp = engineTmp.getBindings(ScriptContext.ENGINE_SCOPE);
			Iterator<String> it = bindTmp.keySet().iterator();
			while(it.hasNext()){
				String key = it.next();
				if(setCur.contains(key)){
					printError("global var duplicated: "+key+" in '"+f.getAbsolutePath()+"' & '"+_mapScriptKeyFile.get(key)+"'");
					return false;
				}else{
					_mapScriptKeyFile.put(key, f.getAbsolutePath());
				}
			}
		} catch (FileNotFoundException | ScriptException e) {
			e.printStackTrace();
			break;
		}finally{
			engineTmp = null;
		}
		bRet = true;
	} while (false);
	return bRet;
}
 
Example 18
Source File: GraphvizWriter.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void writeGraph(OutputStream os) throws IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    super.writeGraph(baos);

    try
    {
        StringBuilder builder = new StringBuilder();
        builder.append(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("vizjs/viz.js")));
        builder.append("var result = new Viz(dotGraph);");

        String script = builder.toString();
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
        Compilable compilingEngine = (Compilable) engine;
        CompiledScript cscript = compilingEngine.compile(script);

        // Bindings bindings = cscript.getEngine().createBindings();
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        for (Map.Entry me : bindings.entrySet())
        {
            System.out.printf("%s: %s\n", me.getKey(), String.valueOf(me.getValue()));
        }
        bindings.put("dotGraph", baos.toString());
        // cscript.eval();
        Object result = cscript.eval(bindings);
        LOG.info("Result:" + ReflectionToStringBuilder.toString(result));
    }
    catch (Exception e)
    {
        throw new IOException("Exception generating graph.", e);
    }
}
 
Example 19
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 4 votes vote down vote up
@Test
public void test_bsh_script_engine( ) throws Throwable {
    ScriptEngineManager manager =
        new ScriptEngineManager( bsh.Interpreter.class.getClassLoader() );

    ScriptEngine engine = manager.getEngineByName( "beanshell" );
    assertNotNull( engine );

    // basic eval
    int i = (Integer)engine.eval("2*2");
    assertEquals( 4, i );

    // set a variable
    engine.put( "foo", 42 );
    assertEquals( 42, engine.get("foo") );

    // bsh primitives stay primitive internally
    engine.eval( "int fooInt=42" );
    assertEquals( 42, engine.get("foo") );
    assertSame( engine.eval("fooInt.getClass();"), Primitive.class );
    assertThat( engine.getContext().getAttribute( "fooInt", ENGINE_SCOPE ),
        instanceOf( Integer.class ) );

    // Variables visible through bindings in both directions?
    Bindings engineScope = engine.getBindings( ENGINE_SCOPE );
    Bindings engineScope2 = engine.getContext().getBindings( ENGINE_SCOPE );
    assertSame( engineScope, engineScope2 );
    assertThat( engineScope.get("foo"), instanceOf( Integer.class ) );
    engineScope.put("bar", "gee");
    // get() and eval() for us should be equivalent in this case
    assertEquals( "gee", engine.get("bar") );
    assertEquals( "gee", engine.eval("bar") );

    // install and invoke a method
    engine.eval("foo() { return foo+1; }");
    // invoke a method
    Invocable invocable = (Invocable) engine;
    assertEquals( 43, invocable.invokeFunction( "foo" ) );

    // get interface
    engine.eval("flag=false; run() { flag=true; }");
    assertFalse( (Boolean) engine.get("flag") );
    assertNull( engine.get("flag_nonexistent") );
    Runnable runnable = (Runnable) invocable.getInterface( Runnable.class );
    runnable.run();
    assertTrue( (Boolean) engine.get("flag") );

    // get interface from scripted object
    engine.eval(
        "flag2=false; myObj() { run() { flag2=true; } return this; }");
    assertFalse( (Boolean) engine.get("flag2") );
    Object scriptedObject = invocable.invokeFunction("myObj");
    assertThat( scriptedObject, instanceOf( This.class ) );
    runnable =
        (Runnable) invocable.getInterface( scriptedObject, Runnable.class );
    runnable.run();
    assertTrue( (Boolean) engine.get("flag2") );
    // Run with alternate bindings
    assertTrue( (Boolean) engine.get("flag") );
    assertEquals( 42, engine.get("foo") );
    Bindings newEngineScope = engine.createBindings();
    engine.eval( "flag=false; foo=33;", newEngineScope );
    assertFalse( (Boolean) newEngineScope.get("flag") );
    assertEquals(33, newEngineScope.get("foo") );
    // These are unchanged in default context
    assertTrue( (Boolean )engine.get("flag") );
    assertEquals( 42, engine.get("foo") );

    // Try redirecting output
    String fname = "testBshScriptEngine.out";
    String outString = "checkstyle-supressions.xml";
    Writer fout = new FileWriter( fname );
    engine.getContext().setWriter( fout );
    engine.put( "outString", outString );
    engine.eval(new StringReader("dir('src/conf');"));
    BufferedReader bin = new BufferedReader( new FileReader( fname ) );
    String line = bin.readLine();
    assertNotNull(line);
    assertThat(line, endsWith(outString));
    new File(fname).delete();
    bin.close();
    fout.close();

    // Add a new scope dynamically?

}
 
Example 20
Source File: EJSParser.java    From jeddict with Apache License 2.0 4 votes vote down vote up
private ScriptEngine createEngine() {
        // Hack until NETBEANS-2705 fixed
        System.getProperties().setProperty("polyglot.js.nashorn-compat", "true");
        System.getProperties().setProperty("js.global-arguments", "true");
        CompiledScript compiledScript;
        Bindings bindings;
        GraalJSEngineFactory graalJSEngineFactory = new GraalJSEngineFactory();
        ScriptEngine scriptEngine = graalJSEngineFactory.getScriptEngine();
//      org.netbeans.api.scripting.Scripting.createManager().getEngineByName("Graal.js");

        try {
            if (base == null) {
                base = readString(loadResource(TEMPLATES + "base.js"));
            }
            if (ejs == null) {
                ejs = readString(loadResource(TEMPLATES + "ejs.js"));
            }

            scriptEngine.eval(base);
            Compilable compilingEngine = (Compilable) scriptEngine;
            compiledScript = compilingEngine.compile(ejs);
            bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            compiledScript.eval(bindings);
            scriptEngine.eval(scripts.toString());

            for (Map<String, Object> context : contexts) {
                context.entrySet()
                        .forEach(entry -> {
                                Object value = entry.getValue();
                                if (value instanceof Collection || value instanceof Map) {
                                        value = toJson(scriptEngine, value);
                                }
                                bindings.put(entry.getKey(), value);
                        });
            }
        } catch (ScriptException ex) {
            Exceptions.printStackTrace(ex);
        }
        // Hack until NETBEANS-2705 fixed
        System.getProperties().remove("polyglot.js.nashorn-compat");
        return scriptEngine;
    }