javax.script.SimpleBindings Java Examples

The following examples show how to use javax.script.SimpleBindings. 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: ExportServlet.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
private void addScriptBindings(SlingScriptHelper scriptHelper, SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws IOException {
    SimpleBindings bindings = new SimpleBindings();
    bindings.put(SLING, scriptHelper);
    bindings.put(RESOURCE, request.getResource());
    bindings.put(SlingModelsScriptEngineFactory.RESOLVER, request.getResource().getResourceResolver());
    bindings.put(REQUEST, request);
    bindings.put(RESPONSE, response);
    try {
        bindings.put(READER, request.getReader());
    } catch (Exception e) {
        bindings.put(READER, new BufferedReader(new StringReader("")));
    }
    bindings.put(OUT, response.getWriter());
    bindings.put(LOG, logger);

    scriptEngineFactory.invokeBindingsValuesProviders(bindingsValuesProvidersByContext, bindings);

    SlingBindings slingBindings = new SlingBindings();
    slingBindings.putAll(bindings);

    request.setAttribute(SlingBindings.class.getName(), slingBindings);

}
 
Example #2
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void userEngineScopeBindingsRetentionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // definition retained with user's ENGINE_SCOPE Binding
    assertTrue(e.eval("typeof foo", newContext).equals("function"));

    final Bindings oldBindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
    // but not in another ENGINE_SCOPE binding
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("undefined"));

    // restore ENGINE_SCOPE and check again
    newContext.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("function"));
}
 
Example #3
Source File: ScopeTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void userEngineScopeBindingsRetentionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // definition retained with user's ENGINE_SCOPE Binding
    assertTrue(e.eval("typeof foo", newContext).equals("function"));

    final Bindings oldBindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
    // but not in another ENGINE_SCOPE binding
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("undefined"));

    // restore ENGINE_SCOPE and check again
    newContext.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("function"));
}
 
Example #4
Source File: CodeCompletionOperation.java    From camunda-bpm-workbench with GNU Affero General Public License v3.0 6 votes vote down vote up
public void execute(DebugSessionImpl debugSession, SuspendedExecutionImpl suspendedExecution) {
  CodeCompleterBuilder builder = new CodeCompleterBuilder();

  if (scopeId != null) {
    synchronized (suspendedExecution) {
      if(!suspendedExecution.isResumed) {
        ExecutionEntity executionEntity = suspendedExecution.getExecution();
        ScriptBindingsFactory bindingsFactory = Context.getProcessEngineConfiguration()
            .getScriptingEngines().getScriptBindingsFactory();
        Bindings scopeBindings = bindingsFactory.createBindings(executionEntity, new SimpleBindings());
        builder.bindings(scopeBindings);
      }
    }
  }

  List<CodeCompletionHint> hints = builder.buildCompleter().complete(prefix);
  debugSession.fireCodeCompletion(hints);
}
 
Example #5
Source File: TomEEEmbeddedMojo.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void scriptCustomization(final List<String> customizers, final String ext, final String base) {
    if (customizers == null || customizers.isEmpty()) {
        return;
    }
    final ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(ext);
    if (engine == null) {
        throw new IllegalStateException("No engine for " + ext + ". Maybe add the JSR223 implementation as plugin dependency.");
    }
    for (final String js : customizers) {
        try {
            final SimpleBindings bindings = new SimpleBindings();
            bindings.put("catalinaBase", base);
            engine.eval(new StringReader(js), bindings);
        } catch (final ScriptException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
 
Example #6
Source File: GremlinGroovyScriptEngineCompilationOptionsTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterLongCompilation() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(
            CompilationOptionsCustomizer.build().setExpectedCompilationTime(10).create());

    final int numberOfParameters = 3000;
    final Bindings b = new SimpleBindings();

    // generate a script that takes a long time to compile
    String script = "x = 0";
    for (int ix = 0; ix < numberOfParameters; ix++) {
        if (ix > 0 && ix % 100 == 0) {
            script = script + ";" + System.lineSeparator() + "x = x";
        }
        script = script + " + x" + ix;
        b.put("x" + ix, ix);
    }

    assertEquals(0, engine.getClassCacheLongRunCompilationCount());

    engine.eval(script, b);

    assertEquals(1, engine.getClassCacheLongRunCompilationCount());
}
 
Example #7
Source File: JavaScriptRuleEngine.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T _eval(String scriptText, Map<String, Object> data)throws RuleException{
	Bindings bindings = new SimpleBindings();
	if(context != null){
		bindings.put(Names.GLOBAL, context);
	}
	bindings.put(Names.LOCAL, data);
	
	// execution
	try {
		Object o = scriptEngine.eval(scriptText, bindings);
		
		if(o != null){
			return (T)o;
		}
		return null;
	} catch (ScriptException e) {
		throw new RuleException("Execute the script error", e);
	}
}
 
Example #8
Source File: NashornEngineUtil.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static SimpleHttpResponse process(SimpleHttpRequest httpRequest)
		throws NoSuchMethodException, ScriptException, IOException {
	CompiledScript compiled;
	Compilable engine;
	String scriptFilePath = "./src/main/resources/templates/js/script.js";
	
	engine = (Compilable) engineFactory.getScriptEngine();
	compiled = ((Compilable) engine).compile(Files.newBufferedReader(Paths.get(scriptFilePath),StandardCharsets.UTF_8));
	
	SimpleBindings global = new SimpleBindings();
	global.put("theReq", httpRequest);
	global.put("theResp", new SimpleHttpResponse());
	
	Object result = compiled.eval(global);
	SimpleHttpResponse resp = (SimpleHttpResponse) result;
	return resp;
}
 
Example #9
Source File: GroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIncludeCustomTypeTranslationForSomethingSilly() throws Exception {
    final TinkerGraph graph = TinkerGraph.open();
    final SillyClass notSillyEnough = SillyClass.from("not silly enough", 100);
    final GraphTraversalSource g = graph.traversal();

    // without type translation we get uglinesss
    final String scriptBad = GroovyTranslator.of("g").
            translate(g.inject(notSillyEnough).asAdmin().getBytecode()).getScript();
    assertEquals(String.format("g.inject(%s)", "not silly enough:100"), scriptBad);

    // with type translation we get valid gremlin
    final String scriptGood = GroovyTranslator.of("g", new SillyClassTranslator(false)).
            translate(g.inject(notSillyEnough).asAdmin().getBytecode()).getScript();
    assertEquals(String.format("g.inject(org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslatorTest.SillyClass.from('%s', (int) %s))", notSillyEnough.getX(), notSillyEnough.getY()), scriptGood);
    assertThatScriptOk(scriptGood, "g", g);

    final GremlinGroovyScriptEngine customEngine = new GremlinGroovyScriptEngine(new SillyClassTranslatorCustomizer());
    final Bindings b = new SimpleBindings();
    b.put("g", g);
    final Traversal t = customEngine.eval(g.inject(notSillyEnough).asAdmin().getBytecode(), b, "g");
    final SillyClass sc = (SillyClass) t.next();
    assertEquals(notSillyEnough.getX(), sc.getX());
    assertEquals(notSillyEnough.getY(), sc.getY());
    assertThat(t.hasNext(), is(false));
}
 
Example #10
Source File: GremlinExecutorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRaiseExceptionInWithResultOfLifeCycle() throws Exception {
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();
    final GremlinExecutor.LifeCycle lc = GremlinExecutor.LifeCycle.build()
            .withResult(r -> {
                throw new RuntimeException("no worky");
            }).create();

    final AtomicBoolean exceptionRaised = new AtomicBoolean(false);

    final CompletableFuture<Object> future = gremlinExecutor.eval("1+1", "gremlin-groovy", new SimpleBindings(), lc);
    future.handle((r, t) -> {
        exceptionRaised.set(t != null && t instanceof RuntimeException && t.getMessage().equals("no worky"));
        return null;
    }).get();

    assertThat(exceptionRaised.get(), is(true));

    gremlinExecutor.close();
}
 
Example #11
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleMaps() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final Script script = GroovyTranslator.of("g", true).translate(g.V().id().is(new LinkedHashMap<Object,Object>() {{
        put(3, "32");
        put(Arrays.asList(1, 2, 3.1d), 4);
    }}).asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(6, bindings.size());
    assertEquals(Integer.valueOf(3), bindings.get("_args_0"));
    assertEquals("32", bindings.get("_args_1"));
    assertEquals(Integer.valueOf(1), bindings.get("_args_2"));
    assertEquals(Integer.valueOf(2), bindings.get("_args_3"));
    assertEquals(Double.valueOf(3.1), bindings.get("_args_4"));
    assertEquals(Integer.valueOf(4), bindings.get("_args_5"));
    assertEquals("g.V().id().is([(_args_0):(_args_1),([_args_2, _args_3, _args_4]):(_args_5)])", script.getScript());
    final Script standard = GroovyTranslator.of("g").translate(g.V().id().is(new LinkedHashMap<Object,Object>() {{
        put(3, "32");
        put(Arrays.asList(1, 2, 3.1d), 4);
    }}).asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard.getScript(), script.getScript(), bindings, true);
}
 
Example #12
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void userEngineScopeBindingsTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    e.eval("function func() {}");

    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    // we are using a new bindings - so it should have 'func' defined
    final Object value = e.eval("typeof func", newContext);
    assertTrue(value.equals("undefined"));
}
 
Example #13
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void userEngineScopeBindingsRetentionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // definition retained with user's ENGINE_SCOPE Binding
    assertTrue(e.eval("typeof foo", newContext).equals("function"));

    final Bindings oldBindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
    // but not in another ENGINE_SCOPE binding
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("undefined"));

    // restore ENGINE_SCOPE and check again
    newContext.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("function"));
}
 
Example #14
Source File: ScriptEngineLambda.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public Object apply(final Object a) {
    try {
        final Bindings bindings = new SimpleBindings();
        bindings.put(A, a);
        return this.engine.eval(this.script, bindings);
    } catch (final ScriptException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example #15
Source File: GremlinExecutorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldOverrideAfterFailure() throws Exception {
    final AtomicInteger called = new AtomicInteger(0);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterFailure((b,t) -> called.set(1)).create();
    try {
        gremlinExecutor.eval("10/0", null, new SimpleBindings(),
                GremlinExecutor.LifeCycle.build().afterFailure((b,t) -> called.set(200)).create()).get();
        fail("Should have failed with division by zero");
    } catch (Exception ignored) {

    }

    // need to wait long enough for the callback to register
    Thread.sleep(500);

    assertEquals(200, called.get());
}
 
Example #16
Source File: MeecrowaveRunMojo.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
private void scriptCustomization(final List<String> customizers, final String ext, final Map<String, Object> customBindings) {
    if (customizers == null || customizers.isEmpty()) {
        return;
    }
    final ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(ext);
    if (engine == null) {
        throw new IllegalStateException("No engine for " + ext + ". Maybe add the JSR223 implementation as plugin dependency.");
    }
    for (final String js : customizers) {
        try {
            final SimpleBindings bindings = new SimpleBindings();
            bindings.put("project", project);
            engine.eval(new StringReader(js), bindings);
            bindings.putAll(customBindings);
        } catch (final ScriptException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
 
Example #17
Source File: ScopeTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void userEngineScopeBindingsRetentionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // definition retained with user's ENGINE_SCOPE Binding
    assertTrue(e.eval("typeof foo", newContext).equals("function"));

    final Bindings oldBindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
    // but not in another ENGINE_SCOPE binding
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("undefined"));

    // restore ENGINE_SCOPE and check again
    newContext.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("function"));
}
 
Example #18
Source File: GremlinGroovyScriptEngineTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPromoteDefinedVarsInInterpreterModeWithBindings() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(new InterpreterModeGroovyCustomizer());
    final Bindings b = new SimpleBindings();
    b.put("x", 2);
    engine.eval("def addItUp = { x, y -> x + y }", b);
    assertEquals(3, engine.eval("int xxx = 1 + x", b));
    assertEquals(4, engine.eval("yyy = xxx + 1", b));
    assertEquals(7, engine.eval("def zzz = yyy + xxx", b));
    assertEquals(4, engine.eval("zzz - xxx", b));
    assertEquals("accessible-globally", engine.eval("if (yyy > 0) { def inner = 'should-stay-local'; outer = 'accessible-globally' }\n outer", b));
    assertEquals("accessible-globally", engine.eval("outer", b));

    try {
        engine.eval("inner", b);
        fail("Should not have been able to access 'inner'");
    } catch (Exception ex) {
        final Throwable root = ExceptionUtils.getRootCause(ex);
        assertThat(root, instanceOf(MissingPropertyException.class));
    }

    assertEquals(10, engine.eval("addItUp(zzz,xxx)", b));
}
 
Example #19
Source File: ScopeTest.java    From openjdk-jdk8u-backup 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 #20
Source File: ScriptEngineScopeTest.java    From es6draft with MIT License 5 votes vote down vote up
@Test
public void accessToBuiltinsNonSharedSimpleBindings() throws ScriptException {
    Object defaultObject = engine.eval("Object");
    Object bindingsObject = engine.eval("Object", new SimpleBindings());

    assertThat(defaultObject, notNullValue());
    assertThat(bindingsObject, notNullValue());
    assertThat(defaultObject, Matchers.not(sameInstance(bindingsObject)));
}
 
Example #21
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void userEngineScopeBindingsNoLeakTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // in the default context's ENGINE_SCOPE, 'foo' shouldn't exist
    assertTrue(e.eval("typeof foo").equals("undefined"));
}
 
Example #22
Source File: ScriptEngineScopeTest.java    From es6draft with MIT License 5 votes vote down vote up
@Test
public void isolatedBindingsAndSimpleBindings() throws ScriptException {
    Bindings binding = new SimpleBindings();
    engine.eval("var value = 'Alnitak'", binding);

    assertThat(engine.eval("value", binding), instanceOfWith(String.class, is("Alnitak")));
    assertThat(engine.eval("typeof value"), instanceOfWith(String.class, is("undefined")));
    assertThat(engine.eval("typeof value", engine.createBindings()), instanceOfWith(String.class, is("undefined")));
    assertThat(engine.eval("typeof value", new SimpleBindings()), instanceOfWith(String.class, is("undefined")));
}
 
Example #23
Source File: ScopeTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
public void method() throws ScriptException {
    // a context with a new global bindings, same engine bindings
    final ScriptContext sc = new SimpleScriptContext();
    final Bindings global = new SimpleBindings();
    sc.setBindings(global, ScriptContext.GLOBAL_SCOPE);
    sc.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);
    global.put("text", "methodText");
    String value = engine.eval("text", sc).toString();
    Assert.assertEquals(value, "methodText");
}
 
Example #24
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEscapeStrings() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final Script script = GroovyTranslator.of("g", true).translate(g.addV("customer")
            .property("customer_id", 501L)
            .property("name", "Foo\u0020Bar")
            .property("age", 25)
            .property("special", "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?")
            .asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(9, bindings.size());
    assertEquals("customer", bindings.get("_args_0"));
    assertEquals("customer_id", bindings.get("_args_1"));
    assertEquals(Long.valueOf(501), bindings.get("_args_2"));
    assertEquals("name", bindings.get("_args_3"));
    assertEquals("Foo\u0020Bar", bindings.get("_args_4"));
    assertEquals("age", bindings.get("_args_5"));
    assertEquals(Integer.valueOf(25), bindings.get("_args_6"));
    assertEquals("special", bindings.get("_args_7"));
    assertEquals("`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?", bindings.get("_args_8"));
    assertEquals("g.addV(_args_0).property(_args_1,_args_2).property(_args_3,_args_4).property(_args_5,_args_6).property(_args_7,_args_8)", script.getScript());

    final Script standard = GroovyTranslator.of("g").translate(g.addV("customer")
            .property("customer_id", 501L)
            .property("name", "Foo\u0020Bar")
            .property("age", 25)
            .property("special", "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?")
            .asAdmin().getBytecode());

    bindings.put("g", g);
    //add vertex will return different vertex id
    assertParameterizedScriptOk(standard.getScript(), script.getScript(), bindings, false);
}
 
Example #25
Source File: GremlinExecutorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEvalScriptWithGlobalBindings() throws Exception {
    final Bindings b = new SimpleBindings();
    b.put("x", 1);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(b).create();
    assertEquals(2, gremlinExecutor.eval("1+x").get());
    gremlinExecutor.close();
}
 
Example #26
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void userEngineScopeBindingsNoLeakTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // in the default context's ENGINE_SCOPE, 'foo' shouldn't exist
    assertTrue(e.eval("typeof foo").equals("undefined"));
}
 
Example #27
Source File: NashornScriptEngine.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Bindings createBindings() {
    if (_global_per_engine) {
        // just create normal SimpleBindings.
        // We use same 'global' for all Bindings.
        return new SimpleBindings();
    }
    return createGlobalMirror();
}
 
Example #28
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleSet() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final Script script = GroovyTranslator.of("g", true).translate(g.V().id().is(new HashSet<Object>() {{
        add(3);
        add(Arrays.asList(1, 2, 3.1d));
        add(3);
        add("3");
    }}).asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(5, bindings.size());
    assertEquals(Integer.valueOf(3), bindings.get("_args_0"));
    assertEquals("3", bindings.get("_args_1"));
    assertEquals(Integer.valueOf(1), bindings.get("_args_2"));
    assertEquals(Integer.valueOf(2), bindings.get("_args_3"));
    assertEquals(Double.valueOf(3.1), bindings.get("_args_4"));
    assertEquals("g.V().id().is([_args_0, _args_1, [_args_2, _args_3, _args_4]] as Set)", script.getScript());

    final Script standard = GroovyTranslator.of("g" ).translate(g.V().id().is(new HashSet<Object>() {{
        add(3);
        add(Arrays.asList(1, 2, 3.1d));
        add(3);
        add("3");
    }}).asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard.getScript(), script.getScript(), bindings, true);
}
 
Example #29
Source File: ScopeTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void userEngineScopeBindingsNoLeakTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // in the default context's ENGINE_SCOPE, 'foo' shouldn't exist
    assertTrue(e.eval("typeof foo").equals("undefined"));
}
 
Example #30
Source File: SlingModelsScriptEngineFactory.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
void invokeBindingsValuesProviders(BindingsValuesProvidersByContext bindingsValuesProvidersByContext, SimpleBindings bindings) {
    final Collection<BindingsValuesProvider> bindingsValuesProviders =
            bindingsValuesProvidersByContext.getBindingsValuesProviders(this, SlingModelsScriptEngineFactory.BINDINGS_CONTEXT);

    if (!bindingsValuesProviders.isEmpty()) {
        Set<String> protectedKeys = new HashSet<String>();
        protectedKeys.addAll(SlingModelsScriptEngineFactory.PROTECTED_KEYS);

        ProtectedBindings protectedBindings = new ProtectedBindings(bindings, protectedKeys);
        for (BindingsValuesProvider provider : bindingsValuesProviders) {
            provider.addBindings(protectedBindings);
        }

    }
}