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

The following examples show how to use javax.script.Bindings#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: GremlinGroovyScriptEngine.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Traversal.Admin eval(final Bytecode bytecode, final Bindings bindings, final String traversalSource) throws ScriptException {
    // these validations occur before merging in bytecode bindings which will override existing ones. need to
    // extract the named traversalsource prior to that happening so that bytecode bindings can share the same
    // namespace as global bindings (e.g. traversalsources and graphs).
    if (traversalSource.equals(HIDDEN_G))
        throw new IllegalArgumentException("The traversalSource cannot have the name " + HIDDEN_G + " - it is reserved");

    if (bindings.containsKey(HIDDEN_G))
        throw new IllegalArgumentException("Bindings cannot include " + HIDDEN_G + " - it is reserved");

    if (!bindings.containsKey(traversalSource))
        throw new IllegalArgumentException("The bindings available to the ScriptEngine do not contain a traversalSource named: " + traversalSource);

    final Object b = bindings.get(traversalSource);
    if (!(b instanceof TraversalSource))
        throw new IllegalArgumentException(traversalSource + " is of type " + b.getClass().getSimpleName() + " and is not an instance of TraversalSource");

    final Bindings inner = new SimpleBindings();
    inner.putAll(bindings);
    inner.putAll(bytecode.getBindings());
    inner.put(HIDDEN_G, b);
    org.apache.tinkerpop.gremlin.process.traversal.Script script = GroovyTranslator.of(HIDDEN_G, typeTranslator).translate(bytecode);
    script.getParameters().ifPresent(inner::putAll);
    return (Traversal.Admin) this.eval(script.getScript(), inner);
}
 
Example 2
Source File: JavascriptRequestResponseFilter.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public void filterResponse(HttpResponse response, HttpMessageContents contents, HttpMessageInfo messageInfo) {
    if (compiledResponseFilterScript == null) {
        return;
    }

    Bindings bindings = JAVASCRIPT_ENGINE.createBindings();
    bindings.put("response", response);
    bindings.put("contents", contents);
    bindings.put("messageInfo", messageInfo);
    bindings.put("log", log);
    try {
        compiledResponseFilterScript.eval(bindings);
    } catch (ScriptException e) {
        log.error("Could not invoke filterResponse using supplied javascript", e);
    }
}
 
Example 3
Source File: ScriptObjectMirrorTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void mapScriptObjectMirrorCallsiteTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("nashorn");
    final String TEST_SCRIPT = "typeof obj.foo";

    final Bindings global = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    engine.eval("var obj = java.util.Collections.emptyMap()");
    // this will drive callsite "obj.foo" of TEST_SCRIPT
    // to use "obj instanceof Map" as it's guard
    engine.eval(TEST_SCRIPT, global);
    // redefine 'obj' to be a script object
    engine.eval("obj = {}");

    final Bindings newGlobal = engine.createBindings();
    // transfer 'obj' from default global to new global
    // new global will get a ScriptObjectMirror wrapping 'obj'
    newGlobal.put("obj", global.get("obj"));

    // Every ScriptObjectMirror is a Map! If callsite "obj.foo"
    // does not see the new 'obj' is a ScriptObjectMirror, it'll
    // continue to use Map's get("obj.foo") instead of ScriptObjectMirror's
    // getMember("obj.foo") - thereby getting null instead of undefined
    assertEquals("undefined", engine.eval(TEST_SCRIPT, newGlobal));
}
 
Example 4
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void createBindingsTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    b.put("foo", 42.0);
    Object res = null;
    try {
        res = e.eval("foo == 42.0", b);
    } catch (final ScriptException | NullPointerException se) {
        se.printStackTrace();
        fail(se.getMessage());
    }

    assertEquals(res, Boolean.TRUE);
}
 
Example 5
Source File: FileUtil.java    From jeddict with Apache License 2.0 6 votes vote down vote up
public static void expandTemplate(Reader reader, Writer writer, Map<String, Object> values, Charset targetEncoding) throws IOException {
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);
    }
    bind.put(ENCODING_PROPERTY_NAME, targetEncoding.name());

    try {
        eng.getContext().setWriter(writer);
        eng.eval(reader);
    } catch (ScriptException ex) {
        throw new IOException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}
 
Example 6
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public static void testMegamorphicGetInGlobal() throws Exception {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("nashorn");
    final String script = "foo";
    // "foo" is megamorphic because of different global scopes.
    // Make sure ScriptContext variable search works even after
    // it becomes megamorphic.
    for (int index = 0; index < 25; index++) {
        final Bindings bindings = new SimpleBindings();
        bindings.put("foo", index);
        final Number value = (Number)engine.eval(script, bindings);
        assertEquals(index, value.intValue());
    }
}
 
Example 7
Source File: ScriptEngineScopeTest.java    From es6draft with MIT License 5 votes vote down vote up
@Test
public void bindingValueWithThisExplicitSimpleBinding() throws ScriptException {
    Bindings binding = new SimpleBindings();
    binding.put("value", "Sabik");

    assertThat(engine.eval("this.value", binding), nullValue());
}
 
Example 8
Source File: ConsStringTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsStringFlattening() throws ScriptException {
    final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);
    final Map<Object, Object> m = new HashMap<>();
    b.put("m", m);
    e.eval("var x = 'f'; x += 'oo'; var y = 'b'; y += 'ar'; m.put(x, y)");
    assertEquals("bar", m.get("foo"));
}
 
Example 9
Source File: BaseAction.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
protected String initPassword(Business business, Person person) throws Exception {
	String str = Config.person().getPassword();
	Pattern pattern = Pattern.compile(com.x.base.core.project.config.Person.REGULAREXPRESSION_SCRIPT);
	Matcher matcher = pattern.matcher(str);
	if (matcher.matches()) {
		String eval = ScriptFactory.functionalization(StringEscapeUtils.unescapeJson(matcher.group(1)));
		ScriptContext scriptContext = new SimpleScriptContext();
		Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
		bindings.put("person", person);
		Object o = ScriptFactory.scriptEngine.eval(eval, scriptContext);
		return o.toString();
	} else {
		return str;
	}
}
 
Example 10
Source File: ConsStringTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testArrayConsString() throws ScriptException {
    final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);
    final ArrayHolder h = new ArrayHolder();
    b.put("h", h);
    e.eval("var x = 'f'; x += 'oo'; h.array = [x];");
    assertEquals(1, h.array.length);
    assertEquals("foo", h.array[0]);
}
 
Example 11
Source File: ClojureScriptEngine.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected ClojureScriptEngine(ScriptEngineFactory scriptEngineFactory) {
    this.scriptEngineFactory = scriptEngineFactory;

    // Set up the engine bindings
    Bindings engineScope = getBindings(ScriptContext.ENGINE_SCOPE);
    engineScope.put(ENGINE, ENGINE_NAME);
    engineScope.put(ENGINE_VERSION, ENGINE_VERSION);
    engineScope.put(NAME, ENGINE_NAME);
    engineScope.put(LANGUAGE, ENGINE_NAME);
    engineScope.put(LANGUAGE_VERSION, ENGINE_VERSION);
}
 
Example 12
Source File: ScriptEngineSample.java    From luaj with MIT License 5 votes vote down vote up
public static void testBindings(ScriptEngine e, Bindings b) throws ScriptException {
    CompiledScript cs = ((Compilable)e).compile(
    		"print( 'somejavaint', type(somejavaint), somejavaint )\n" +
    		"print( 'somejavadouble', type(somejavadouble), somejavadouble )\n" +
    		"print( 'somejavastring', type(somejavastring), somejavastring )\n" +
    		"print( 'somejavaobject', type(somejavaobject), somejavaobject )\n" +
    		"print( 'somejavaarray', type(somejavaarray), somejavaarray, somejavaarray[1] )\n" +
    		"someluaint = 444\n" +
    		"someluadouble = 555.666\n" +
    		"someluastring = 'def'\n" +
    		"someluauserdata = somejavaobject\n" +
    		"someluatable = { 999, 111 }\n" +
    		"someluafunction = function(x) print( 'hello, world', x ) return 678 end\n" +
    		"" );
    b.put("somejavaint", 111);
    b.put("somejavadouble", 222.333);
    b.put("somejavastring", "abc");
    b.put("somejavaobject", new SomeUserClass());
    b.put("somejavaarray", new int[] { 777, 888 } );
    System.out.println( "eval: "+cs.eval(b) );
    Object someluaint = b.get("someluaint");
    Object someluadouble = b.get("someluaint");
    Object someluastring = b.get("someluastring");
    Object someluauserdata = b.get("someluauserdata");
    Object someluatable = b.get("someluatable");
    Object someluafunction = b.get("someluafunction");
    System.out.println( "someluaint: "+someluaint.getClass()+" "+someluaint );
    System.out.println( "someluadouble: "+someluadouble.getClass()+" "+someluadouble );
    System.out.println( "someluastring: "+someluastring.getClass()+" "+someluastring );
    System.out.println( "someluauserdata: "+someluauserdata.getClass()+" "+someluauserdata );
    System.out.println( "someluatable: "+someluatable.getClass()+" "+someluatable );
    System.out.println( "someluafunction: "+someluafunction.getClass()+" "+someluafunction );
    System.out.println( "someluafunction(345): "+((LuaValue) someluafunction).call(LuaValue.valueOf(345)) );
}
 
Example 13
Source File: GremlinGroovyScriptEngineSandboxedStandardTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEvalGraphTraversalSource() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()", bindings));

    engine = new GremlinGroovyScriptEngine(notSandboxed);
    try {
        bindings = engine.createBindings();
        bindings.put("g", g);
        bindings.put("marko", convertToVertexId(graph, "marko"));
        engine.eval("g.V(marko).next()", bindings);
        fail("Type checking should have forced an error as 'g' is not defined");
    } catch (Exception ex) {
        assertEquals(MultipleCompilationErrorsException.class, ex.getCause().getClass());
        assertThat(ex.getMessage(), containsString("The variable [g] is undeclared."));
    }

    engine = new GremlinGroovyScriptEngine(sandboxed);
    bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()", bindings));
    assertEquals(g.V(convertToVertexId(graph, "marko")).out("created").count().next(), engine.eval("g.V(marko).out(\"created\").count().next()", bindings));
}
 
Example 14
Source File: CompilableTest.java    From es6draft with MIT License 5 votes vote down vote up
@Test
public void compileStringWithContextAndBindings() throws ScriptException {
    CompiledScript script = compilable.compile("numberVal * 2");
    ScriptContext context = new SimpleScriptContext();
    Bindings bindings = engine.createBindings();
    bindings.put("numberVal", 8);
    context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

    assertThat(script.eval(context), instanceOfWith(Number.class, is(numberCloseTo(16))));
}
 
Example 15
Source File: ScriptRouter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>)inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
 
Example 16
Source File: ScopeTest.java    From jdk8u_nashorn 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 17
Source File: ConsStringTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsStringFlattening() throws ScriptException {
    final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);
    final Map<Object, Object> m = new HashMap<>();
    b.put("m", m);
    e.eval("var x = 'f'; x += 'oo'; var y = 'b'; y += 'ar'; m.put(x, y)");
    assertEquals("bar", m.get("foo"));
}
 
Example 18
Source File: ScriptRouter.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>)inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
 
Example 19
Source File: NashornJsEvaluator.java    From iotplatform with Apache License 2.0 4 votes vote down vote up
public static Bindings toBindings(Bindings bindings, List<KvEntry> entries) {
  for (KvEntry entry : entries) {
    bindings.put(entry.getKey(), getValue(entry));
  }
  return bindings;
}
 
Example 20
Source File: ScriptEngineTest.java    From es6draft with MIT License 4 votes vote down vote up
@Test
public void getAndPut() throws ScriptException {
    final String key1 = "key1", key2 = "key2";
    final String value1 = "value1", value2 = "value2", value3 = "value3";
    Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);

    // key-value is initially null
    assertThat(engine.get(key1), nullValue());
    assertThat(engineScope.get(key1), nullValue());

    // can set from engine key-value and retrieve values from engine and bindings
    engine.put(key1, value1);
    assertThat(engine.get(key1), instanceOfWith(String.class, is(value1)));
    assertThat(engineScope.get(key1), instanceOfWith(String.class, is(value1)));

    // can override from engine key-value and retrieve new values from engine and bindings
    engine.put(key1, value2);
    assertThat(engine.get(key1), instanceOfWith(String.class, is(value2)));
    assertThat(engineScope.get(key1), instanceOfWith(String.class, is(value2)));

    // can override key-value from bindings and retrieve new values from engine and bindings
    Object oldValueA = engineScope.put(key1, value3);
    assertThat(oldValueA, instanceOfWith(String.class, is(value2)));
    assertThat(engine.get(key1), instanceOfWith(String.class, is(value3)));
    assertThat(engineScope.get(key1), instanceOfWith(String.class, is(value3)));

    // can set key-value from bindings and retrieve values from engine and bindings
    Object oldValueB = engineScope.put(key2, value1);
    assertThat(oldValueB, nullValue());
    assertThat(engine.get(key2), instanceOfWith(String.class, is(value1)));
    assertThat(engineScope.get(key2), instanceOfWith(String.class, is(value1)));

    // can override key-value from bindings and retrieve new values from engine and bindings
    Object oldValueC = engineScope.put(key2, value2);
    assertThat(oldValueC, instanceOfWith(String.class, is(value1)));
    assertThat(engine.get(key2), instanceOfWith(String.class, is(value2)));
    assertThat(engineScope.get(key2), instanceOfWith(String.class, is(value2)));

    // can override key-value from engine and retrieve new values from engine and bindings
    engine.put(key2, value3);
    assertThat(engine.get(key2), instanceOfWith(String.class, is(value3)));
    assertThat(engineScope.get(key2), instanceOfWith(String.class, is(value3)));
}