Search in sources :

Example 21 with ContextFactory

use of org.mozilla.javascript.ContextFactory in project jaggery by wso2.

the class DatabaseHostObject method executeQuery.

private static Object executeQuery(Context cx, final DatabaseHostObject db, final PreparedStatement stmt, String query, final Function callback, final boolean keyed) throws ScriptException {
    // select
    String regex = "^[\\s\\t\\r\\n]*[Ss][Ee][Ll][Ee][Cc][Tt].*";
    final boolean isSelect = query.matches(regex);
    if (callback != null) {
        final ContextFactory factory = cx.getFactory();
        final ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(new Callable() {

            public Object call() throws Exception {
                Context cx = RhinoEngine.enterContext(factory);
                try {
                    Object result;
                    if (isSelect) {
                        result = processResults(cx, db, db, stmt.executeQuery(), keyed);
                    } else {
                        result = stmt.executeUpdate();
                    }
                    stmt.close();
                    callback.call(cx, db, db, new Object[] { result });
                } catch (SQLException e) {
                    log.warn(e);
                } finally {
                    es.shutdown();
                    RhinoEngine.exitContext();
                }
                return null;
            }
        });
        return null;
    } else {
        try {
            Object result;
            if (isSelect) {
                result = processResults(cx, db, db, stmt.executeQuery(), keyed);
            } else {
                result = stmt.executeUpdate();
            }
            stmt.close();
            return result;
        } catch (SQLException e) {
            log.warn(e);
            throw new ScriptException(e);
        }
    }
}
Also used : ContextFactory(org.mozilla.javascript.ContextFactory) Context(org.mozilla.javascript.Context) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) ExecutorService(java.util.concurrent.ExecutorService) StreamHostObject(org.jaggeryjs.hostobjects.stream.StreamHostObject) NativeObject(org.mozilla.javascript.NativeObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) Callable(java.util.concurrent.Callable) DataSourceException(org.wso2.carbon.ndatasource.common.DataSourceException) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException)

Example 22 with ContextFactory

use of org.mozilla.javascript.ContextFactory in project structr by structr.

the class Scripting method setupJavascriptContext.

public static Context setupJavascriptContext() {
    final Context scriptingContext = new ContextFactory().enterContext();
    // enable some optimizations..
    scriptingContext.setLanguageVersion(Context.VERSION_1_2);
    scriptingContext.setOptimizationLevel(9);
    scriptingContext.setInstructionObserverThreshold(0);
    scriptingContext.setGenerateObserverCount(false);
    return scriptingContext;
}
Also used : SecurityContext(org.structr.common.SecurityContext) Context(org.mozilla.javascript.Context) ScriptContext(javax.script.ScriptContext) ActionContext(org.structr.schema.action.ActionContext) ContextFactory(org.mozilla.javascript.ContextFactory)

Example 23 with ContextFactory

use of org.mozilla.javascript.ContextFactory 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>() {

        @Override
        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 24 with ContextFactory

use of org.mozilla.javascript.ContextFactory 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 BaseObjectColumnValueSelector[] 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 BaseObjectColumnValueSelector selector = selectorList[i];
                if (selector != null) {
                    final Object arg = selector.getObject();
                    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.
                        args[i + 1] = cx.newArray(scope, arrayToObjectArray(arg));
                    } else if (arg instanceof List) {
                        // Using toArray(Object[]), instead of just toArray(), because Arrays.asList()'s impl and similar List
                        // impls could clone the underlying array in toArray(), that could be not Object[], but e. g. String[].
                        args[i + 1] = cx.newArray(scope, ((List) arg).toArray(ObjectArrays.EMPTY_ARRAY));
                    } else {
                        args[i + 1] = Context.javaToJS(arg, scope);
                    }
                }
            }
            final Object res = fnAggregate.call(cx, scope, scope, args);
            return Context.toNumber(res);
        }

        private Object[] arrayToObjectArray(Object array) {
            int len = Array.getLength(array);
            final Object[] objectArray = new Object[len];
            for (int j = 0; j < len; j++) {
                objectArray[j] = Array.get(array, j);
            }
            return objectArray;
        }

        @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) BaseObjectColumnValueSelector(org.apache.druid.segment.BaseObjectColumnValueSelector) ScriptableObject(org.mozilla.javascript.ScriptableObject) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 25 with ContextFactory

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

the class JavaScriptExtractionFn method compile.

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

        @Override
        public String 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.toString(res) : 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)

Aggregations

ContextFactory (org.mozilla.javascript.ContextFactory)25 Context (org.mozilla.javascript.Context)22 ScriptableObject (org.mozilla.javascript.ScriptableObject)15 Function (com.google.common.base.Function)4 ContextAction (org.mozilla.javascript.ContextAction)4 IOException (java.io.IOException)3 Method (java.lang.reflect.Method)3 Callable (java.util.concurrent.Callable)3 ExecutorService (java.util.concurrent.ExecutorService)3 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)3 Scriptable (org.mozilla.javascript.Scriptable)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 SlingContextFactory (org.apache.sling.scripting.javascript.helper.SlingContextFactory)2 StreamHostObject (org.jaggeryjs.hostobjects.stream.StreamHostObject)2 Function (org.mozilla.javascript.Function)2 NativeObject (org.mozilla.javascript.NativeObject)2 RhinoException (org.mozilla.javascript.RhinoException)2 ImmutableList (com.google.common.collect.ImmutableList)1 ObjectColumnSelector (io.druid.segment.ObjectColumnSelector)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1