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

The following examples show how to use javax.script.ScriptContext#setAttribute() . These examples are extracted from open source projects. 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
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 2
Source Project: constellation   File: SReadableGraph.java    License: 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 3
Source Project: neoscada   File: ScriptExecutor.java    License: 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 4
@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
@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 6
Source Project: es6draft   File: ScriptEngineScopeTest.java    License: 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 7
@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 8
Source Project: constellation   File: SCollection.java    License: 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 9
Source Project: es6draft   File: ScriptEngineScopeTest.java    License: 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 10
@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 11
Source Project: hottub   File: ScopeTest.java    License: 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 12
Source Project: neoscada   File: ScriptInput.java    License: 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 13
Source Project: proxyee-down   File: JavascriptEngine.java    License: 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 14
Source Project: es6draft   File: ScriptEngineScopeTest.java    License: 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 15
Source Project: greycat   File: CoreTask.java    License: 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 16
@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 17
@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 18
@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 Project: scipio-erp   File: ScriptUtil.java    License: 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 Project: jdk8u60   File: ScopeTest.java    License: 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) {}
}