Java 类javax.script.SimpleBindings 实例源码

项目:cas-5.1.0    文件:ScriptedRegisteredServiceAttributeReleasePolicy.java   
private static Map<String, Object> getAttributesFromInlineGroovyScript(final Map<String, Object> attributes,
                                                                       final Matcher matcherInline) throws ScriptException {
    final String script = matcherInline.group(1).trim();
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
    if (engine == null) {
        LOGGER.warn("Script engine is not available for Groovy");
        return new HashMap<>();
    }
    final Object[] args = {attributes, LOGGER};
    LOGGER.debug("Executing script, with parameters [{}]", args);

    final Bindings binding = new SimpleBindings();
    binding.put("attributes", attributes);
    binding.put("logger", LOGGER);
    return (Map<String, Object>) engine.eval(script, binding);
}
项目:ARCLib    文件:ScriptExecutor.java   
public Object executeScriptWithConsole(ScriptType type, String script, Map<String, Object> params, StringWriter console) {
    ScriptEngine scriptEngine = produceScriptEngine(type);

    if (console != null) {
        scriptEngine.getContext().setWriter(console);
    }

    SimpleBindings bindings = new SimpleBindings();
    bindings.putAll(params);
    bindings.put("spring", context);

    try {
        return scriptEngine.eval(script, bindings);
    } catch (ScriptException ex) {
        throw new GeneralException(ex);
    }
}
项目:openjdk-jdk10    文件:Test3.java   
public static void main(String[] args) throws Exception {
    System.out.println("\nTest3\n");
    final Reader reader = new FileReader(
        new File(System.getProperty("test.src", "."), "Test3.js"));
    ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = Helper.getJsEngine(m);
    if (engine == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    Bindings en = new SimpleBindings();
    engine.setBindings(en, ScriptContext.ENGINE_SCOPE);
    en.put("key", "engine value");
    Bindings gn = new SimpleBindings();
    engine.setBindings(gn, ScriptContext.GLOBAL_SCOPE);
    gn.put("key", "global value");
    engine.eval(reader);
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@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"));
}
项目:manifold    文件:SimpleParserImpl.java   
private Object parseObject()
{
  Bindings map = new SimpleBindings();
  advance();
  if( _token.getType() == TokenType.STRING )
  {
    parseMember( map );
    while( _token.getType() == TokenType.COMMA )
    {
      advance();
      parseMember( map );
    }
  }
  checkAndSkip( TokenType.RCURLY, "}" );
  return map;
}
项目:manifold    文件:JsonImplCodeGen.java   
private SrcClass genClass( String fqnImpl, JsonStructureType model )
{
  SrcClass srcClass = new SrcClass( fqnImpl, SrcClass.Kind.Class )
    .modifiers( !fqnImpl.equals( _fqn ) ? Modifier.STATIC : 0 )
    .imports( Bindings.class )
    .imports( SimpleBindings.class )
    .imports( IJsonIO.class )
    .imports( List.class )
    .imports( SourcePosition.class )
    //.iface( fqnIface )
    .superClass( JsonImplBase.class );
  addConstructors( srcClass );
  addProperties( srcClass, model );
  addInnerTypes( srcClass, model.getInnerTypes() );
  return srcClass;
}
项目:openjdk9    文件:ScopeTest.java   
@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"));
}
项目:kaziranga    文件:ScopeTest.java   
@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"));
}
项目:LiteGraph    文件:Session.java   
public Session(final String session, final Context context, final ConcurrentHashMap<String, Session> sessions) {
    logger.info("New session established for {}", session);
    this.session = session;
    this.bindings = new SimpleBindings();
    this.settings = context.getSettings();
    this.graphManager = context.getGraphManager();
    this.scheduledExecutorService = context.getScheduledExecutorService();
    this.sessions = sessions;

    final Settings.ProcessorSettings processorSettings = this.settings.processors.stream()
            .filter(p -> p.className.equals(SessionOpProcessor.class.getCanonicalName()))
            .findAny().orElse(SessionOpProcessor.DEFAULT_SETTINGS);
    this.configuredSessionTimeout = Long.parseLong(processorSettings.config.get(SessionOpProcessor.CONFIG_SESSION_TIMEOUT).toString());

    this.gremlinExecutor = initializeGremlinExecutor().create();
}
项目:LiteGraph    文件:ScriptEnginesTest.java   
@Test
public void shouldNotPreserveInstantiatedVariablesBetweenEvals() throws Exception {
    final ScriptEngines engines = new ScriptEngines(se -> {});
    engines.reload("gremlin-groovy", Collections.<String>emptySet(),
            Collections.<String>emptySet(), Collections.emptyMap());

    final Bindings localBindingsFirstRequest = new SimpleBindings();
    localBindingsFirstRequest.put("x", "there");
    assertEquals("herethere", engines.eval("z = 'here' + x", localBindingsFirstRequest, "gremlin-groovy"));

    try {
        final Bindings localBindingsSecondRequest = new SimpleBindings();
        engines.eval("z", localBindingsSecondRequest, "gremlin-groovy");
        fail("Should not have knowledge of z");
    } catch (Exception ex) {
        final Throwable root = ExceptionUtils.getRootCause(ex);
        assertThat(root, instanceOf(MissingPropertyException.class));
    }
}
项目:LiteGraph    文件:ScriptEnginesTest.java   
@Test
public void shouldMergeBindingsFromLocalAndGlobal() throws Exception {
    final ScriptEngines engines = new ScriptEngines(se -> {});
    engines.reload("gremlin-groovy", Collections.<String>emptySet(),
            Collections.<String>emptySet(), Collections.emptyMap());

    engines.loadPlugins(Arrays.asList(new GremlinPlugin() {
        @Override
        public String getName() {
            return "mock";
        }

        @Override
        public void pluginTo(final PluginAcceptor pluginAcceptor) throws IllegalEnvironmentException, PluginInitializationException {
            pluginAcceptor.addBinding("y", "here");
        }
    }));

    final Bindings localBindings = new SimpleBindings();
    localBindings.put("x", "there");

    assertEquals("herethere", engines.eval("y+x", localBindings, "gremlin-groovy"));
}
项目:LiteGraph    文件:ScriptEnginesTest.java   
@Test
public void shouldMergeBindingsWhereLocalOverridesGlobal() throws Exception {
    final ScriptEngines engines = new ScriptEngines(se -> {});
    engines.reload("gremlin-groovy", Collections.<String>emptySet(),
            Collections.<String>emptySet(), Collections.emptyMap());

    engines.loadPlugins(Arrays.asList(new GremlinPlugin() {
        @Override
        public String getName() {
            return "mock";
        }

        @Override
        public void pluginTo(final PluginAcceptor pluginAcceptor) throws IllegalEnvironmentException, PluginInitializationException {
            pluginAcceptor.addBinding("y", "here");
        }
    }));

    // the "y" below should override the global variable setting.
    final Bindings localBindings = new SimpleBindings();
    localBindings.put("y", "there");
    localBindings.put("z", "where");

    assertEquals("therewhere", engines.eval("y+z", localBindings, "gremlin-groovy"));
}
项目:LiteGraph    文件:GremlinExecutorTest.java   
@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();
}
项目:LiteGraph    文件:GremlinExecutorTest.java   
@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());
}
项目:LiteGraph    文件:GremlinGroovyScriptEngineTest.java   
@Test
public void shouldPromoteDefinedVarsInInterpreterModeWithBindings() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(new InterpreterModeCustomizerProvider());
    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));
}
项目:HeliosStreams    文件:AgentName.java   
/**
 * Attempts to determine the app name by looking up the value of the 
 * system property {@link #JS_APP_NAME}, and compiling its value
 * as a JS script, then returning the value of the evaluation of the script.
 * The following binds are passed to the script: <ul>
 *  <li><b>sysprops</b>: The system properties</li>
 *  <li><b>agprops</b>: The agent properties which will be an empty properties instance if {@link JMXHelper#getAgentProperties()} failed.</li>
 *  <li><b>envs</b>: A map of environment variables</li>
 *  <li><b>mbs</b>: The platform MBeanServer</li>
 *  <li><b>cla</b>: The command line arguments as an array of strings</li>
 * </ul>
 * @return The app name or null if {@link #JS_APP_NAME} was not defined
 * or did not compile, or did not return a valid app name
 */
public static String getJSAppName() {
    String js = System.getProperty(JS_APP_NAME, "").trim();
    if(js==null || js.isEmpty()) return null;
    try {
        ScriptEngine se = new ScriptEngineManager().getEngineByExtension("js");
        Bindings b = new SimpleBindings();
        b.put("sysprops", System.getProperties());
        b.put("envs", System.getenv());
        b.put("mbs", JMXHelper.getHeliosMBeanServer());
        b.put("cla", ManagementFactory.getRuntimeMXBean().getInputArguments().toArray(new String[0]));
        Properties p = JMXHelper.getAgentProperties();
        b.put("agprops", p);
        Object value = se.eval(js, b);
        if(value!=null && !value.toString().trim().isEmpty()) return value.toString().trim();
        return null;
    } catch (Exception ex) {
        return null;
    }
}
项目:HeliosStreams    文件:AgentName.java   
/**
 * Attempts to determine the app name by looking up the value of the 
 * system property {@link #JS_APP_NAME}, and compiling its value
 * as a JS script, then returning the value of the evaluation of the script.
 * The following binds are passed to the script: <ul>
 *  <li><b>sysprops</b>: The system properties</li>
 *  <li><b>agprops</b>: The agent properties which will be an empty properties instance if {@link JMXHelper#getAgentProperties()} failed.</li>
 *  <li><b>envs</b>: A map of environment variables</li>
 *  <li><b>mbs</b>: The platform MBeanServer</li>
 *  <li><b>cla</b>: The command line arguments as an array of strings</li>
 * </ul>
 * @return The app name or null if {@link #JS_APP_NAME} was not defined
 * or did not compile, or did not return a valid app name
 */
public static String getJSAppName() {
    String js = System.getProperty(JS_APP_NAME, "").trim();
    if(js==null || js.isEmpty()) return null;
    try {
        ScriptEngine se = new ScriptEngineManager().getEngineByExtension("js");
        Bindings b = new SimpleBindings();
        b.put("sysprops", System.getProperties());
        b.put("envs", System.getenv());
        b.put("mbs", JMXHelper.getHeliosMBeanServer());
        b.put("cla", ManagementFactory.getRuntimeMXBean().getInputArguments().toArray(new String[0]));
        Properties p = JMXHelper.getAgentProperties();
        b.put("agprops", p);
        Object value = se.eval(js, b);
        if(value!=null && !value.toString().trim().isEmpty()) return value.toString().trim();
        return null;
    } catch (Exception ex) {
        return null;
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:ScopeTest.java   
@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"));
}
项目:jdk8u_nashorn    文件:ScopeTest.java   
@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"));
}
项目:nashorn-commonjs-modules    文件:ModuleTest.java   
@Test
public void itCanEnableRequireInDifferentBindingsOnTheSameEngine() throws Throwable {
  NashornScriptEngine engine =
      (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
  Bindings bindings1 = new SimpleBindings();
  Bindings bindings2 = new SimpleBindings();

  Require.enable(engine, root, bindings1);

  assertNull(engine.getBindings(ScriptContext.ENGINE_SCOPE).get("require"));
  assertNotNull(bindings1.get("require"));
  assertNull(bindings2.get("require"));
  assertEquals("file1", ((Bindings) engine.eval("require('./file1')", bindings1)).get("file1"));

  try {
    engine.eval("require('./file1')", bindings2);
    fail();
  } catch (ScriptException ignored) {
  }

  Require.enable(engine, root, bindings2);
  assertNull(engine.getBindings(ScriptContext.ENGINE_SCOPE).get("require"));
  assertNotNull(bindings2.get("require"));
  assertEquals("file1", ((Bindings) engine.eval("require('./file1')", bindings2)).get("file1"));
}
项目:JShellScriptEngine    文件:JShellScriptEngineTest.java   
@Test
public void globalBindings() throws Exception {
    scriptEngine.setBindings(new SimpleBindings(), GLOBAL_SCOPE);
    scriptEngine.getBindings(GLOBAL_SCOPE).put("x", 2);

    assertEquals(2, scriptEngine.eval("x"));

    assertEquals(2, scriptEngine.getBindings(GLOBAL_SCOPE).get("x"));
    assertEquals(null, scriptEngine.getBindings(ENGINE_SCOPE).get("x"));
}
项目:JShellScriptEngine    文件:JShellScriptEngineTest.java   
@Test
public void newVariablesInEngineScope() throws Exception {
    scriptEngine.setBindings(new SimpleBindings(), GLOBAL_SCOPE);

    assertEquals(2, scriptEngine.eval("int x = 2;"));

    assertEquals(null, scriptEngine.getBindings(GLOBAL_SCOPE).get("x"));
    assertEquals(2, scriptEngine.getBindings(ENGINE_SCOPE).get("x"));
}
项目:JShellScriptEngine    文件:JShellScriptEngineTest.java   
@Test
public void globalAndEngineBindings() throws Exception {
    scriptEngine.setBindings(new SimpleBindings(), GLOBAL_SCOPE);
    scriptEngine.getBindings(GLOBAL_SCOPE).put("x", 2);
    scriptEngine.getBindings(ENGINE_SCOPE).put("x", 3);

    assertEquals(3, scriptEngine.eval("x"));
    assertEquals(4, scriptEngine.eval("x = 4"));

    assertEquals(2, scriptEngine.getBindings(GLOBAL_SCOPE).get("x"));
    assertEquals(4, scriptEngine.getBindings(ENGINE_SCOPE).get("x"));
}
项目:JShellScriptEngine    文件:JShellScriptEngineTest.java   
@Test
public void invalidBindings() throws Exception {
    scriptEngine.setBindings(new SimpleBindings(), GLOBAL_SCOPE);
    scriptEngine.getBindings(GLOBAL_SCOPE).put("a.b", 2);

    assertEquals(1, scriptEngine.eval("1"));
}
项目:open-rmbt    文件:TestScriptInterpreter.java   
public static boolean controlIf(String clause, AbstractResult<?> object) throws ScriptException {
    final Bindings bindings = new SimpleBindings(object.getResultMap());
    try {
        final Object result = jsEngine.eval(clause, bindings);
        return Boolean.parseBoolean(result.toString());

    } catch (javax.script.ScriptException e) {
        throw new ScriptException(ScriptException.ERROR_UNKNOWN + " IF: " + e.getMessage());
    }
}
项目:GuildBot    文件:CommandExecutor.java   
public CommandExecutor(final GuildBot guildBot)
{
    this.guildBot = guildBot;

    this.globalStore = new SimpleBindings();

    guildBot.getThreadPool().execute(this::init);
}
项目:OpenJSharp    文件:NashornScriptEngine.java   
@Override
public Bindings createBindings() {
    if (_global_per_engine) {
        // just create normal SimpleBindings.
        // We use same 'global' for all Bindings.
        return new SimpleBindings();
    }
    return createGlobalMirror(null);
}
项目:openjdk-jdk10    文件:Test5.java   
public static void main(String[] args) throws Exception {
        System.out.println("\nTest5\n");
        ScriptEngineManager m = new ScriptEngineManager();
        ScriptEngine engine = Helper.getJsEngine(m);
        if (engine == null) {
            System.out.println("Warning: No js engine found; test vacuously passes.");
            return;
        }
        Bindings g = new SimpleBindings();
        Bindings e = new SimpleBindings();
        g.put("key", "value in global");
        e.put("key", "value in engine");
        ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e, ScriptContext.ENGINE_SCOPE);
        System.out.println("engine scope only");
        e.put("count", new Integer(1));

        try (Reader reader = new FileReader(
            new File(System.getProperty("test.src", "."), "Test5.js"))) {
            engine.eval(reader,ctxt);
        }

        System.out.println("both scopes");
        ctxt.setBindings(g, ScriptContext.GLOBAL_SCOPE);
        e.put("count", new Integer(2));
        try (Reader reader = new FileReader(
            new File(System.getProperty("test.src", "."), "Test5.js"))) {
            engine.eval(reader,ctxt);
        }
        System.out.println("only global");
        e.put("count", new Integer(3));
        ctxt.removeAttribute("key", ScriptContext.ENGINE_SCOPE);
        try (Reader reader = new FileReader(
            new File(System.getProperty("test.src", "."), "Test5.js"))) {
            engine.eval(reader,ctxt);
        }
}
项目:openjdk-jdk10    文件:NashornScriptEngine.java   
@Override
public Bindings createBindings() {
    if (_global_per_engine) {
        // just create normal SimpleBindings.
        // We use same 'global' for all Bindings.
        return new SimpleBindings();
    }
    return createGlobalMirror();
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@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"));
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@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"));
}
项目:openjdk-jdk10    文件: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);
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@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);
}
项目:openjdk-jdk10    文件: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());
    }
}
项目:openjdk-jdk10    文件:ScopeTest.java   
public void program() throws ScriptException {
    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", "programText");
    String value = engine.eval("text", sc).toString();
    Assert.assertEquals(value, "programText");
    engine.put("program", this);
    engine.eval("program.method()");
    // eval again from here!
    value = engine.eval("text", sc).toString();
    Assert.assertEquals(value, "programText");
}
项目:openjdk-jdk10    文件:ScopeTest.java   
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");
    final String value = engine.eval("text", sc).toString();
    Assert.assertEquals(value, "methodText");
}
项目:manifold    文件:NashornJsonParser.java   
static Bindings wrapValueInBindings( Object result ) throws ScriptException
{
  if( result == null ||
      result instanceof List ||
      result instanceof String ||
      result instanceof Number ||
      result instanceof Boolean )
  {
    Bindings wrapper = new SimpleBindings();
    wrapper.put( "value", result );
    return wrapper;
  }
  throw new ScriptException( "Unexpected JSON result type: " + result.getClass().getName() );
}
项目:iotplatform    文件:NashornJsEvaluator.java   
public static Bindings getAttributeBindings(DeviceAttributes attributes) {
  Bindings bindings = new SimpleBindings();
  convertListEntries(bindings, CLIENT_SIDE, attributes.getClientSideAttributes());
  convertListEntries(bindings, SERVER_SIDE, attributes.getServerSideAttributes());
  convertListEntries(bindings, SHARED, attributes.getServerSidePublicAttributes());
  return bindings;
}
项目:openjdk9    文件:NashornScriptEngine.java   
@Override
public Bindings createBindings() {
    if (_global_per_engine) {
        // just create normal SimpleBindings.
        // We use same 'global' for all Bindings.
        return new SimpleBindings();
    }
    return createGlobalMirror();
}
项目:openjdk9    文件:ScopeTest.java   
@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"));
}