javax.script.Bindings Java Examples

The following examples show how to use javax.script.Bindings. 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 Project: oval   Author: sebthom   File: ExpressionLanguageJRubyImpl.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
   LOG.debug("Evaluating JavaScript expression: {1}", expression);
   try {
      final Bindings scope = engine.createBindings();
      final StringBuilder localVars = new StringBuilder();
      for (final Entry<String, ?> entry : values.entrySet()) {

         // workaround for http://ruby.11.x6.nabble.com/undefined-local-variable-in-ScriptEngine-eval-tp3452553p3452557.html
         scope.put("$" + entry.getKey(), entry.getValue()); // register as global var
         localVars.append(entry.getKey()) // // reference as local var
            .append("=$") //
            .append(entry.getKey()) //
            .append("\n");
      }

      return engine.eval(localVars.toString() + expression, scope);
   } catch (final ScriptException ex) {
      throw new ExpressionEvaluationException("Evaluating JRuby expression failed: " + expression, ex);
   }
}
 
Example #2
Source Project: pentaho-kettle   Author: pentaho   File: ScriptAddedFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static Object isNum( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
  Object FunctionContext ) {

  if ( ArgList.length == 1 ) {
    try {
      if ( isNull( ArgList[0] ) ) {
        return null;
      } else if ( isUndefined( ArgList[0] ) ) {
        return undefinedValue;
      }
      double sArg1 = (Double) ArgList[0];
      if ( Double.isNaN( sArg1 ) ) {
        return Boolean.FALSE;
      } else {
        return Boolean.TRUE;
      }
    } catch ( Exception e ) {
      return Boolean.FALSE;
    }
  } else {
    throw new RuntimeException( "The function call isNum requires 1 argument." );
  }
}
 
Example #3
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: MultiScopes.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}
 
Example #4
Source Project: dynkt   Author: xafero   File: KotlinCompiledScript.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Object eval(ScriptContext context) throws ScriptException {
	// Only compile if necessary (should be only the first time!)
	if (cachedClazz == null) {
		try {
			FileWriter out;
			IOUtils.write(script, out = new FileWriter(file));
			out.flush();
			out.close();
			cachedClazz = engine.compileScript(file);
		} catch (Exception e) {
			throw new ScriptException(e);
		}
	}
	// Evaluate it
	Bindings bnd = context.getBindings(ScriptContext.ENGINE_SCOPE);
	bnd.put(ScriptEngine.FILENAME, file.getAbsolutePath());
	return engine.evalClass(cachedClazz, bnd);
}
 
Example #5
Source Project: hop   Author: project-hop   File: ScriptAddedFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static String rpad( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
                           Object FunctionContext ) {
  try {
    if ( ArgList.length == 3 ) {
      if ( isNull( ArgList, new int[] { 0, 1, 2 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1, 2 } ) ) {
        return (String) undefinedValue;
      }
      String valueToPad = (String) ArgList[ 0 ];
      String filler = (String) ArgList[ 1 ];
      int size = (Integer) ArgList[ 2 ];

      while ( valueToPad.length() < size ) {
        valueToPad = valueToPad + filler;
      }
      return valueToPad;
    }
  } catch ( Exception e ) {
    throw new RuntimeException( "The function call rpad requires 3 arguments." );
  }
  return null;
}
 
Example #6
Source Project: tinkerpop   Author: apache   File: ScriptRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean nextKeyValue() throws IOException {
    while (true) {
        if (!this.lineRecordReader.nextKeyValue()) return false;
        try {
            final Bindings bindings = this.engine.createBindings();
            final StarGraph graph = StarGraph.open();
            bindings.put(GRAPH, graph);
            bindings.put(LINE, this.lineRecordReader.getCurrentValue().toString());
            final StarGraph.StarVertex sv = (StarGraph.StarVertex) script.eval(bindings);
            if (sv != null) {
                final Optional<StarGraph.StarVertex> vertex = sv.applyGraphFilter(this.graphFilter);
                if (vertex.isPresent()) {
                    this.vertexWritable.set(vertex.get());
                    return true;
                }
            }
        } catch (final ScriptException e) {
            throw new IOException(e.getMessage());
        }
    }
}
 
Example #7
Source Project: tinkerpop   Author: apache   File: GremlinGroovyScriptEngineOverGraphTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldProperlyHandleBindings() throws Exception {
    final Graph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.put("g", g);
    engine.put("marko", convertToVertexId(graph, "marko"));
    Assert.assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()"));

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("s", "marko");
    bindings.put("f", 0.5f);
    bindings.put("i", 1);
    bindings.put("b", true);
    bindings.put("l", 100l);
    bindings.put("d", 1.55555d);

    assertEquals(engine.eval("g.E().has('weight',f).next()", bindings), g.E(convertToEdgeId(graph, "marko", "knows", "vadas")).next());
    assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
}
 
Example #8
Source Project: incubator-atlas   Author: apache   File: Titan1Graph.java    License: Apache License 2.0 6 votes vote down vote up
private Object executeGremlinScript(String gremlinQuery) throws AtlasBaseException {
    GremlinGroovyScriptEngine scriptEngine = getGremlinScriptEngine();

    try {
        Bindings bindings = scriptEngine.createBindings();

        bindings.put("graph", getGraph());
        bindings.put("g", getGraph().traversal());

        Object result = scriptEngine.eval(gremlinQuery, bindings);

        return result;
    } catch (ScriptException e) {
        throw new AtlasBaseException(AtlasErrorCode.GREMLIN_SCRIPT_EXECUTION_FAILED, gremlinQuery);
    } finally {
        releaseGremlinScriptEngine(scriptEngine);
    }
}
 
Example #9
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: MultiScopes.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}
 
Example #10
Source Project: carbon-identity-framework   Author: wso2   File: JsAuthenticationContextTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetServiceProviderFromWrappedContext() throws Exception {

    final String SERVICE_PROVIDER_NAME = "service_provider_js_test";

    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setServiceProviderName(SERVICE_PROVIDER_NAME);

    JsAuthenticationContext jsAuthenticationContext = new JsAuthenticationContext(authenticationContext);
    Bindings bindings = scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE);
    bindings.put("context", jsAuthenticationContext);

    Object result = scriptEngine.eval("context.serviceProviderName");
    assertNotNull(result);
    assertEquals(result, SERVICE_PROVIDER_NAME, "Service Provider name set in AuthenticationContext is not " +
        "accessible from JSAuthenticationContext");
}
 
Example #11
Source Project: netbeans   Author: apache   File: TemplateUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String expandTemplate(Reader reader, Map<String, Object> values) {
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    try {
        eng.eval(reader);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();
}
 
Example #12
Source Project: iotplatform   Author: osswangxining   File: AlarmProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private Bindings buildBindings(RuleContext ctx, FromDeviceMsg msg) {
  Bindings bindings = NashornJsEvaluator.getAttributeBindings(ctx.getDeviceMetaData().getDeviceAttributes());
  if (msg != null) {
    switch (msg.getMsgType()) {
    case POST_ATTRIBUTES_REQUEST:
      bindings = NashornJsEvaluator.updateBindings(bindings, (UpdateAttributesRequest) msg);
      break;
    case POST_TELEMETRY_REQUEST:
      TelemetryUploadRequest telemetryMsg = (TelemetryUploadRequest) msg;
      for (List<KvEntry> entries : telemetryMsg.getData().values()) {
        bindings = NashornJsEvaluator.toBindings(bindings, entries);
      }
    }
  }
  return bindings;
}
 
Example #13
Source Project: es6draft   Author: anba   File: TypeConversionTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testUnsupportedWithBindings() throws ScriptException {
    // Unsupported Java classes end up as `null` in default bindings
    Bindings bindings = engine.createBindings();
    Object javaObject = new JavaObject();
    bindings.put("javaObject", javaObject);

    assertThat(bindings.get("javaObject"), nullValue());
    assertThat(engine.eval("javaObject", bindings), nullValue());

    assertThat(engine.eval("typeof javaObject", bindings), instanceOfWith(String.class, is("object")));
    assertThat(engine.eval("javaObject == null", bindings),
            instanceOfWith(Boolean.class, sameInstance(Boolean.TRUE)));
    assertThat(engine.eval("javaObject === void 0", bindings),
            instanceOfWith(Boolean.class, sameInstance(Boolean.FALSE)));
    assertThat(engine.eval("javaObject === null", bindings),
            instanceOfWith(Boolean.class, sameInstance(Boolean.TRUE)));
}
 
Example #14
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: ScopeTest.java    License: 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 #15
Source Project: pentaho-kettle   Author: pentaho   File: ScriptAddedFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static String resolveIP( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
  Object FunctionContext ) {
  String sRC = "";
  if ( ArgList.length == 2 ) {
    try {
      InetAddress addr = InetAddress.getByName( (String) ArgList[0] );
      if ( ( (String) ArgList[1] ).equals( "IP" ) ) {
        sRC = addr.getHostName();
      } else {
        sRC = addr.getHostAddress();
      }
      if ( sRC.equals( ArgList[0] ) ) {
        sRC = "-";
      }
    } catch ( Exception e ) {
      sRC = "-";
    }
  } else {
    throw new RuntimeException( "The function call resolveIP requires 2 arguments." );
  }

  return sRC;
}
 
Example #16
Source Project: nashorn-commonjs-modules   Author: malaporte   File: ModuleTest.java    License: MIT License 6 votes vote down vote up
@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"));
}
 
Example #17
Source Project: camunda-bpm-platform   Author: camunda   File: ScriptBindingsFactory.java    License: Apache License 2.0 5 votes vote down vote up
public Bindings createBindings(VariableScope variableScope, Bindings engineBindings) {
  List<Resolver> scriptResolvers = new ArrayList<Resolver>();
  for (ResolverFactory scriptResolverFactory: resolverFactories) {
    Resolver resolver = scriptResolverFactory.createResolver(variableScope);
    if (resolver!=null) {
      scriptResolvers.add(resolver);
    }
  }
  return new ScriptBindings(scriptResolvers, variableScope, engineBindings);
}
 
Example #18
Source Project: dubbo-2.6.5   Author: tianheframe   File: ScriptRouter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@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 Project: carbon-identity-framework   Author: wso2   File: JsAuthenticationContextTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testClaimAssignment() throws ScriptException {

    ClaimMapping claimMapping1 = ClaimMapping.build("", "", "", false);

    ClaimMapping claimMapping2 = ClaimMapping.build("Test.Remote.Claim.Url.2", "Test.Remote.Claim.Url.2", "",
        false);

    AuthenticatedUser authenticatedUser = new AuthenticatedUser();
    authenticatedUser.getUserAttributes().put(claimMapping1, "TestClaimVal1");
    authenticatedUser.getUserAttributes().put(claimMapping2, "TestClaimVal2");
    AuthenticationContext authenticationContext = new AuthenticationContext();
    setupAuthContextWithStepData(authenticationContext, authenticatedUser);

    JsAuthenticationContext jsAuthenticationContext = new JsAuthenticationContext(authenticationContext);
    Bindings bindings = scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE);
    bindings.put("context", jsAuthenticationContext);

    Object result = scriptEngine.eval("context.steps[1].subject.remoteClaims['Test.Remote.Claim.Url.1']");
    assertNull(result);
    result = scriptEngine.eval("context.steps[1].subject.remoteClaims['Test.Remote.Claim.Url.2']");
    assertEquals(result, "TestClaimVal2");

    scriptEngine.eval("context.steps[1].subject.remoteClaims['Test.Remote.Claim.Url.2'] = 'Modified2'");
    result = scriptEngine.eval("context.steps[1].subject.remoteClaims['Test.Remote.Claim.Url.2']");
    assertEquals(result, "Modified2");

}
 
Example #20
Source Project: enhydrator   Author: AdamBien   File: FunctionScriptLoader.java    License: Apache License 2.0 5 votes vote down vote up
public RowTransformer getRowTransformer(String scriptName) {
    return (Row input) -> {
        if (input == null) {
            return null;
        }
        Reader content = load(ROW_SCRIPT_FOLDER, scriptName);
        try {
            Bindings bindings = ScriptingEnvironmentProvider.create(manager, this.scriptEngineBindings, input);
            return (Row) engine.eval(content, bindings);
        } catch (ScriptException ex) {
            throw new IllegalStateException("Cannot evaluate script: " + scriptName, ex);
        }
    };
}
 
Example #21
Source Project: Mastering-Spring-5.1   Author: PacktPublishing   File: JavaScriptCode.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) throws ScriptException {
	final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
	final ScriptEngine scriptEngine = scriptEngineManager.getEngineByName( "Nashorn");
	final Bindings bindings = scriptEngine.createBindings();
	bindings.put( "str", "Let's pass from Java to JavaScript" );		         
	scriptEngine.eval( " print(str)", bindings );
}
 
Example #22
Source Project: tinkerpop   Author: apache   File: GremlinExecutorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEvalScriptWithGlobalAndLocalBindings() throws Exception {
    final Bindings g = new SimpleBindings();
    g.put("x", 1);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(g).create();
    final Bindings b = new SimpleBindings();
    b.put("y", 1);
    assertEquals(2, gremlinExecutor.eval("y+x", b).get());
    gremlinExecutor.close();
}
 
Example #23
Source Project: syndesis-extensions   Author: syndesisio   File: TelegramBotAction.java    License: Apache License 2.0 5 votes vote down vote up
void process(Exchange exchange) throws Exception {
    Bindings bindings = new SimpleBindings();
    bindings.put("env", System.getenv());
    bindings.put("sys", System.getProperties());
    bindings.put("body", exchange.hasOut() ? exchange.getOut().getBody() : exchange.getIn().getBody());
    bindings.put("message", exchange.hasOut() ? exchange.getOut() : exchange.getIn());
    bindings.put("exchange", exchange);
    bindings.put("lastcommand", this.lastImplementedCommand);

    String bot = commandimpl + "\n" + PRE_COMMAND + commandname + POST_COMMAND;

    this.engine.eval(bot, bindings);
}
 
Example #24
Source Project: dubbox   Author: hutai123   File: ScriptRouter.java    License: 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 #25
Source Project: es6draft   Author: anba   File: ScriptEngineScopeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void globalScopeAccess() throws ScriptException {
    Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
    globalScope.put("globalVar", "Aldebaran");

    assertThat(engine.eval("globalVar"), instanceOfWith(String.class, is("Aldebaran")));
}
 
Example #26
Source Project: dynkt   Author: xafero   File: KotlinScriptEngineTest.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testEvalFromFile2() throws FileNotFoundException, ScriptException {
	InputStreamReader code = getStream("hello1.kt");
	StringWriter out;
	Bindings bnd = engine.createBindings();
	bnd.put("out", new PrintWriter(out = new StringWriter()));
	Object result = engine.eval(code, bnd);
	assertNotNull(result);
	assertEquals("main", result.getClass().getDeclaredMethods()[0].getName());
	assertEquals("Hello, World!", out.toString().trim());
}
 
Example #27
Source Project: jdk8u60   Author: chenghanpeng   File: JavaSE6ScriptEngine.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void execute(Diagram d, String code) {
    try {
        Bindings b = bindings;
        b.put("graph", d);
        engine.eval(code, b);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example #28
Source Project: tinkerpop   Author: apache   File: GremlinExecutorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetGlobalBindings() throws Exception {
    final Bindings b = new SimpleBindings();
    final Object bound = new Object();
    b.put("x", bound);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().
            addPlugins("gremlin-groovy", triggerPlugin).
            globalBindings(b).create();
    assertEquals(bound, gremlinExecutor.getScriptEngineManager().getBindings().get("x"));
    gremlinExecutor.close();
}
 
Example #29
Source Project: jdk8u_nashorn   Author: JetBrains   File: NashornLinker.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static GuardedInvocation getMirrorConverter(final Class<?> sourceType, final Class<?> targetType) {
    // Could've also used (targetType.isAssignableFrom(ScriptObjectMirror.class) && targetType != Object.class) but
    // it's probably better to explicitly spell out the supported target types
    if (targetType == Map.class || targetType == Bindings.class || targetType == JSObject.class || targetType == ScriptObjectMirror.class) {
        if (ScriptObject.class.isAssignableFrom(sourceType)) {
            return new GuardedInvocation(CREATE_MIRROR);
        } else if (sourceType.isAssignableFrom(ScriptObject.class) || sourceType.isInterface()) {
            return new GuardedInvocation(CREATE_MIRROR, IS_SCRIPT_OBJECT);
        }
    }
    return null;
}
 
Example #30
Source Project: es6draft   Author: anba   File: ScriptEngineScopeTest.java    License: 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")));
}