Search in sources :

Example 1 with Function

use of org.mozilla.javascript.Function 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 2 with Function

use of org.mozilla.javascript.Function in project hackpad by dropbox.

the class TypeOfTest method test0.

/**
	 * ECMA 11.4.3 says that typeof on host object is Implementation-dependent
	 */
public void test0() throws Exception {
    final Function f = new BaseFunction() {

        @Override
        public Object call(Context _cx, Scriptable _scope, Scriptable _thisObj, Object[] _args) {
            return _args[0].getClass().getName();
        }
    };
    final ContextAction action = new ContextAction() {

        public Object run(final Context context) {
            final Scriptable scope = context.initStandardObjects();
            scope.put("myObj", scope, f);
            return context.evaluateString(scope, "typeof myObj", "test script", 1, null);
        }
    };
    doTest("function", action);
}
Also used : Context(org.mozilla.javascript.Context) BaseFunction(org.mozilla.javascript.BaseFunction) Function(org.mozilla.javascript.Function) BaseFunction(org.mozilla.javascript.BaseFunction) ContextAction(org.mozilla.javascript.ContextAction) Scriptable(org.mozilla.javascript.Scriptable)

Example 3 with Function

use of org.mozilla.javascript.Function in project sling by apache.

the class AsyncExtractor method decodeJSPromise.

private void decodeJSPromise(final Scriptable promise, final UnaryCallback callback) {
    try {
        Context context = Context.enter();
        final AsyncContainer errorContainer = new AsyncContainer();
        final Function errorHandler = createErrorHandler(errorContainer);
        final Function successHandler = convertCallback(callback);
        EventLoopInterop.schedule(context, new Runnable() {

            @Override
            public void run() {
                ScriptableObject.callMethod(promise, THEN_METHOD, new Object[] { successHandler, errorHandler });
            }
        });
        if (errorContainer.isCompleted()) {
            throw new SightlyException("Promise has completed with failure: " + Context.toString(errorContainer.getResult()));
        }
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) BaseFunction(org.mozilla.javascript.BaseFunction) Function(org.mozilla.javascript.Function) SightlyException(org.apache.sling.scripting.sightly.SightlyException) ScriptableObject(org.mozilla.javascript.ScriptableObject)

Example 4 with Function

use of org.mozilla.javascript.Function in project cxf by apache.

the class JavascriptTestUtilities method rhinoCallExpectingException.

/**
 * Call a Javascript function, identified by name, on a set of arguments. Optionally, expect it to throw
 * an exception.
 *
 * @param expectingException
 * @param functionName
 * @param args
 * @return
 */
public Object rhinoCallExpectingException(final Object expectingException, final String functionName, final Object... args) {
    Object fObj = rhinoScope.get(functionName, rhinoScope);
    if (!(fObj instanceof Function)) {
        throw new RuntimeException("Missing test function " + functionName);
    }
    Function function = (Function) fObj;
    try {
        return function.call(rhinoContext, rhinoScope, rhinoScope, args);
    } catch (RhinoException angryRhino) {
        if (expectingException != null && angryRhino instanceof JavaScriptException) {
            JavaScriptException jse = (JavaScriptException) angryRhino;
            Assert.assertEquals(jse.getValue(), expectingException);
            return null;
        }
        String trace = angryRhino.getScriptStackTrace();
        Assert.fail("JavaScript error: " + angryRhino.toString() + " " + trace);
    } catch (JavaScriptAssertionFailed assertion) {
        Assert.fail(assertion.getMessage());
    }
    return null;
}
Also used : Function(org.mozilla.javascript.Function) ScriptableObject(org.mozilla.javascript.ScriptableObject) RhinoException(org.mozilla.javascript.RhinoException) JavaScriptException(org.mozilla.javascript.JavaScriptException)

Example 5 with Function

use of org.mozilla.javascript.Function in project cxf by apache.

the class JsXMLHttpRequest method notifyReadyStateChangeListener.

private void notifyReadyStateChangeListener() {
    if (readyStateChangeListener instanceof Function) {
        LOG.fine("notify " + readyState);
        // for now, call with no args.
        Function listenerFunction = (Function) readyStateChangeListener;
        listenerFunction.call(Context.getCurrentContext(), getParentScope(), null, new Object[] {});
    }
}
Also used : Function(org.mozilla.javascript.Function)

Aggregations

Function (org.mozilla.javascript.Function)26 ScriptableObject (org.mozilla.javascript.ScriptableObject)17 Context (org.mozilla.javascript.Context)13 Scriptable (org.mozilla.javascript.Scriptable)9 ContextAction (org.mozilla.javascript.ContextAction)5 RhinoException (org.mozilla.javascript.RhinoException)4 Map (java.util.Map)3 SightlyException (org.apache.sling.scripting.sightly.SightlyException)3 BaseFunction (org.mozilla.javascript.BaseFunction)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 TimingFunction (org.apache.sling.scripting.sightly.js.impl.async.TimingFunction)2 HybridObject (org.apache.sling.scripting.sightly.js.impl.rhino.HybridObject)2 ContextFactory (org.mozilla.javascript.ContextFactory)2 ContinuationPending (org.mozilla.javascript.ContinuationPending)2 NativeArray (org.mozilla.javascript.NativeArray)2 NativeObject (org.mozilla.javascript.NativeObject)2 Script (org.mozilla.javascript.Script)2 ImmutableList (com.google.common.collect.ImmutableList)1