Search in sources :

Example 1 with NativeArray

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

the class Bug492525Test method getAllIdsShouldIncludeArrayIndices.

@Test
public void getAllIdsShouldIncludeArrayIndices() {
    NativeArray array = new NativeArray(new String[] { "a", "b" });
    Object[] expectedIds = new Object[] { 0, 1, "length" };
    Object[] actualIds = array.getAllIds();
    assertArrayEquals(expectedIds, actualIds);
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) Test(org.junit.Test)

Example 2 with NativeArray

use of org.mozilla.javascript.NativeArray 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 3 with NativeArray

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

the class DatabaseHostObject method jsFunction_query.

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "SQL_INJECTION_JDBC", "SQL_INJECTION_JDBC", "SQL_INJECTION_JDBC", "SQL_INJECTION_JDBC" })
public static Object jsFunction_query(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException, SQLException {
    String functionName = "query";
    int argsCount = args.length;
    if (argsCount == 0) {
        HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
    }
    DatabaseHostObject db = (DatabaseHostObject) thisObj;
    String query;
    if (argsCount == 1) {
        //query
        Function callback = null;
        if (!(args[0] instanceof String)) {
            HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
        }
        query = (String) args[0];
        PreparedStatement stmt = db.conn.prepareStatement(query);
        return executeQuery(cx, db, stmt, query, callback, true);
    } else if (argsCount == 2) {
        if (!(args[0] instanceof String)) {
            //batch
            Function callback = null;
            if (!(args[0] instanceof NativeArray)) {
                HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
            }
            NativeArray queries = (NativeArray) args[0];
            NativeArray values = null;
            if (args[1] instanceof Function) {
                callback = (Function) args[1];
            } else if (args[1] instanceof NativeArray) {
                values = (NativeArray) args[1];
            } else {
                HostObjectUtil.invalidArgsError(hostObjectName, functionName, "2", "array | function", args[0], false);
            }
            return executeBatch(cx, db, queries, values, callback);
        } else {
            //query
            Function callback = null;
            query = (String) args[0];
            PreparedStatement stmt = db.conn.prepareStatement(query);
            if (args[1] instanceof Function) {
                callback = (Function) args[1];
            } else {
                setQueryParams(stmt, args, 1, 1);
            }
            return executeQuery(cx, db, stmt, query, callback, true);
        }
    } else if (argsCount == 3) {
        if (!(args[0] instanceof String)) {
            //batch
            Function callback = null;
            if (!(args[0] instanceof NativeArray)) {
                HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "array", args[0], false);
            }
            if (!(args[1] instanceof NativeArray)) {
                HostObjectUtil.invalidArgsError(hostObjectName, functionName, "2", "array", args[1], false);
            }
            if (!(args[2] instanceof Function)) {
                HostObjectUtil.invalidArgsError(hostObjectName, functionName, "3", "function", args[2], false);
            }
            NativeArray queries = (NativeArray) args[0];
            NativeArray values = (NativeArray) args[1];
            callback = (Function) args[2];
            return executeBatch(cx, db, queries, values, callback);
        } else {
            //query
            Function callback = null;
            query = (String) args[0];
            PreparedStatement stmt = db.conn.prepareStatement(query);
            if (args[2] instanceof Function) {
                callback = (Function) args[2];
                setQueryParams(stmt, args, 1, 1);
            } else {
                setQueryParams(stmt, args, 1, 2);
            }
            return executeQuery(cx, db, stmt, query, callback, true);
        }
    } else {
        //args count > 3
        if (!(args[0] instanceof String)) {
            HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
        }
        Function callback = null;
        query = (String) args[0];
        PreparedStatement stmt = db.conn.prepareStatement(query);
        if (args[argsCount - 1] instanceof Function) {
            callback = (Function) args[argsCount - 1];
            setQueryParams(stmt, args, 1, argsCount - 1);
        } else {
            setQueryParams(stmt, args, 1, argsCount - 1);
        }
        return executeQuery(cx, db, stmt, query, callback, true);
    }
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) Function(org.mozilla.javascript.Function)

Example 4 with NativeArray

use of org.mozilla.javascript.NativeArray in project OpenAM by OpenRock.

the class JavaScriptHttpClient method convertRequestData.

private Map convertRequestData(NativeObject requestData) {
    HashMap<String, ArrayList<HashMap>> convertedRequestData = new HashMap<String, ArrayList<HashMap>>();
    if (requestData != null) {
        NativeArray cookies = (NativeArray) NativeObject.getProperty(requestData, "cookies");
        ArrayList<HashMap> convertedCookies = new ArrayList<HashMap>();
        if (cookies != null) {
            Object[] cookieIds = cookies.getIds();
            for (Object id : cookieIds) {
                NativeObject cookie = (NativeObject) cookies.get((Integer) id, null);
                String domain = (String) cookie.get("domain", null);
                String field = (String) cookie.get("field", null);
                String value = (String) cookie.get("value", null);
                convertedCookies.add(convertCookie(domain, field, value));
            }
        }
        convertedRequestData.put("cookies", convertedCookies);
        NativeArray headers = (NativeArray) NativeObject.getProperty(requestData, "headers");
        ArrayList<HashMap> convertedHeaders = new ArrayList<HashMap>();
        if (headers != null) {
            Object[] headerIds = headers.getIds();
            for (Object id : headerIds) {
                NativeObject header = (NativeObject) headers.get((Integer) id, null);
                String field = (String) header.get("field", null);
                String value = (String) header.get("value", null);
                convertedHeaders.add(convertHeader(field, value));
            }
        }
        convertedRequestData.put("headers", convertedHeaders);
    }
    return convertedRequestData;
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) NativeObject(org.mozilla.javascript.NativeObject) NativeObject(org.mozilla.javascript.NativeObject)

Example 5 with NativeArray

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

the class Main method processSource.

/**
     * Evaluate JavaScript source.
     *
     * @param cx the current context
     * @param filename the name of the file to compile, or null
     *                 for interactive mode.
     */
public static void processSource(Context cx, String filename) {
    if (filename == null || filename.equals("-")) {
        PrintStream ps = global.getErr();
        if (filename == null) {
            // print implementation version
            ps.println(cx.getImplementationVersion());
        }
        String charEnc = shellContextFactory.getCharacterEncoding();
        if (charEnc == null) {
            charEnc = System.getProperty("file.encoding");
        }
        BufferedReader in;
        try {
            in = new BufferedReader(new InputStreamReader(global.getIn(), charEnc));
        } catch (UnsupportedEncodingException e) {
            throw new UndeclaredThrowableException(e);
        }
        int lineno = 1;
        boolean hitEOF = false;
        while (!hitEOF) {
            String[] prompts = global.getPrompts(cx);
            if (filename == null)
                ps.print(prompts[0]);
            ps.flush();
            String source = "";
            // Collect lines of source to compile.
            while (true) {
                String newline;
                try {
                    newline = in.readLine();
                } catch (IOException ioe) {
                    ps.println(ioe.toString());
                    break;
                }
                if (newline == null) {
                    hitEOF = true;
                    break;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source))
                    break;
                ps.print(prompts[1]);
            }
            Script script = loadScriptFromSource(cx, source, "<stdin>", lineno, null);
            if (script != null) {
                Object result = evaluateScript(script, cx, global);
                // Avoid printing out undefined or function definitions.
                if (result != Context.getUndefinedValue() && !(result instanceof Function && source.trim().startsWith("function"))) {
                    try {
                        ps.println(Context.toString(result));
                    } catch (RhinoException rex) {
                        ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                    }
                }
                NativeArray h = global.history;
                h.put((int) h.getLength(), h, source);
            }
        }
        ps.println();
    } else if (filename.equals(mainModule)) {
        try {
            require.requireMain(cx, filename);
        } catch (RhinoException rex) {
            ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
            exitCode = EXITCODE_RUNTIME_ERROR;
        } catch (VirtualMachineError ex) {
            // Treat StackOverflow and OutOfMemory as runtime errors
            ex.printStackTrace();
            String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(msg);
        }
    } else {
        processFile(cx, global, filename);
    }
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) PrintStream(java.io.PrintStream) Script(org.mozilla.javascript.Script) InputStreamReader(java.io.InputStreamReader) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Function(org.mozilla.javascript.Function) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) BufferedReader(java.io.BufferedReader) ScriptableObject(org.mozilla.javascript.ScriptableObject) RhinoException(org.mozilla.javascript.RhinoException)

Aggregations

NativeArray (org.mozilla.javascript.NativeArray)10 ScriptableObject (org.mozilla.javascript.ScriptableObject)4 Test (org.junit.Test)3 Function (org.mozilla.javascript.Function)2 NativeObject (org.mozilla.javascript.NativeObject)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 PrintStream (java.io.PrintStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)1 ArrayList (java.util.ArrayList)1 Callable (java.util.concurrent.Callable)1 ExecutorService (java.util.concurrent.ExecutorService)1 NodeIterator (javax.jcr.NodeIterator)1 Property (javax.jcr.Property)1 PropertyIterator (javax.jcr.PropertyIterator)1 RepositoryException (javax.jcr.RepositoryException)1 Value (javax.jcr.Value)1 StreamHostObject (org.jaggeryjs.hostobjects.stream.StreamHostObject)1