Search in sources :

Example 1 with Context

use of org.mozilla.javascript.Context in project druid by druid-io.

the class JavaScriptParser method compile.

private static Function<Object, Object> compile(String function) {
    final ContextFactory contextFactory = ContextFactory.getGlobal();
    final Context context = contextFactory.enterContext();
    context.setOptimizationLevel(9);
    final ScriptableObject scope = context.initStandardObjects();
    final org.mozilla.javascript.Function fn = context.compileFunction(scope, function, "fn", 1, null);
    Context.exit();
    return new Function<Object, Object>() {

        public Object apply(Object input) {
            // ideally we need a close() function to discard the context once it is not used anymore
            Context cx = Context.getCurrentContext();
            if (cx == null) {
                cx = contextFactory.enterContext();
            }
            final Object res = fn.call(cx, scope, scope, new Object[] { input });
            return res != null ? Context.toObject(res, scope) : null;
        }
    };
}
Also used : ContextFactory(org.mozilla.javascript.ContextFactory) Context(org.mozilla.javascript.Context) Function(com.google.common.base.Function) ScriptableObject(org.mozilla.javascript.ScriptableObject) ScriptableObject(org.mozilla.javascript.ScriptableObject)

Example 2 with Context

use of org.mozilla.javascript.Context in project druid by druid-io.

the class JavaScriptAggregatorFactory method compileScript.

@VisibleForTesting
static JavaScriptAggregator.ScriptAggregator compileScript(final String aggregate, final String reset, final String combine) {
    final ContextFactory contextFactory = ContextFactory.getGlobal();
    Context context = contextFactory.enterContext();
    context.setOptimizationLevel(JavaScriptConfig.DEFAULT_OPTIMIZATION_LEVEL);
    final ScriptableObject scope = context.initStandardObjects();
    final Function fnAggregate = context.compileFunction(scope, aggregate, "aggregate", 1, null);
    final Function fnReset = context.compileFunction(scope, reset, "reset", 1, null);
    final Function fnCombine = context.compileFunction(scope, combine, "combine", 1, null);
    Context.exit();
    return new JavaScriptAggregator.ScriptAggregator() {

        @Override
        public double aggregate(final double current, final ObjectColumnSelector[] selectorList) {
            Context cx = Context.getCurrentContext();
            if (cx == null) {
                cx = contextFactory.enterContext();
                // Disable primitive wrapping- we want Java strings and primitives to behave like JS entities.
                cx.getWrapFactory().setJavaPrimitiveWrap(false);
            }
            final int size = selectorList.length;
            final Object[] args = new Object[size + 1];
            args[0] = current;
            for (int i = 0; i < size; i++) {
                final ObjectColumnSelector selector = selectorList[i];
                if (selector != null) {
                    final Object arg = selector.get();
                    if (arg != null && arg.getClass().isArray()) {
                        // Context.javaToJS on an array sort of works, although it returns false for Array.isArray(...) and
                        // may have other issues too. Let's just copy the array and wrap that.
                        final Object[] arrayAsObjectArray = new Object[Array.getLength(arg)];
                        for (int j = 0; j < Array.getLength(arg); j++) {
                            arrayAsObjectArray[j] = Array.get(arg, j);
                        }
                        args[i + 1] = cx.newArray(scope, arrayAsObjectArray);
                    } else {
                        args[i + 1] = Context.javaToJS(arg, scope);
                    }
                }
            }
            final Object res = fnAggregate.call(cx, scope, scope, args);
            return Context.toNumber(res);
        }

        @Override
        public double combine(final double a, final double b) {
            final Object res = contextFactory.call(new ContextAction() {

                @Override
                public Object run(final Context cx) {
                    return fnCombine.call(cx, scope, scope, new Object[] { a, b });
                }
            });
            return Context.toNumber(res);
        }

        @Override
        public double reset() {
            final Object res = contextFactory.call(new ContextAction() {

                @Override
                public Object run(final Context cx) {
                    return fnReset.call(cx, scope, scope, new Object[] {});
                }
            });
            return Context.toNumber(res);
        }

        @Override
        public void close() {
            if (Context.getCurrentContext() != null) {
                Context.exit();
            }
        }
    };
}
Also used : ContextFactory(org.mozilla.javascript.ContextFactory) Context(org.mozilla.javascript.Context) Function(org.mozilla.javascript.Function) ScriptableObject(org.mozilla.javascript.ScriptableObject) ContextAction(org.mozilla.javascript.ContextAction) ScriptableObject(org.mozilla.javascript.ScriptableObject) ObjectColumnSelector(io.druid.segment.ObjectColumnSelector) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 3 with Context

use of org.mozilla.javascript.Context in project neo4j by neo4j.

the class JavascriptExecutor method execute.

@Override
public Object execute(Map<String, Object> variables) throws EvaluationException {
    Context cx = Context.enter();
    try {
        Scriptable scope = cx.newObject(prototype);
        scope.setPrototype(prototype);
        if (variables != null) {
            for (String k : variables.keySet()) {
                scope.put(k, scope, variables.get(k));
            }
        }
        Object out = compiledScript.exec(cx, scope);
        if (out instanceof NativeJavaObject) {
            return ((NativeJavaObject) out).unwrap();
        } else if (out instanceof Undefined) {
            return null;
        } else {
            return out;
        }
    } catch (RhinoException e) {
        throw new EvaluationException("Failed to execute script, see nested exception.", e);
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) Undefined(org.mozilla.javascript.Undefined) NativeJavaObject(org.mozilla.javascript.NativeJavaObject) RhinoException(org.mozilla.javascript.RhinoException) EvaluationException(org.neo4j.server.rest.domain.EvaluationException) Scriptable(org.mozilla.javascript.Scriptable) NativeJavaObject(org.mozilla.javascript.NativeJavaObject)

Example 4 with Context

use of org.mozilla.javascript.Context in project neo4j by neo4j.

the class TestWhiteListJavaWrapper method shouldDownCastSubclassesToAllowedParentClass.

@Test
public void shouldDownCastSubclassesToAllowedParentClass() throws Exception {
    // Given
    Set<String> whiteList = new HashSet<String>();
    whiteList.add(Object.class.getName());
    WhiteListJavaWrapper wrapper = new WhiteListJavaWrapper(new WhiteListClassShutter(whiteList));
    Context cx = Context.enter();
    Scriptable scope = cx.initStandardObjects();
    // When
    Object wrapped = wrapper.wrap(cx, scope, new TestWhiteListJavaWrapper(), null);
    // Then
    assertThat(wrapped, is(instanceOf(NativeJavaObject.class)));
    NativeJavaObject obj = (NativeJavaObject) wrapped;
    assertThat(obj.has("aGetter", scope), is(false));
    assertThat((UniqueTag) obj.get("aGetter", scope), is(UniqueTag.NOT_FOUND));
}
Also used : Context(org.mozilla.javascript.Context) NativeJavaObject(org.mozilla.javascript.NativeJavaObject) Scriptable(org.mozilla.javascript.Scriptable) NativeJavaObject(org.mozilla.javascript.NativeJavaObject) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 5 with Context

use of org.mozilla.javascript.Context in project neo4j by neo4j.

the class TestWhiteListJavaWrapper method shouldThrowSecurityExceptionWhenAccessingLockedClasses.

@Test(expected = SecurityException.class)
public void shouldThrowSecurityExceptionWhenAccessingLockedClasses() throws Exception {
    // Given
    Set<String> whiteList = new HashSet<String>();
    whiteList.add(Object.class.getName());
    WhiteListJavaWrapper wrapper = new WhiteListJavaWrapper(new WhiteListClassShutter(whiteList));
    Context cx = Context.enter();
    Scriptable scope = cx.initStandardObjects();
    // When
    Object wrapped = wrapper.wrap(cx, scope, TestWhiteListJavaWrapper.class, null);
}
Also used : Context(org.mozilla.javascript.Context) NativeJavaObject(org.mozilla.javascript.NativeJavaObject) Scriptable(org.mozilla.javascript.Scriptable) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

Context (org.mozilla.javascript.Context)153 Scriptable (org.mozilla.javascript.Scriptable)69 ScriptableObject (org.mozilla.javascript.ScriptableObject)63 ContextAction (org.mozilla.javascript.ContextAction)23 ContextFactory (org.mozilla.javascript.ContextFactory)22 Script (org.mozilla.javascript.Script)17 IOException (java.io.IOException)14 Function (org.mozilla.javascript.Function)13 ScriptContext (javax.script.ScriptContext)10 Test (org.junit.Test)8 RhinoException (org.mozilla.javascript.RhinoException)8 ArrayList (java.util.ArrayList)7 ContinuationPending (org.mozilla.javascript.ContinuationPending)7 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)7 InputStreamReader (java.io.InputStreamReader)6 Date (java.util.Date)6 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)6 JavaScriptException (org.mozilla.javascript.JavaScriptException)6 HashSet (java.util.HashSet)5 List (java.util.List)5