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 File: TemplateUtil.java    From netbeans with Apache License 2.0 7 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 #2
Source File: ModuleTest.java    From nashorn-commonjs-modules with 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 #3
Source File: KotlinCompiledScript.java    From dynkt with 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 #4
Source File: MultiScopes.java    From openjdk-jdk9 with 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 #5
Source File: JsAuthenticationContextTest.java    From carbon-identity-framework with 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 #6
Source File: Titan1Graph.java    From incubator-atlas with 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 #7
Source File: AlarmProcessor.java    From iotplatform with 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 #8
Source File: TypeConversionTest.java    From es6draft with 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 #9
Source File: MultiScopes.java    From openjdk-jdk8u with 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 File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void createBindingsTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    b.put("foo", 42.0);
    Object res = null;
    try {
        res = e.eval("foo == 42.0", b);
    } catch (final ScriptException | NullPointerException se) {
        se.printStackTrace();
        fail(se.getMessage());
    }

    assertEquals(res, Boolean.TRUE);
}
 
Example #11
Source File: ScriptAddedFunctions.java    From pentaho-kettle with 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 #12
Source File: ScriptAddedFunctions.java    From pentaho-kettle with 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 #13
Source File: ScriptAddedFunctions.java    From hop with 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 #14
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with 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 #15
Source File: ScriptRecordReader.java    From tinkerpop with 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 #16
Source File: ExpressionLanguageJRubyImpl.java    From oval with 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 #17
Source File: ScriptingEngines.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected Object evaluate(String script, String language, Bindings bindings) {
    ScriptEngine scriptEngine = getEngineByName(language);
    try {
        return scriptEngine.eval(script, bindings);
    } catch (ScriptException e) {
        throw new ActivitiException("problem evaluating script: " + e.getMessage(), e);
    }
}
 
Example #18
Source File: ModuleTest.java    From nashorn-commonjs-modules with MIT License 5 votes vote down vote up
@Test
public void itCanLoadModulesSpecifyingOnlyTheFolderWhenPackageJsonHasAMainFile()
    throws Throwable {
  Folder dir = mock(Folder.class);
  when(dir.getFile("package.json")).thenReturn("{ \"main\": \"foo.js\" }");
  when(dir.getFile("foo.js")).thenReturn("exports.foo = 'foo';");
  when(root.getFolder("dir")).thenReturn(dir);
  assertEquals("foo", ((Bindings) require.require("./dir")).get("foo"));
}
 
Example #19
Source File: ScriptRunPerformence.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
private Bindings createBinding(Map<String, Object> vars,
        ScriptEngine scriptEngine) {
    Bindings binds = scriptEngine.createBindings();
    if (null != vars && !vars.isEmpty()) {
        binds.putAll(vars);
    }
    
    return binds;
}
 
Example #20
Source File: LexicalBindingTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test multi-threaded access to global lexically declared variables for shared script classes with multiple globals.
 */
@Test
public static void multiThreadedLetTest() throws ScriptException, InterruptedException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine e = factory.getScriptEngine(LANGUAGE_ES6);
    final Bindings b = e.createBindings();
    final ScriptContext origContext = e.getContext();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    final String sharedScript = "foo";

    assertEquals(e.eval("let foo = 'original context';", origContext), null);
    assertEquals(e.eval("let foo = 'new context';", newCtxt), null);

    final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
    t1.start();
    t2.start();
    t1.join();
    t2.join();

    assertEquals(e.eval("foo = 'newer context';", newCtxt), "newer context");
    final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));

    t3.start();
    t4.start();
    t3.join();
    t4.join();

    assertEquals(e.eval(sharedScript), "original context");
    assertEquals(e.eval(sharedScript, newCtxt), "newer context");
}
 
Example #21
Source File: ScopeTest.java    From jdk8u60 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 #22
Source File: ConsStringTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsStringFromMirror() throws ScriptException {
    final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);
    //final Map<Object, Object> m = new HashMap<>();
    e.eval("var x = 'f'; x += 'oo'; var obj = {x: x};");
    assertEquals("foo", ((JSObject)b.get("obj")).getMember("x"));
}
 
Example #23
Source File: ScopeTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test multi-threaded access to primitive prototype properties for shared script classes with multiple globals.
 */
@Test
public static void multiThreadedPrimitiveTest() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    final ScriptContext origContext = e.getContext();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

    final Object obj1 = e.eval("String.prototype.foo = 'original context';", origContext);
    final Object obj2 = e.eval("String.prototype.foo = 'new context';", newCtxt);
    assertEquals(obj1, "original context");
    assertEquals(obj2, "new context");
    final String sharedScript = "''.foo";

    final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
    t1.start();
    t2.start();
    t1.join();
    t2.join();

    final Object obj3 = e.eval("delete String.prototype.foo; Object.prototype.foo = 'newer context';", newCtxt);
    assertEquals(obj3, "newer context");
    final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));

    t3.start();
    t4.start();
    t3.join();
    t4.join();

    Assert.assertEquals(e.eval(sharedScript), "original context");
    Assert.assertEquals(e.eval(sharedScript, newCtxt), "newer context");
}
 
Example #24
Source File: ScopeTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test multi-threaded access to global getters and setters for shared script classes with multiple globals.
 */
@Test
public static void getterSetterTest() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    final ScriptContext origContext = e.getContext();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    final String sharedScript = "accessor1";

    e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), origContext);
    assertEquals(e.eval("accessor1 = 1;"), 1);
    assertEquals(e.eval(sharedScript), 1);

    e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), newCtxt);
    assertEquals(e.eval("accessor1 = 2;", newCtxt), 2);
    assertEquals(e.eval(sharedScript, newCtxt), 2);


    final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, 1, 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, 2, 1000));

    t1.start();
    t2.start();
    t1.join();
    t2.join();

    assertEquals(e.eval(sharedScript), 1);
    assertEquals(e.eval(sharedScript, newCtxt), 2);
    assertEquals(e.eval("v"), 1);
    assertEquals(e.eval("v", newCtxt), 2);
}
 
Example #25
Source File: JDK_8078414_Test.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCanNotConvertArbitraryClassToMirror() {
    assertCanNotConvert(Double.class, Map.class);
    assertCanNotConvert(Double.class, Bindings.class);
    assertCanNotConvert(Double.class, JSObject.class);
    assertCanNotConvert(Double.class, ScriptObjectMirror.class);
}
 
Example #26
Source File: AbstractEvaluatableScriptAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Note, calling this method modifies the underlying {@link ScriptEngine},
 * preventing concurrent use of the ScriptEngine (Nashorn's {@link ScriptEngine} and
 * {@link javax.script.CompiledScript} is thread-safe, but {@link Bindings} isn't).
 */
InvocableScriptAdapter prepareInvokableScript(final ScriptBindingsConfigurer bindingsConfigurer) {
    final Bindings bindings = createBindings(bindingsConfigurer);
    evalUnchecked(bindings);
    final ScriptEngine engine = getEngine();
    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    return new InvocableScriptAdapter(scriptModel, engine);
}
 
Example #27
Source File: NashornJsEvaluator.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public static Bindings convertListEntries(Bindings bindings, String attributesVarName,
    Collection<AttributeKvEntry> attributes) {
  Map<String, Object> attrMap = new HashMap<>();
  for (AttributeKvEntry attr : attributes) {
    if (!CLIENT_SIDE.equalsIgnoreCase(attr.getKey()) && !SERVER_SIDE.equalsIgnoreCase(attr.getKey())
        && !SHARED.equalsIgnoreCase(attr.getKey())) {
      bindings.put(attr.getKey(), getValue(attr));
    }
    attrMap.put(attr.getKey(), getValue(attr));
  }
  bindings.put(attributesVarName, attrMap);
  return bindings;
}
 
Example #28
Source File: JavaSE6ScriptEngine.java    From openjdk-jdk8u-backup with 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 #29
Source File: ScriptAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static Object quarter( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
  Object FunctionContext ) {
  try {
    if ( ArgList.length == 1 ) {
      if ( isNull( ArgList[0] ) ) {
        return new Double( Double.NaN );
      } else if ( isUndefined( ArgList[0] ) ) {
        return undefinedValue;
      }
      java.util.Date dArg1 = (java.util.Date) ArgList[0];
      Calendar cal = Calendar.getInstance();
      cal.setTime( dArg1 );

      // Patch by Ingo Klose: calendar months start at 0 in java.
      int iMonth = cal.get( Calendar.MONTH );
      if ( iMonth <= 2 ) {
        return new Double( 1 );
      } else if ( iMonth <= 5 ) {
        return new Double( 2 );
      } else if ( iMonth <= 8 ) {
        return new Double( 3 );
      } else {
        return new Double( 4 );
      }
    } else {
      throw new RuntimeException( "The function call quarter requires 1 argument." );
    }
  } catch ( Exception e ) {
    throw new RuntimeException( e.toString() );
  }
}
 
Example #30
Source File: LexicalBindingTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test multi-threaded access to global lexically declared variables for shared script classes with multiple globals.
 */
@Test
public static void multiThreadedLetTest() throws ScriptException, InterruptedException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine e = factory.getScriptEngine(LANGUAGE_ES6);
    final Bindings b = e.createBindings();
    final ScriptContext origContext = e.getContext();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    final String sharedScript = "foo";

    assertEquals(e.eval("let foo = 'original context';", origContext), null);
    assertEquals(e.eval("let foo = 'new context';", newCtxt), null);

    final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
    t1.start();
    t2.start();
    t1.join();
    t2.join();

    assertEquals(e.eval("foo = 'newer context';", newCtxt), "newer context");
    final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));

    t3.start();
    t4.start();
    t3.join();
    t4.join();

    assertEquals(e.eval(sharedScript), "original context");
    assertEquals(e.eval(sharedScript, newCtxt), "newer context");
}