javax.script.Bindings#put ( )源码实例Demo

下面列出了javax.script.Bindings#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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);
    }
}
 
源代码2 项目: jdk8u60   文件: ScriptObjectMirrorTest.java
@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));
}
 
源代码3 项目: TencentKona-8   文件: ScopeTest.java
@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);
}
 
源代码4 项目: jeddict   文件: FileUtil.java
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();
        }
    }
}
 
源代码5 项目: tinkerpop   文件: GremlinGroovyScriptEngine.java
@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);
}
 
源代码6 项目: es6draft   文件: ScriptEngineScopeTest.java
@Test
public void bindingValueWithThisExplicitSimpleBinding() throws ScriptException {
    Bindings binding = new SimpleBindings();
    binding.put("value", "Sabik");

    assertThat(engine.eval("this.value", binding), nullValue());
}
 
源代码7 项目: dubbox-hystrix   文件: ScriptRouter.java
@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;
    }
}
 
源代码8 项目: openjdk-8-source   文件: ConsStringTest.java
@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"));
}
 
源代码9 项目: jdk8u_nashorn   文件: ScopeTest.java
@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);
}
 
源代码10 项目: dubbox   文件: ScriptRouter.java
@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;
    }
}
 
源代码11 项目: es6draft   文件: CompilableTest.java
@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))));
}
 
@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));
}
 
源代码13 项目: luaj   文件: ScriptEngineSample.java
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)) );
}
 
源代码14 项目: nifi   文件: ClojureScriptEngine.java
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);
}
 
源代码15 项目: jdk8u_nashorn   文件: ConsStringTest.java
@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]);
}
 
源代码16 项目: o2oa   文件: BaseAction.java
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;
	}
}
 
源代码17 项目: TencentKona-8   文件: ConsStringTest.java
@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"));
}
 
源代码18 项目: openjdk-jdk9   文件: ScopeTest.java
@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());
    }
}
 
源代码19 项目: iotplatform   文件: NashornJsEvaluator.java
public static Bindings toBindings(Bindings bindings, List<KvEntry> entries) {
  for (KvEntry entry : entries) {
    bindings.put(entry.getKey(), getValue(entry));
  }
  return bindings;
}
 
源代码20 项目: es6draft   文件: ScriptEngineTest.java
@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)));
}