Search in sources :

Example 66 with Context

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

the class DatabaseHostObject method executeBatch.

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings("SQL_INJECTION_JDBC")
private static Object executeBatch(Context cx, final DatabaseHostObject db, NativeArray queries, NativeArray params, final Function callback) throws ScriptException, SQLException {
    if (params != null && (queries.getLength() != params.getLength())) {
        String msg = "Query array and values array should be in the same size. HostObject : " + hostObjectName + ", Method : query";
        log.warn(msg);
        throw new ScriptException(msg);
    }
    final Statement stmt = db.conn.createStatement();
    for (int index : (Integer[]) queries.getIds()) {
        Object obj = queries.get(index, db);
        if (!(obj instanceof String)) {
            String msg = "Invalid query type : " + obj.toString() + ". Query should be a string";
            log.warn(msg);
            throw new ScriptException(msg);
        }
        String query = (String) obj;
        if (params != null) {
            Object valObj = params.get(index, db);
            if (!(valObj instanceof NativeArray)) {
                String msg = "Invalid value type : " + obj.toString() + " for the query " + query;
                log.warn(msg);
                throw new ScriptException(msg);
            }
            query = replaceWildcards(db, query, (NativeArray) valObj);
        }
        stmt.addBatch(query);
    }
    if (callback != null) {
        final ContextFactory factory = cx.getFactory();
        final ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(new Callable() {

            public Object call() throws Exception {
                Context ctx = RhinoEngine.enterContext(factory);
                try {
                    int[] result = stmt.executeBatch();
                    callback.call(ctx, db, db, new Object[] { result });
                } catch (SQLException e) {
                    log.warn(e);
                } finally {
                    es.shutdown();
                    RhinoEngine.exitContext();
                }
                return null;
            }
        });
        return null;
    } else {
        return stmt.executeBatch();
    }
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) 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 67 with Context

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

the class WebAppSessionListener method sessionDestroyed.

@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    ServletContext ctx = httpSessionEvent.getSession().getServletContext();
    List<Object> jsListeners = (List<Object>) ctx.getAttribute(JaggeryCoreConstants.JS_DESTROYED_LISTENERS);
    if (jsListeners == null) {
        return;
    }
    JaggeryContext shared = WebAppManager.sharedJaggeryContext(ctx);
    Context cx = shared.getEngine().enterContext();
    JaggeryContext context = CommonManager.getJaggeryContext();
    if (CommonManager.getJaggeryContext() == null) {
        context = WebAppManager.clonedJaggeryContext(ctx);
        CommonManager.setJaggeryContext(context);
    }
    RhinoEngine engine = context.getEngine();
    ScriptableObject clonedScope = context.getScope();
    JavaScriptProperty session = new JavaScriptProperty("session");
    session.setValue(cx.newObject(clonedScope, "Session", new Object[] { httpSessionEvent.getSession() }));
    RhinoEngine.defineProperty(clonedScope, session);
    for (Object jsListener : jsListeners) {
        CommonManager.getCallstack(context).push((String) jsListener);
        try {
            ScriptReader sr = new ScriptReader(ctx.getResourceAsStream((String) jsListener)) {

                @Override
                protected void build() throws IOException {
                    try {
                        sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                    } catch (ScriptException e) {
                        throw new IOException(e);
                    }
                }
            };
            engine.exec(sr, clonedScope, null);
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            CommonManager.getCallstack(context).pop();
        }
    }
    Context.exit();
}
Also used : JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) Context(org.mozilla.javascript.Context) ServletContext(javax.servlet.ServletContext) ScriptableObject(org.mozilla.javascript.ScriptableObject) JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) IOException(java.io.IOException) RhinoEngine(org.jaggeryjs.scriptengine.engine.RhinoEngine) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) JavaScriptProperty(org.jaggeryjs.scriptengine.engine.JavaScriptProperty) StringReader(java.io.StringReader) ServletContext(javax.servlet.ServletContext) ScriptableObject(org.mozilla.javascript.ScriptableObject) List(java.util.List) ScriptReader(org.jaggeryjs.jaggery.core.ScriptReader)

Example 68 with Context

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

the class JaggeryShell method enterContext.

/**
 * Enter shell context.
 *
 * @param args argument list of parameters
 * Will need to send empty array to execute expressions.
 */
public static void enterContext(final String[] args) {
    // Associate a new Context with this thread
    final Context context = ContextFactory.getGlobal().enterContext();
    try {
        // Initialize the standard objects (Object, Function, etc.)
        // This must be done before scripts can be executed.
        final JaggeryShell shell = new JaggeryShell();
        context.initStandardObjects(shell);
        // Define some global functions particular to the shell. Note
        // that these functions are not part of ECMA.
        final String[] names = { CMD_QUIT, CMD_VERSION, CMD_HELP };
        shell.defineFunctionProperties(names, JaggeryShell.class, ScriptableObject.DONTENUM);
        final String[] optionArgs = processOptions(context, args);
        // Set up "arguments" in the global scope to contain the command
        // line arguments after the name of the script to execute
        Object[] array;
        if (optionArgs.length == 0) {
            array = new Object[0];
        } else {
            final int length = optionArgs.length - 1;
            array = new Object[length];
            System.arraycopy(optionArgs, 1, array, 0, length);
        }
        final Scriptable argsObj = context.newArray(shell, array);
        shell.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM);
        shell.processSource(context, optionArgs.length == 0 ? null : optionArgs[0]);
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) ScriptableObject(org.mozilla.javascript.ScriptableObject) Scriptable(org.mozilla.javascript.Scriptable)

Example 69 with Context

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

the class JavaScriptPostAggregator method compile.

private static Function 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() {

        @Override
        public double apply(Object[] args) {
            // 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();
            }
            return Context.toNumber(fn.call(cx, scope, scope, args));
        }
    };
}
Also used : ContextFactory(org.mozilla.javascript.ContextFactory) Context(org.mozilla.javascript.Context) ScriptableObject(org.mozilla.javascript.ScriptableObject)

Example 70 with Context

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

the class MapAdapter method put.

public Object put(Object key, Object value) {
    // Wrap the value if it is not already
    if (value != null && !(value instanceof Scriptable)) {
        Context cx = Context.getCurrentContext();
        value = cx.getWrapFactory().wrap(cx, object, value, value.getClass());
    }
    Object prev = get(key);
    if (key instanceof Integer)
        object.put(((Integer) key).intValue(), object, value);
    else if (key instanceof String)
        object.put((String) key, object, value);
    else
        prev = null;
    return prev;
}
Also used : Context(org.mozilla.javascript.Context) ScriptableObject(org.mozilla.javascript.ScriptableObject) Scriptable(org.mozilla.javascript.Scriptable)

Aggregations

Context (org.mozilla.javascript.Context)152 Scriptable (org.mozilla.javascript.Scriptable)68 ScriptableObject (org.mozilla.javascript.ScriptableObject)62 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 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)6 JavaScriptException (org.mozilla.javascript.JavaScriptException)6 Date (java.util.Date)5 HashSet (java.util.HashSet)5 List (java.util.List)5