Java Code Examples for javax.script.ScriptContext#setAttribute()

The following examples show how to use javax.script.ScriptContext#setAttribute() . 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: ScriptEngineScopeTest.java    From es6draft with MIT License 6 votes vote down vote up
@Test
public void scopeInteractionNewContextPropertyAssignment() throws ScriptException {
    ScriptContext context = new SimpleScriptContext();
    context.setBindings(engine.getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE);
    context.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    context.setAttribute("value", "Phecda", ScriptContext.ENGINE_SCOPE);
    context.setAttribute("value", "Scheat", ScriptContext.GLOBAL_SCOPE);

    engine.eval("this.value = 'Aludra'", context);

    assertThat(engine.eval("this.value", context), instanceOfWith(String.class, is("Aludra")));
    assertThat(engine.eval("value", context), instanceOfWith(String.class, is("Aludra")));
    assertThat(context.getAttribute("value", ScriptContext.ENGINE_SCOPE),
            instanceOfWith(String.class, is("Aludra")));
    assertThat(context.getAttribute("value", ScriptContext.GLOBAL_SCOPE),
            instanceOfWith(String.class, is("Scheat")));
}
 
Example 2
Source File: JuelScriptEngine.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public static void importFunctions(ScriptContext ctx, String namespace, Object obj) {
  Class<?> clazz = null;
  if (obj instanceof Class) {
    clazz = (Class<?>) obj;
  } else if (obj instanceof String) {
    try {
      clazz = ReflectUtil.loadClass((String) obj);
    } catch (ActivitiException ae) {
      throw new ELException(ae);
    }
  } else {
    throw new ELException("Class or class name is missing");
  }
  Method[] methods = clazz.getMethods();
  for (Method m : methods) {
    int mod = m.getModifiers();
    if (Modifier.isStatic(mod) && Modifier.isPublic(mod)) {
      String name = namespace + ":" + m.getName();
      ctx.setAttribute(name, m, ScriptContext.ENGINE_SCOPE);
    }
  }
}
 
Example 3
Source File: SReadableGraph.java    From constellation with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate a function against each vertex on the graph.
 *
 * Note: This method will only work for Python scripts as it makes use of
 * Python specific syntax.
 *
 * @param callback the function to evaluate.
 * @throws ScriptException
 */
public void withVertices(final Object callback) throws ScriptException {
    try {
        final ScriptContext context = graph.getEngine().getContext();
        context.setAttribute(FUNC, callback, ScriptContext.ENGINE_SCOPE);

        final int vertexCount = readableGraph.getVertexCount();
        for (int position = 0; position < vertexCount; position++) {
            final int vertexId = readableGraph.getVertex(position);

            context.setAttribute("__p1", new SVertex(readableGraph, vertexId), ScriptContext.ENGINE_SCOPE);
            graph.getEngine().eval(FUNC_P1);
        }
    } finally {
        readableGraph.release();
    }
}
 
Example 4
Source File: TrustedScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void evalFileNameWithSpecialCharsTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine engine = fac.getScriptEngine(new String[] { "--verify-code=true" });
    final ScriptContext ctxt = new SimpleScriptContext();
    // use file name with "dangerous" chars.
    ctxt.setAttribute(ScriptEngine.FILENAME, "<myscript>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var a = 3;");
    ctxt.setAttribute(ScriptEngine.FILENAME, "[myscript]", ScriptContext.ENGINE_SCOPE);
    engine.eval("var h = 'hello';");
    ctxt.setAttribute(ScriptEngine.FILENAME, ";/\\$.", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
    // name used by jjs shell tool for the interactive mode
    ctxt.setAttribute(ScriptEngine.FILENAME, "<shell>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
}
 
Example 5
Source File: ScriptExecutor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
protected void restoreVars ( final ScriptContext context, final Map<String, Object> vars )
{
    if ( vars == null )
    {
        return;
    }

    for ( final Map.Entry<String, Object> entry : vars.entrySet () )
    {
        if ( entry.getValue () == null )
        {
            context.removeAttribute ( entry.getKey (), ScriptContext.ENGINE_SCOPE );
        }
        else
        {
            context.setAttribute ( entry.getKey (), entry.getValue (), ScriptContext.ENGINE_SCOPE );
        }
    }
}
 
Example 6
Source File: TrustedScriptEngineTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void evalFileNameWithSpecialCharsTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine engine = fac.getScriptEngine(new String[] { "--verify-code=true" });
    final ScriptContext ctxt = new SimpleScriptContext();
    // use file name with "dangerous" chars.
    ctxt.setAttribute(ScriptEngine.FILENAME, "<myscript>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var a = 3;");
    ctxt.setAttribute(ScriptEngine.FILENAME, "[myscript]", ScriptContext.ENGINE_SCOPE);
    engine.eval("var h = 'hello';");
    ctxt.setAttribute(ScriptEngine.FILENAME, ";/\\$.", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
    // name used by jjs shell tool for the interactive mode
    ctxt.setAttribute(ScriptEngine.FILENAME, "<shell>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
}
 
Example 7
Source File: JavascriptEngine.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ScriptException, NoSuchMethodException, JsonProcessingException, InterruptedException {
  ScriptEngine engine = buildEngine();
  Invocable invocable = (Invocable) engine;
  engine.eval("load('E:/study/extensions/bilibili-helper/dist/hook.js')");
  HttpRequestForm requestForm = new HttpRequestForm();
  requestForm.setUrl("https://www.bilibili.com/video/av34765642");
  Object result = invocable.invokeFunction("error");
  ScriptContext ctx = new SimpleScriptContext();
  ctx.setAttribute("result", result, ScriptContext.ENGINE_SCOPE);
  System.out.println(engine.eval("!!result&&typeof result=='object'&&typeof result.then=='function'", ctx));
}
 
Example 8
Source File: ScriptEngineTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 9
Source File: ScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 10
Source File: CoreTask.java    From greycat with Apache License 2.0 5 votes vote down vote up
/**
 * @native ts
 * var print = console.log;
 * var println = console.log;
 * var ctx = context;
 * return eval(script);
 */
private static boolean executeScript(String script, TaskContext context) {
    ScriptContext scriptCtx = new SimpleScriptContext();
    scriptCtx.setAttribute("ctx", context, ScriptContext.ENGINE_SCOPE);
    try {
        return (boolean) TaskHelper.SCRIPT_ENGINE.eval(script, scriptCtx);
    } catch (ScriptException | ClassCastException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 11
Source File: ScriptEngineScopeTest.java    From es6draft with MIT License 5 votes vote down vote up
@Test
public void bindingValueWithThisExplicitContextSimpleBindings() throws ScriptException {
    ScriptContext context = new SimpleScriptContext();
    context.setAttribute("value", "Markeb", ScriptContext.ENGINE_SCOPE);

    assertThat(engine.eval("this.value", context), nullValue());
}
 
Example 12
Source File: ScriptEngineTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
 
Example 13
Source File: ScriptInput.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected Double handleEval ( final long timestamp )
{
    if ( this.scriptExecutor == null )
    {
        return null;
    }

    final ScriptContext context = new SimpleScriptContext ();
    context.setAttribute ( "timestamp", timestamp, ScriptContext.GLOBAL_SCOPE ); //$NON-NLS-1$
    try
    {
        final Map<String, Object> var = new HashMap<String, Object> ( 1 );
        var.put ( "timestamp", timestamp ); //$NON-NLS-1$
        final Object result = this.scriptExecutor.execute ( context, var );
        if ( result == null )
        {
            return null;
        }
        if ( result instanceof Number )
        {
            return ( (Number)result ).doubleValue ();
        }
        else
        {
            return Double.parseDouble ( result.toString () );
        }
    }
    catch ( final Exception e )
    {
        return null;
    }
}
 
Example 14
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGlobalScopeSearch() throws Exception {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext c = e.getContext();
    c.setAttribute("name1234", "value", ScriptContext.GLOBAL_SCOPE);
    assertEquals(c.getAttribute("name1234"), "value");
    assertEquals(c.getAttributesScope("name1234"),
        ScriptContext.GLOBAL_SCOPE);
}
 
Example 15
Source File: ScopeTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGlobalScopeSearch() throws Exception {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext c = e.getContext();
    c.setAttribute("name1234", "value", ScriptContext.GLOBAL_SCOPE);
    assertEquals(c.getAttribute("name1234"), "value");
    assertEquals(c.getAttributesScope("name1234"),
        ScriptContext.GLOBAL_SCOPE);
}
 
Example 16
Source File: ScriptEngineScopeTest.java    From es6draft with MIT License 5 votes vote down vote up
@Test
public void bindingValueWithThisExplicitContext() throws ScriptException {
    ScriptContext context = new SimpleScriptContext();
    context.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    context.setAttribute("value", "Markab", ScriptContext.ENGINE_SCOPE);

    assertThat(engine.eval("this.value", context), instanceOfWith(String.class, is("Markab")));
}
 
Example 17
Source File: SCollection.java    From constellation with Apache License 2.0 5 votes vote down vote up
private SCollection filterTransactions(final Object callback) throws ScriptException {
    final ScriptContext context = engine.getContext();
    context.setAttribute("__func", callback, ScriptContext.ENGINE_SCOPE);

    final BitSet transactions = new BitSet();
    for (int txId = elementIds.nextSetBit(0); txId >= 0; txId = elementIds.nextSetBit(txId + 1)) {
        context.setAttribute("__p1", new STransaction(readableGraph, txId), ScriptContext.ENGINE_SCOPE);
        final Object b = engine.eval("__func(__p1)");
        if ((Boolean) b) {
            transactions.set(txId);
        }
    }

    return new SCollection(engine, readableGraph, GraphElementType.TRANSACTION, transactions);
}
 
Example 18
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testScriptContext_NPE_IAE() throws Exception {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext c = e.getContext();
    try {
        c.getAttribute("");
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae1) {}

    try {
        c.getAttribute(null);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe1) {}

    try {
        c.getAttribute("", ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae2) {}

    try {
        c.getAttribute(null, ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe2) {}

    try {
        c.removeAttribute("", ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae3) {}

    try {
        c.removeAttribute(null, ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe3) {}

    try {
        c.setAttribute("", "value", ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae4) {}

    try {
        c.setAttribute(null, "value", ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe4) {}

    try {
        c.getAttributesScope("");
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae5) {}

    try {
        c.getAttributesScope(null);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe5) {}
}
 
Example 19
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the script at the specified location and returns the result.
 *
 * @param filePath Script path and file name.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @param args Function/method arguments.
 * @return The script result.
 * @throws ScriptException
 * @throws NoSuchMethodException
 * @throws IOException
 * @throws IllegalArgumentException
 */
public static Object executeScript(String filePath, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException, IOException {
    Assert.notNull("filePath", filePath, "scriptContext", scriptContext);
    scriptContext.setAttribute(ScriptEngine.FILENAME, filePath, ScriptContext.ENGINE_SCOPE);
    if (functionName == null) {
        // The Rhino script engine will not work when invoking a function on a compiled script.
        // The test for null can be removed when the engine is fixed.
        CompiledScript script = compileScriptFile(filePath);
        if (script != null) {
            return executeScript(script, functionName, scriptContext, args);
        }
    }
    String fileExtension = getFileExtension(filePath);
    if ("bsh".equalsIgnoreCase(fileExtension)) { // SCIPIO: 2018-09-19: Warn here, there's nowhere else we can do it...
        Debug.logWarning("Deprecated Beanshell script file invoked (" + filePath + "); "
                + "this is a compatibility mode only (runs as Groovy); please convert to Groovy script", module);
        // FIXME?: This does not properly use the GroovyLangVariant.BSH bindings for scripts in filesystem... unclear if should have
        fileExtension = "groovy";
    }
    ScriptEngineManager manager = getScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension(fileExtension);
    if (engine == null) {
        throw new IllegalArgumentException("The script type is not supported for location: " + filePath);
    }
    engine = configureScriptEngineForInvoke(engine); // SCIPIO: 2017-01-27: Custom configurations for the engine
    if (Debug.verboseOn()) {
        Debug.logVerbose("Begin processing script [" + filePath + "] using engine " + engine.getClass().getName(), module);
    }
    engine.setContext(scriptContext);
    URL scriptUrl = FlexibleLocation.resolveLocation(filePath);
    try (
            InputStreamReader reader = new InputStreamReader(new FileInputStream(scriptUrl.getFile()), UtilIO
                    .getUtf8());) {
        Object result = engine.eval(reader);
        if (UtilValidate.isNotEmpty(functionName)) {
            try {
                Invocable invocableEngine = (Invocable) engine;
                result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
            } catch (ClassCastException e) {
                throw new ScriptException("Script engine " + engine.getClass().getName()
                        + " does not support function/method invocations");
            }
        }
        return result;
    }
}
 
Example 20
Source File: ScopeTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testScriptContext_NPE_IAE() throws Exception {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext c = e.getContext();
    try {
        c.getAttribute("");
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae1) {}

    try {
        c.getAttribute(null);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe1) {}

    try {
        c.getAttribute("", ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae2) {}

    try {
        c.getAttribute(null, ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe2) {}

    try {
        c.removeAttribute("", ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae3) {}

    try {
        c.removeAttribute(null, ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe3) {}

    try {
        c.setAttribute("", "value", ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae4) {}

    try {
        c.setAttribute(null, "value", ScriptContext.ENGINE_SCOPE);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe4) {}

    try {
        c.getAttributesScope("");
        throw new AssertionError("should have thrown IAE");
    } catch (IllegalArgumentException iae5) {}

    try {
        c.getAttributesScope(null);
        throw new AssertionError("should have thrown NPE");
    } catch (NullPointerException npe5) {}
}