Search in sources :

Example 1 with Bindings

use of javax.script.Bindings in project metrics by dropwizard.

the class PickledGraphiteTest method unpickleOutput.

String unpickleOutput() throws Exception {
    StringBuilder results = new StringBuilder();
    // the charset is important. if the GraphitePickleReporter and this test
    // don't agree, the header is not always correctly unpacked.
    String payload = output.toString("UTF-8");
    PyList result = new PyList();
    int nextIndex = 0;
    while (nextIndex < payload.length()) {
        Bindings bindings = new SimpleBindings();
        bindings.put("payload", payload.substring(nextIndex));
        unpickleScript.eval(bindings);
        result.addAll(result.size(), (PyList) bindings.get("metrics"));
        nextIndex += (Integer) bindings.get("batchLength");
    }
    for (Object aResult : result) {
        PyTuple datapoint = (PyTuple) aResult;
        String name = datapoint.get(0).toString();
        PyTuple valueTuple = (PyTuple) datapoint.get(1);
        Object timestamp = valueTuple.get(0);
        Object value = valueTuple.get(1);
        results.append(name).append(" ").append(value).append(" ").append(timestamp).append("\n");
    }
    return results.toString();
}
Also used : SimpleBindings(javax.script.SimpleBindings) PyList(org.python.core.PyList) PyTuple(org.python.core.PyTuple) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings)

Example 2 with Bindings

use of javax.script.Bindings in project dubbo by alibaba.

the class ScriptRouter method route.

@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;
    }
}
Also used : CompiledScript(javax.script.CompiledScript) ScriptException(javax.script.ScriptException) Invoker(com.alibaba.dubbo.rpc.Invoker) Compilable(javax.script.Compilable) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Bindings(javax.script.Bindings)

Example 3 with Bindings

use of javax.script.Bindings in project jOOQ by jOOQ.

the class NashornTest method testScripts.

@Test
public void testScripts() throws Exception {
    Stream.of(new File(getClass().getResource("/org/jooq/example/test").toURI()).listFiles((dir, name) -> name.endsWith(".js"))).forEach(file -> {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");
        Bindings bindings = engine.getBindings(ENGINE_SCOPE);
        bindings.put("connection", connection);
        try {
            engine.eval(new FileReader(file));
        } catch (Exception e) {
            throw new RuntimeException("Error while running " + file, e);
        }
    });
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager) FileReader(java.io.FileReader) File(java.io.File) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine) Test(org.junit.Test)

Example 4 with Bindings

use of javax.script.Bindings in project openhab1-addons by openhab.

the class EBusTelegramParser method evaluateScript.

/**
     * Evaluates the compiled script of a entry.
     * 
     * @param entry The configuration entry to evaluate
     * @param scopeValues All known values for script scope
     * @return The computed value
     * @throws ScriptException
     */
private Object evaluateScript(Entry<String, TelegramValue> entry, Map<String, Object> scopeValues) throws ScriptException {
    Object value = null;
    // executes compiled script
    if (entry.getValue().getCsript() != null) {
        CompiledScript cscript = entry.getValue().getCsript();
        // Add global variables thisValue and keyName to JavaScript context
        Bindings bindings = cscript.getEngine().createBindings();
        bindings.putAll(scopeValues);
        value = cscript.eval(bindings);
    }
    // try to convert the returned value to BigDecimal
    value = ObjectUtils.defaultIfNull(NumberUtils.toBigDecimal(value), value);
    // round to two digits, maybe not optimal for any result
    if (value instanceof BigDecimal) {
        ((BigDecimal) value).setScale(2, BigDecimal.ROUND_HALF_UP);
    }
    return value;
}
Also used : CompiledScript(javax.script.CompiledScript) Bindings(javax.script.Bindings) BigDecimal(java.math.BigDecimal)

Example 5 with Bindings

use of javax.script.Bindings in project es6draft by anba.

the class TypeConversionTest method testUnsupportedWithSimpleBindings.

@Test
public void testUnsupportedWithSimpleBindings() throws ScriptException {
    // Unsupported Java classes end up as `null` in simple bindings
    Bindings bindings = new SimpleBindings();
    Object javaObject = new JavaObject();
    bindings.put("javaObject", javaObject);
    assertThat(bindings.get("javaObject"), sameInstance(javaObject));
    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)));
}
Also used : SimpleBindings(javax.script.SimpleBindings) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) Test(org.junit.Test)

Aggregations

Bindings (javax.script.Bindings)142 SimpleBindings (javax.script.SimpleBindings)74 Test (org.junit.Test)36 ScriptException (javax.script.ScriptException)27 ScriptContext (javax.script.ScriptContext)24 SimpleScriptContext (javax.script.SimpleScriptContext)21 SlingBindings (org.apache.sling.api.scripting.SlingBindings)18 Test (org.testng.annotations.Test)17 ScriptEngine (javax.script.ScriptEngine)15 CompiledScript (javax.script.CompiledScript)14 Resource (org.apache.sling.api.resource.Resource)11 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)10 SlingScriptHelper (org.apache.sling.api.scripting.SlingScriptHelper)10 HashMap (java.util.HashMap)9 Map (java.util.Map)9 IOException (java.io.IOException)8 StringWriter (java.io.StringWriter)7 ArrayList (java.util.ArrayList)7 PrintWriter (java.io.PrintWriter)6 ScriptEngineManager (javax.script.ScriptEngineManager)6