Java Examples for org.mozilla.javascript.NativeArray

The following java examples will help you to understand the usage of org.mozilla.javascript.NativeArray. These source code samples are taken from different open source projects.

Example 1
Project: mongodb-jvm-master  File: RhinoBSONList.java View source code
@Override
protected NativeArray addValue(NativeArray ret, T value) {
    NativeArray newArray = new NativeArray(ret.getLength() + 1);
    for (int a = 0; a < ret.getLength(); a++) {
        Object value1 = ScriptableObject.getProperty(ret, a);
        ScriptableObject.putProperty(newArray, a, value1);
    }
    ScriptableObject.putProperty(newArray, (int) ret.getLength(), value);
    return newArray;
}
Example 2
Project: mungbean-master  File: RhinoBSONList.java View source code
@Override
protected NativeArray addValue(NativeArray ret, T value) {
    NativeArray newArray = new NativeArray(ret.getLength() + 1);
    for (int a = 0; a < ret.getLength(); a++) {
        Object value1 = ScriptableObject.getProperty(ret, a);
        ScriptableObject.putProperty(newArray, a, value1);
    }
    ScriptableObject.putProperty(newArray, (int) ret.getLength(), value);
    return newArray;
}
Example 3
Project: alfresco-enhanced-script-environment-master  File: NativeArrayConverter.java View source code
/**
     *
     * {@inheritDoc}
     */
@Override
public void afterPropertiesSet() {
    PropertyCheck.mandatory(this, "registry", this.registry);
    // Collection registered previously but now handled by ScriptableFacadeListConverter
    this.registry.registerValueInstanceConverter(Object[].class, this);
    this.registry.registerValueInstanceConverter(byte[].class, this);
    this.registry.registerValueInstanceConverter(short[].class, this);
    this.registry.registerValueInstanceConverter(char[].class, this);
    this.registry.registerValueInstanceConverter(int[].class, this);
    this.registry.registerValueInstanceConverter(long[].class, this);
    this.registry.registerValueInstanceConverter(float[].class, this);
    this.registry.registerValueInstanceConverter(double[].class, this);
    this.registry.registerValueInstanceConverter(boolean[].class, this);
    this.registry.registerValueInstanceConverter(NativeArray.class, this);
}
Example 4
Project: pentaho-reporting-master  File: JavascriptValueConverter.java View source code
public Object convert(final Object o) {
    if (o == null) {
        return null;
    }
    final String classString = o.getClass().getName();
    if ("sun.org.mozilla.javascript.internal.Wrapper".equals(classString) || "sun.org.mozilla.javascript.Wrapper".equals(classString)) {
        try {
            final Method unwrap = o.getClass().getMethod("unwrap");
            return unwrap.invoke(o);
        } catch (Throwable e) {
            logger.debug("Unable to call 'unwrap' on suspected javascript object.");
            return null;
        }
    }
    if ("sun.org.mozilla.javascript.internal.NativeArray".equals(classString)) {
        final String scriptableClassName = "sun.org.mozilla.javascript.internal.Scriptable";
        return unwrapArray(o, scriptableClassName);
    } else if ("sun.org.mozilla.javascript.NativeArray".equals(classString)) {
        final String scriptableClassName = "sun.org.mozilla.javascript.Scriptable";
        return unwrapArray(o, scriptableClassName);
    }
    return null;
}
Example 5
Project: Purple-Robot-master  File: JavaScriptEngine.java View source code
@ScriptingEngineMethod(language = "All", assetPath = "all_scheduled_scripts.html", category = R.string.docs_script_category_dialogs_notifications, arguments = {})
public NativeArray scheduledScripts() {
    List<Map<String, String>> scripts = ScheduleManager.allScripts(this._context);
    NativeArray allScripts = new NativeArray(scripts.size());
    for (int i = 0; i < scripts.size(); i++) {
        Map<String, String> script = scripts.get(i);
        Map<String, Object> scriptObj = new HashMap<>();
        for (String key : script.keySet()) scriptObj.put(key, script.get(key));
        NativeObject nativeObj = JavaScriptEngine.mapToNative(this._jsContext, this._scope, scriptObj);
        NativeArray.putProperty(allScripts, i, nativeObj);
    }
    return allScripts;
}
Example 6
Project: alfresco-jscript-extensions-master  File: BatchScriptFacade.java View source code
/**
	 * process the given processorfunction on a set of nodes which are given as
	 * native array. The processing takes place in a de.jgoldhammer.alfresco.jscript.batch processor with the
	 * given batchName, the number of workerthreads and the number of nodes as
	 * batchsize.
	 *
	 * @param batchName
	 *            the name of the de.jgoldhammer.alfresco.jscript.batch
	 * @param workerThreads
	 *            the number of threads which can be used for the de.jgoldhammer.alfresco.jscript.batch
	 *            processing
	 * @param batchSize
	 * 			size of the batch
	 * @param scriptNodes
	 *            the array of scriptnodes to process (if you have your own
	 *            logic to determine the nodes)
	 * @param processorFunction
	 *            the javascript function to process- the function must have the
	 *            named "process"
	 *
	 *            Example: de.jgoldhammer.alfresco.jscript.batch.runForNodes('MyProcessor', 4, 10, nodes,
	 *            function process(node){ logger.error(node); }, true);
	 * @param runAsSystem
	 *            true if the processing should be run as system, false to
	 *            process as the current user
	 * @param beforeProcessFunction
	 * 				the function to run before the processing
	 * @param afterProcessFunction
	 * 				the function to run after the processing
	 *
	 */
@ScriptMethod(code = "de.jgoldhammer.alfresco.jscript.batch.run('MyProcessor',4,10,'TEXT:alfresco',function process(node){logger.error(node);}, true);", help = "", output = "nothing", type = ScriptMethodType.WRITE)
public void runForNodes(String batchName, int workerThreads, final int batchSize, final NativeArray scriptNodes, final String processorFunction, final boolean runAsSystem, final String beforeProcessFunction, final String afterProcessFunction) {
    BatchProcessor<Collection<NodeRef>> processor;
    final Scriptable batchScope = this.scope;
    List<NodeRef> nodeRefs = convertScriptNodesArray(scriptNodes);
    processor = new BatchProcessor<Collection<NodeRef>>(batchName, transactionService.getRetryingTransactionHelper(), new SimpleListWorkProvider(nodeRefs, batchSize), workerThreads, FIXED_BATCH_SIZE, null, null, FIXED_BATCH_SIZE);
    processor.process(new ScriptedBatchProcessWorker(runAsSystem, batchScope, processorFunction, nodeRefs, beforeProcessFunction, afterProcessFunction, Context.getCurrentContext(), serviceRegistry, scriptService), true);
}
Example 7
Project: AnalyzerBeans-master  File: JavaScriptUtils.java View source code
/**
	 * Adds the values of a row to the JavaScript scope
	 * 
	 * @param scope
	 * @param inputRow
	 * @param columns
	 * @param arrayName
	 */
public static void addToScope(Scriptable scope, InputRow inputRow, InputColumn<?>[] columns, String arrayName) {
    NativeArray values = new NativeArray(columns.length * 2);
    for (int i = 0; i < columns.length; i++) {
        InputColumn<?> column = columns[i];
        Object value = inputRow.getValue(column);
        if (value != null) {
            Class<?> dataType = column.getDataType();
            if (ReflectionUtils.isNumber(dataType)) {
                value = Context.toNumber(value);
            } else if (ReflectionUtils.isBoolean(dataType)) {
                value = Context.toBoolean(value);
            }
        }
        values.put(i, values, value);
        values.put(column.getName(), values, value);
        addToScope(scope, value, column.getName(), column.getName().toLowerCase(), column.getName().toUpperCase());
    }
    addToScope(scope, values, arrayName);
}
Example 8
Project: cocoon-master  File: JXTemplateGenerator.java View source code
public Iterator getIterator(Object obj, Info i) throws Exception {
    if (!(obj instanceof Scriptable)) {
        // support Enumeration
        if (obj instanceof Enumeration) {
            final Enumeration e = (Enumeration) obj;
            return new Iterator() {

                public boolean hasNext() {
                    return e.hasMoreElements();
                }

                public Object next() {
                    return e.nextElement();
                }

                public void remove() {
                // no action
                }
            };
        }
        if (obj instanceof Iterator) {
            // support Iterator
            return (Iterator) obj;
        }
        return super.getIterator(obj, i);
    }
    if (obj instanceof NativeArray) {
        return new NativeArrayIterator((NativeArray) obj);
    }
    return new ScriptableIterator((Scriptable) obj);
}
Example 9
Project: DataCleaner-master  File: JavaScriptUtils.java View source code
/**
     * Adds the values of a row to the JavaScript scope
     *
     * @param scope
     * @param inputRow
     * @param columns
     * @param arrayName
     */
public static void addToScope(final Scriptable scope, final InputRow inputRow, final InputColumn<?>[] columns, final String arrayName) {
    final NativeArray values = new NativeArray(columns.length * 2);
    for (int i = 0; i < columns.length; i++) {
        final InputColumn<?> column = columns[i];
        Object value = inputRow.getValue(column);
        if (value != null) {
            final Class<?> dataType = column.getDataType();
            if (ReflectionUtils.isNumber(dataType)) {
                value = Context.toNumber(value);
            } else if (ReflectionUtils.isBoolean(dataType)) {
                value = Context.toBoolean(value);
            }
        }
        values.put(i, values, value);
        values.put(column.getName(), values, value);
        addToScope(scope, value, column.getName(), column.getName().toLowerCase(), column.getName().toUpperCase());
    }
    addToScope(scope, values, arrayName);
}
Example 10
Project: js4emf-master  File: PutHelper.java View source code
private Collection toCollection(Object col, Class<?> valueClass) {
    Collection<Object> result = new ArrayList<Object>();
    if (col instanceof NativeArray) {
        NativeArray array = (NativeArray) col;
        for (int i = 0; i < array.getLength(); i++) {
            addToCollection(result, array.get(i, null), valueClass);
        }
    } else if (col instanceof Collection) {
        for (Object value : (Collection) col) {
            addToCollection(result, value, valueClass);
        }
    } else {
        checkValueType(col, null, Collection.class);
    }
    return result;
}
Example 11
Project: qrone-master  File: ScriptUtils.java View source code
/**
     * 
     * @param obj
     * @return
     */
protected static Object unwrapNative(final Object obj) {
    if (obj instanceof NativeArray) {
        return unwrapNativeArray((NativeArray) obj);
    } else if (obj instanceof Callable) {
        return obj;
    } else if (obj instanceof ScriptableObject) {
        final ScriptableObject sObj = (ScriptableObject) obj;
        final List<Object> sObjIds = Arrays.asList(sObj.getAllIds());
        if (sObjIds.contains("keys")) {
            // a prototype enumerable/hash
            return unwrapObject(sObj);
        } else if (sObjIds.contains("flatten")) {
            // a prototype enumerable/array
            return unwrapPrototypeArray(sObj);
        } else {
            return unwrapObject(sObj);
        }
    } else {
        return obj;
    }
}
Example 12
Project: cometd-master  File: Utils.java View source code
private static Object jsToJava(Object jsObject, Map<Object, Boolean> identities) {
    Object existing = identities.put(jsObject, Boolean.TRUE);
    if (existing != null) {
        return jsObject;
    }
    if (jsObject == null) {
        return null;
    }
    if (jsObject == org.mozilla.javascript.Context.getUndefinedValue()) {
        return null;
    }
    if (jsObject instanceof String) {
        return jsObject;
    }
    if (jsObject instanceof Boolean) {
        return jsObject;
    }
    if (jsObject instanceof Integer) {
        return jsObject;
    }
    if (jsObject instanceof Long) {
        return jsObject;
    }
    if (jsObject instanceof Float) {
        return jsObject;
    }
    if (jsObject instanceof Double) {
        return jsObject;
    }
    if (jsObject instanceof NativeArray) {
        return convertArray((NativeArray) jsObject, identities);
    }
    if (jsObject instanceof NativeObject) {
        return convertObject((NativeObject) jsObject, identities);
    }
    if (jsObject instanceof NativeJavaObject) {
        return ((NativeJavaObject) jsObject).unwrap();
    }
    return jsObject;
}
Example 13
Project: lembos-master  File: DistributedCacheWrap.java View source code
/**
     * Java wrapper for {@link DistributedCache#checkURIs(URI[], URI[])}.
     *
     * @param ctx the JavaScript context
     * @param thisObj the 'this' object
     * @param args the function arguments
     * @param func the function being called
     *
     * @return whether or not the uris are without conflict or issue
     */
@JSStaticFunction
public static boolean checkURIs(final Context ctx, final Scriptable thisObj, final Object[] args, final Function func) {
    final Object arg0 = args.length >= 1 ? args[0] : Undefined.instance;
    final Object arg1 = args.length >= 2 ? args[1] : Undefined.instance;
    if (args.length < 2) {
        throw Utils.makeError(ctx, thisObj, LembosMessages.TWO_ARGS_EXPECTED);
    } else if (!JavaScriptUtils.isDefined(arg0)) {
        throw Utils.makeError(ctx, thisObj, LembosMessages.FIRST_ARG_REQUIRED);
    } else if (!JavaScriptUtils.isDefined(arg1)) {
        throw Utils.makeError(ctx, thisObj, LembosMessages.SECOND_ARG_REQUIRED);
    } else if (!(arg0 instanceof NativeArray)) {
        throw Utils.makeError(ctx, thisObj, LembosMessages.FIRST_ARG_MUST_BE_ARRAY);
    } else if (!(arg1 instanceof NativeArray)) {
        throw Utils.makeError(ctx, thisObj, LembosMessages.SECOND_ARG_MUST_BE_ARRAY);
    }
    final NativeArray jsFileUris = (NativeArray) arg0;
    final NativeArray jsArchiveUris = (NativeArray) arg1;
    final URI[] fileUris = new URI[(int) jsFileUris.getLength()];
    final URI[] archiveUris = new URI[(int) jsArchiveUris.getLength()];
    for (int i = 0; i < fileUris.length; i++) {
        fileUris[i] = URI.create(jsFileUris.get(i).toString());
    }
    for (int i = 0; i < archiveUris.length; i++) {
        archiveUris[i] = URI.create(jsArchiveUris.get(i).toString());
    }
    return DistributedCache.checkURIs(fileUris, archiveUris);
}
Example 14
Project: native.js-master  File: Container.java View source code
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    measureChildren(widthMeasureSpec, heightMeasureSpec);
    int width = 0, height = 0;
    if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY && MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) {
        NativeArray calc = (NativeArray) callFunc("onMeasure");
        width = ((Number) calc.get(0)).intValue();
        height = ((Number) calc.get(1)).intValue();
    } else {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        return;
    }
    if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) {
        width = MeasureSpec.getSize(widthMeasureSpec);
    }
    if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
        height = MeasureSpec.getSize(heightMeasureSpec);
    }
    setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
Example 15
Project: OCJS-master  File: javascriptAPI.java View source code
@JSFunction
public NativeArray invoke(String address, String method, Object[] params) {
    try {
        Object[] result = machine.invoke(address, method, params);
        NativeArray toReturn = new NativeArray(result.length);
        for (Object element : result) {
            toReturn.add(element);
        }
        return toReturn;
    } catch (Exception e) {
        next[0] = address;
        next[1] = method;
        next[2] = params;
        limited = true;
        NativeArray result = new NativeArray(1);
        result.add(false);
        return result;
    }
}
Example 16
Project: postman-runner-master  File: PostmanJsVariables.java View source code
private void prepareJsVariables(ResponseEntity<String> httpResponse) {
    this.responseCode = new NativeObject();
    if (httpResponse != null) {
        Map<String, String> headers = httpResponse.getHeaders().toSingleValueMap();
        List<Object> headerList = new ArrayList<Object>(headers.size());
        for (Map.Entry h : headers.entrySet()) {
            NativeObject hobj = new NativeObject();
            hobj.put("key", hobj, h.getKey());
            hobj.put("value", hobj, h.getValue());
            headerList.add(hobj);
        }
        this.responseHeaders = new NativeArray(headerList.toArray());
        this.responseBody = Context.javaToJS(httpResponse.getBody(), scope);
        this.responseCode.put("code", responseCode, httpResponse.getStatusCode().value());
        this.responseCode.put("name", responseCode, httpResponse.getStatusCode().name());
        this.responseCode.put("detail", responseCode, httpResponse.getStatusCode().toString());
    } else {
        this.responseHeaders = new NativeArray(new Object[] {});
        this.responseBody = Context.javaToJS("", scope);
        this.responseCode.put("code", responseCode, 0);
        this.responseCode.put("name", responseCode, "UNKNOWN");
        this.responseCode.put("detail", responseCode, "UNKNOWN");
    }
    // TODO: fix me
    this.responseTime = Context.javaToJS(0.0, scope);
    // TODO: fix me
    this.iteration = Context.javaToJS(0, scope);
    // The postman js var is only used to setEnvironmentVariables()
    this.postman = Context.javaToJS(this.env, scope);
    this.environment = new NativeObject();
    Set<Map.Entry<String, PostmanEnvValue>> map = this.env.lookup.entrySet();
    for (Map.Entry<String, PostmanEnvValue> e : map) {
        this.environment.put(e.getKey(), environment, e.getValue().value);
    }
    this.tests = new NativeObject();
    this.preRequestScript = new NativeObject();
}
Example 17
Project: ProvToolboxWithNeo4j-master  File: RhinoValidator.java View source code
private List<String> validate(Object json) throws IOException {
    ArrayList<String> result = new ArrayList<String>();
    Object schema = getJSON("schema/prov-json-schema.js", false);
    Global global = new Global();
    Context cx = Context.enter();
    try {
        global.initStandardObjects(cx, true);
        cx.setLanguageVersion(180);
        // Remote module path:
        // https://raw.github.com/garycourt/json-schema/master/lib/
        List<String> modulePaths = Arrays.asList("lib/");
        Require require = global.installRequire(cx, modulePaths, false);
        Scriptable exports = (Scriptable) require.call(cx, global, global, new String[] { "validate" });
        Function validate = (Function) exports.get("validate", exports);
        NativeObject res = (NativeObject) validate.call(cx, global, global, new Object[] { json, schema });
        NativeArray errors = (NativeArray) res.get("errors");
        for (int i = 0; i < errors.size(); i++) {
            NativeObject error = (NativeObject) errors.get(i);
            result.add(error.get("message").toString());
        }
    } finally {
        Context.exit();
    }
    return result;
}
Example 18
Project: scriptographer-master  File: RhinoWrapFactory.java View source code
/**
	 * getConversionWeight above is defined to call calculateConversionWeight
	 * and cache the results. Do not override getConversionWeight in any
	 * subclasses, override calculateConversionWeight instead.
	 */
public int calculateConversionWeight(Object from, Object unwrapped, Class<?> to, int defaultWeight) {
    // See if object "from" can be converted to an instance of class "to"
    // by the use of a map constructor or the setting of all the fields
    // of a NativeObject on the instance after its creation,
    // all added features of JS in Scriptographer:
    boolean isString = false;
    // Let through string as well, for ArgumentReader
    if (from instanceof Scriptable || (isString = from instanceof String)) {
        // The preferred conversion is from a native object / array to
        // a class that supports an ArgumentReader constructor.
        // Everything else is less preferred (even conversion using
        // the same constructor and another Scriptable object, e.g.
        // a wrapped Java object).
        boolean isNativeObject = from instanceof NativeObject;
        if (isNativeObject || from instanceof NativeArray || isString) {
            if (ArgumentReader.class.isAssignableFrom(to))
                return CONVERSION_TRIVIAL + 1;
            else if (ArgumentReader.canConvert(to))
                return CONVERSION_TRIVIAL + 2;
        }
        if (isNativeObject) {
            if (Map.class.isAssignableFrom(to)) {
                // and the other with EnumMap prefer the more general one:
                return Map.class.equals(to) ? CONVERSION_TRIVIAL + 1 : CONVERSION_TRIVIAL + 2;
            }
            // Try and see if unwrapping NativeObjects through JS unwrap
            // method brings us to the right type.
            unwrapped = unwrap(from);
            // from is a NativeObject.
            if (unwrapped != from && to.isInstance(unwrapped))
                return CONVERSION_TRIVIAL;
        } else if (!isString) {
            // String and ArgumentReader we tried above already
            if (getZeroArgumentConstructor(to) != null || ArgumentReader.canConvert(to)) {
                // Rectangle, Point objects!
                return unwrapped.getClass().getSimpleName().equals(to.getSimpleName()) ? CONVERSION_TRIVIAL + 1 : CONVERSION_TRIVIAL + 2;
            }
        }
    }
    return defaultWeight;
}
Example 19
Project: wro4j-master  File: TypeScriptCompiler.java View source code
public String compile(final String typeScript) {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start("initContext");
    final RhinoScriptBuilder builder = initScriptBuilder();
    stopWatch.stop();
    stopWatch.start("compile");
    try {
        final String execute = getCompilationCommand(typeScript);
        final NativeObject compilationResult = (NativeObject) builder.evaluate(execute, "compile");
        final NativeArray errors = (NativeArray) compilationResult.get(PARAM_ERRORS);
        if (errors.size() > 0) {
            throwCompilationError(errors);
        }
        return compilationResult.get(PARAM_SOURCE).toString();
    } finally {
        stopWatch.stop();
        LOG.debug(stopWatch.prettyPrint());
    }
}
Example 20
Project: zen-project-master  File: StruScriptableConvertor.java View source code
public Stru fromScriptable(Scriptable s) {
    Stru res;
    if (RHINO.isArray(s)) {
        res = Arr.make();
        //TODO unsafe
        NativeArray a = (NativeArray) s;
        final int len = (int) a.getLength();
        for (int i = 0; i < len; i++) {
            Arr arr = ((Arr) res);
            // prepare empty slot
            arr.add(null);
            Object val = RHINO.getProperty(s, i);
            if (JsonType.isNullablePrimitive(val)) {
                arr.set(i, val);
            } else if (RHINO.isUndefined(val)) {
            } else {
                arr.set(i, fromScriptable((Scriptable) val));
            }
        }
    } else {
        res = Obj.make();
        for (Object k : s.getIds()) {
            Object val = RHINO.getProperty(s, k);
            if (JsonType.isNullablePrimitive(val)) {
                ((Obj) res).put(k.toString(), val);
            } else if (RHINO.isUndefined(val)) {
            } else {
                ((Obj) res).put(k.toString(), fromScriptable((Scriptable) val));
            }
        }
    }
    return res;
}
Example 21
Project: build-tools-master  File: Main.java View source code
/**
     * 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) {
            ex.printStackTrace();
            String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(msg);
        }
    } else {
        processFile(cx, global, filename);
    }
}
Example 22
Project: closure-compiler-inline-master  File: Main.java View source code
/**
     * 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("-")) {
        Scriptable scope = getShellScope();
        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, scope);
                // 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 (useRequire && filename.equals(mainModule)) {
        try {
            require.requireMain(cx, filename);
        } catch (RhinoException rex) {
            ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
            exitCode = EXITCODE_RUNTIME_ERROR;
        } catch (VirtualMachineError ex) {
            ex.printStackTrace();
            String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(msg);
        }
    } else {
        processFile(cx, getScope(filename), filename);
    }
}
Example 23
Project: com.rc-designs.project-template-master  File: Main.java View source code
/**
     * 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) {
            ex.printStackTrace();
            String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(msg);
        }
    } else {
        processFile(cx, global, filename);
    }
}
Example 24
Project: components-master  File: AbstractQueueComponentTest.java View source code
protected TestsResult getTestsResult() {
    TestsResult result = new TestsResult();
    executeTimer();
    ScriptResult scriptResult = page.executeJavaScript("window.simulationContext.results");
    NativeArray array = (NativeArray) scriptResult.getJavaScriptResult();
    for (int i = 0; i < array.getLength(); i++) {
        NativeObject object = (NativeObject) array.get(i, array);
        String data = null;
        Object dataObject = object.get("data", object);
        if (!(dataObject instanceof Undefined)) {
            data = (String) dataObject;
        }
        Double startTime = (Double) object.get("startTime", object);
        Double endTime = (Double) object.get("endTime", object);
        Object aborted = object.get("aborted", object);
        boolean abortedBoolean = aborted instanceof Boolean && (Boolean) aborted;
        result.addData(new RequestData(data, startTime, endTime, abortedBoolean));
    }
    scriptResult = page.executeJavaScript("Timer.currentTime");
    result.setCurrentTime((Double) scriptResult.getJavaScriptResult());
    return result;
}
Example 25
Project: dltk.javascript-master  File: DBGPDebugger.java View source code
/**
	 * @param fullName
	 * @param level
	 * @param stringBuffer
	 * @param p
	 * @param ids
	 */
private int createChilds(String fullName, int level, StringBuffer stringBuffer, Scriptable p, HashSet duplicates) {
    Object[] ids = null;
    if (p instanceof LazyInitScope) {
        ids = ((LazyInitScope) p).getInitializedIds();
    } else if (p instanceof ScriptableObject && !(p instanceof XMLObject) && !(p instanceof NativeArray)) {
        ids = ((ScriptableObject) p).getAllIds();
    } else {
        ids = p.getIds();
    }
    int counter = 0;
    for (int a = 0; a < ids.length; a++) {
        if (!duplicates.add(ids[a]))
            continue;
        Object pvalue = null;
        try {
            if (ids[a] instanceof Integer) {
                pvalue = p.get(((Integer) ids[a]).intValue(), p);
            } else
                pvalue = p.get(ids[a].toString(), p);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (// HACK because
        !(pvalue instanceof Function)) // ShowFunctionsAction
        // doesnt work because of the lazy
        // behavior of plugins in Eclipse
        {
            counter++;
            if (ids[a] instanceof Integer) {
                printProperty(ids[a].toString(), fullName + "[" + ids[a] + "]", pvalue, stringBuffer, level + 1, false);
            } else {
                printProperty(ids[a].toString(), fullName + "." + ids[a], pvalue, stringBuffer, level + 1, false);
            }
        }
    }
    return counter;
}
Example 26
Project: extension-aws-master  File: RhinoScriptRunner.java View source code
protected Object unmarshal(Object inObj) {
    if (inObj instanceof NativeJavaObject) {
        return ((NativeJavaObject) inObj).unwrap();
    }
    if (inObj instanceof NativeArray) {
        NativeArray array = (NativeArray) inObj;
        Object[] result = new Object[(int) array.jsGet_length()];
        for (int i = 0; i < array.jsGet_length(); i++) {
            result[i] = unmarshal(array.get(i, null));
        }
        return result;
    }
    return inObj;
}
Example 27
Project: galen-master  File: JsFunctionLoad.java View source code
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
    if (args.length == 0) {
        throw new RuntimeException("'load' function takes at least one argument");
    }
    for (Object arg : args) {
        if (arg instanceof NativeArray) {
            NativeArray array = (NativeArray) arg;
            for (int i = 0; i < array.getLength(); i++) {
                Object path = array.get(i);
                if (path != null) {
                    load(path.toString(), cx, scope);
                } else {
                    throw new NullPointerException("Cannot have null argument in load function");
                }
            }
        } else if (arg == null) {
            throw new NullPointerException("Cannot have null argument in load function");
        } else {
            load(arg.toString(), cx, scope);
        }
    }
    return null;
}
Example 28
Project: gecco-master  File: JSVarFieldRender.java View source code
@SuppressWarnings({ "rawtypes" })
private Object injectJsVarField(HttpRequest request, BeanMap beanMap, Field field, Context cx, ScriptableObject scope) {
    Class clazz = field.getType();
    JSVar jsVar = field.getAnnotation(JSVar.class);
    String var = jsVar.var();
    Object jsObj = scope.get(var, scope);
    if (jsObj instanceof NativeObject || jsObj instanceof NativeArray) {
        String jsonPath = jsVar.jsonpath();
        // 将javascript��格�化为json对象
        Object jsonObj = NativeJSON.stringify(cx, scope, jsObj, null, null);
        // 使用fastjson将json字符串格�化为JSONObject
        Object json = JSON.parse(jsonObj.toString());
        // 解�jsonpath
        Object src = com.alibaba.fastjson.JSONPath.eval(json, jsonPath);
        // 如果解�出�的是字符串,�试转�为json对象
        try {
            if (src instanceof String) {
                src = JSON.parse(src.toString());
            }
        } catch (Exception ex) {
        }
        // 将json对象转�为javabean属性
        try {
            Object value = Conversion.getValue(clazz, src);
            return value;
        } catch (Exception e) {
            log.error("field [" + field.getName() + "] conversion error, value=" + src);
        }
    } else if (jsObj instanceof Boolean || jsObj instanceof Number || jsObj instanceof String) {
        try {
            Object value = Conversion.getValue(clazz, jsObj);
            return value;
        } catch (Exception e) {
            log.error("field [" + field.getName() + "] conversion error, value=" + jsObj);
        }
    }
    return null;
}
Example 29
Project: geoserver-master  File: JavaScriptPluginTest.java View source code
/**
     * Test for catalog access through the geoserver.js module.
     * @throws ScriptException 
     */
public void testGeoServerCatalogNamespaces() throws ScriptException {
    ScriptEngine engine = getScriptManager().createNewEngine("js");
    // get list of namespaces in catalog
    Object result = engine.eval("require('geoserver/catalog').namespaces");
    assertTrue(result instanceof NativeArray);
    NativeArray array = (NativeArray) result;
    assertEquals("incorrect number of namespaces", 5, array.getLength());
    @SuppressWarnings("serial") Map<String, String> expectedNamespaces = new HashMap<String, String>() {

        {
            put("cdf", "http://www.opengis.net/cite/data");
            put("cgf", "http://www.opengis.net/cite/geometry");
            put("cite", "http://www.opengis.net/cite");
            put("gs", "http://geoserver.org");
            put("sf", "http://cite.opengeospatial.org/gmlsf");
        }
    };
    Map<String, String> actualNamespaces = new HashMap<String, String>();
    for (Object o : array) {
        Scriptable s = (Scriptable) o;
        actualNamespaces.put((String) s.get("alias", s), (String) s.get("uri", s));
    }
    assertEquals("unexpected namespaces", expectedNamespaces, actualNamespaces);
}
Example 30
Project: hackpad-master  File: Main.java View source code
/**
     * 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) {
            ex.printStackTrace();
            String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(msg);
        }
    } else {
        processFile(cx, global, filename);
    }
}
Example 31
Project: io-master  File: DcResponse.java View source code
/**
     * JavaScript�forEachをJava�処��る���メソッド.
     * @param element forEach��素�一件��渡�れる
     * @param number 渡�れ��素�index�渡�れる
     * @param object forEach対象�オブジェクト�全�素��列�渡�れる
     * @throws IOException IOException
     */
public void bodyResponseFunction(Object element, double number, NativeArray object) throws IOException {
    if (element instanceof DcInputStream) {
        // �状�Engine上�JavaScript��イナリを直接扱��
        // Javaã?®ã‚¹ãƒˆãƒªãƒ¼ãƒ ã‚’ã??ã?®ã?¾ã?¾JavaScript内ã?§æ‰±ã?†ã?“ã?¨ã?§å¯¾å¿œ
        DcInputStream io = (DcInputStream) element;
        byte[] buf = new byte[BUFFER_SIZE];
        int bufLength;
        while ((bufLength = io.read(buf)) != -1) {
            this.output.write(buf, 0, bufLength);
        }
    } else {
        // 文字列�ユーザスクリプト�Content-type�charset�指定��文字エンコーディング�出力。
        this.output.write(((String) element).getBytes(charset));
    }
}
Example 32
Project: javascript-plugin-master  File: JSToRepresentationConverter.java View source code
public Representation convert(final Object data) {
    if (data instanceof Table) {
        return new GremlinTableRepresentation((Table) data);
    }
    if (data instanceof Iterable) {
        return getListRepresentation((Iterable) data);
    }
    if (data instanceof Iterator) {
        Iterator iterator = (Iterator) data;
        return getIteratorRepresentation(iterator);
    }
    if (data instanceof NativeArray) {
        NativeArray na = (NativeArray) data;
        Object[] array = new Object[(int) na.getLength()];
        for (Object o : na.getIds()) {
            int index = (Integer) o;
            array[index] = na.get(index, null);
        }
        return getListRepresentation(Arrays.asList(array));
    }
    return getSingleRepresentation(data);
}
Example 33
Project: jslint4java-master  File: UtilTest.java View source code
@Test
public void testJavaToJS_JSArrays() {
    String[] ary = new String[] { "a", "b" };
    Object result = Util.javaToJS(ary, scope);
    assertThat(result, instanceOf(NativeArray.class));
    // Woohoo—it got the correct class.  Now, let's check it works OK.
    NativeArray nAry = (NativeArray) result;
    assertThat(nAry.getLength(), is(2L));
    assertThat(nAry.get(0, nAry), is((Object) "a"));
    assertThat(nAry.get(1, nAry), is((Object) "b"));
}
Example 34
Project: rhino-mirror-master  File: Main.java View source code
/**
     * 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) {
            ex.printStackTrace();
            String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(msg);
        }
    } else {
        processFile(cx, global, filename);
    }
}
Example 35
Project: rhino_titanium-master  File: Main.java View source code
/**
     * 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 {
        processFile(cx, global, filename);
    }
}
Example 36
Project: richfaces-master  File: AbstractQueueComponentTest.java View source code
protected TestsResult getTestsResult() {
    TestsResult result = new TestsResult();
    executeTimer();
    ScriptResult scriptResult = page.executeJavaScript("window.simulationContext.results");
    NativeArray array = (NativeArray) scriptResult.getJavaScriptResult();
    for (int i = 0; i < array.getLength(); i++) {
        NativeObject object = (NativeObject) array.get(i, array);
        String data = null;
        Object dataObject = object.get("data", object);
        if (!(dataObject instanceof Undefined)) {
            data = (String) dataObject;
        }
        Double startTime = (Double) object.get("startTime", object);
        Double endTime = (Double) object.get("endTime", object);
        Object aborted = object.get("aborted", object);
        boolean abortedBoolean = aborted instanceof Boolean && (Boolean) aborted;
        result.addData(new RequestData(data, startTime, endTime, abortedBoolean));
    }
    scriptResult = page.executeJavaScript("Timer.currentTime");
    result.setCurrentTime((Double) scriptResult.getJavaScriptResult());
    return result;
}
Example 37
Project: sling-master  File: ScriptableNode.java View source code
/**
     * Gets the value of a (Javascript) property or child node. If there is a single single-value
     * JCR property of this node, return its string value. If there are multiple properties
     * of the same name or child nodes of the same name, return an array.
     */
@Override
public Object get(String name, Scriptable start) {
    // builtin javascript properties (jsFunction_ etc.) have priority
    final Object fromSuperclass = super.get(name, start);
    if (fromSuperclass != Scriptable.NOT_FOUND) {
        return fromSuperclass;
    }
    if (node == null) {
        return Undefined.instance;
    }
    final List<Scriptable> items = new ArrayList<Scriptable>();
    // Add all matching nodes to result
    try {
        NodeIterator it = node.getNodes(name);
        while (it.hasNext()) {
            items.add(ScriptRuntime.toObject(this, it.nextNode()));
        }
    } catch (RepositoryException e) {
        log.debug("RepositoryException while collecting Node children", e);
    }
    // Add all matching properties to result
    boolean isMulti = false;
    try {
        PropertyIterator it = node.getProperties(name);
        while (it.hasNext()) {
            Property prop = it.nextProperty();
            if (prop.getDefinition().isMultiple()) {
                isMulti = true;
                Value[] values = prop.getValues();
                for (int i = 0; i < values.length; i++) {
                    items.add(wrap(values[i]));
                }
            } else {
                items.add(wrap(prop.getValue()));
            }
        }
    } catch (RepositoryException e) {
        log.debug("RepositoryException while collecting Node properties", e);
    }
    if (items.size() == 0) {
        return getNative(name, start);
    } else if (items.size() == 1 && !isMulti) {
        return items.iterator().next();
    } else {
        NativeArray result = new NativeArray(items.toArray());
        ScriptRuntime.setObjectProtoAndParent(result, this);
        return result;
    }
}
Example 38
Project: StreamFS-master  File: ModelResource.java View source code
public void processIt(Context cx, Scriptable scope, String process, JSONArray buffer) {
    String e = "var buf = " + buffer.toString() + "; var p=" + process + "; p.func(buf)";
    e = e.trim();
    logger.fine("processIt:  " + e);
    Js2JSONUtils utils = new Js2JSONUtils();
    try {
        //System.out.println("var buf = "+buffer.toString()+";\nvar p="+process+";\n\np.select(buf)");
        Scriptable procItScript = (Scriptable) cx.evaluateString(scope, e, "<procitscript>", 1, null);
        String outputStr = utils.toJSONString(procItScript);
        logger.info("processing_output:" + outputStr);
        JSONObject pData = (JSONObject) JSONSerializer.toJSON(outputStr);
        /*Object[] ids = procItScript.getIds();
			JSONObject pData = new JSONObject();
			for(int k=0; k<ids.length; k++){
				String thisKey = ids[k].toString();
				Object thisValue = procItScript.get(thisKey, procItScript);
				if(thisValue instanceof org.mozilla.javascript.NativeArray){
					NativeArray nativeArray = (NativeArray)thisValue;
					//logger.info("Blah: " + utils.toJSONString(thisValue));

					JSONArray array = new JSONArray();
					pData.put(thisKey, array);
				} else {
					pData.put(thisKey, thisValue.toString());
				}
			}*/
        logger.info("Thread-" + myThread.getName() + " processed data: " + outputStr);
        UUID myPubid = UUID.fromString(myThread.getName());
        String pubPath = database.getIs4RRPath(myPubid);
        Resource p = null;
        if (pubPath != null && (p = RESTServer.getResource(pubPath)) != null && p instanceof ModelGenericPublisherResource) {
            ModelGenericPublisherResource r = (ModelGenericPublisherResource) p;
            r.saveData(pData);
        } else {
            String s = "No available publisher for thread-" + myThread.getName() + "\n\tpubPath=" + pubPath + "\n\tp=" + p + "\n\tinstanceof ModelGenericPub? " + (p instanceof ModelGenericPublisherResource) + "\n\ttype=" + p.TYPE;
            logger.info(s);
        }
    } catch (Exception ex) {
        logger.log(Level.WARNING, "", ex);
    }
}
Example 39
Project: third-party-tools-master  File: Main.java View source code
/**
     * 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) {
            ex.printStackTrace();
            String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(msg);
        }
    } else {
        processFile(cx, global, filename);
    }
}
Example 40
Project: bi-platform-v2-master  File: JavaScriptResultSet.java View source code
public static Object jsFunction_setColumnHeaders(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) {
    if (args == null) {
        return null;
    }
    if (args.length == 0) {
        return null;
    }
    JavaScriptResultSet resultSet = (JavaScriptResultSet) thisObj;
    if ((args.length == 1) && (args[0] instanceof NativeArray)) {
        NativeArray array = (NativeArray) args[0];
        resultSet.setMetaData(JavaScriptResultSet.createMetadata(array, thisObj));
    } else if ((args.length == 2) && (args[0] instanceof NativeArray) && (args[1] instanceof NativeArray)) {
        NativeArray array = (NativeArray) args[0];
        MemoryMetaData metaData = JavaScriptResultSet.createMetadata(array, thisObj);
        // create some metadata objects
        array = (NativeArray) args[1];
        int length = (int) array.getLength();
        String columnTypes[] = new String[length];
        for (int i = 0; i < length; i++) {
            columnTypes[i] = array.get(i, thisObj).toString();
        }
        metaData.setColumnTypes(columnTypes);
        resultSet.setMetaData(metaData);
    } else {
        int length = args.length;
        String columnHeaders[] = new String[length];
        for (int i = 0; i < length; i++) {
            columnHeaders[i] = args[i].toString();
        }
        MemoryMetaData metaData = new MemoryMetaData(new String[][] { columnHeaders }, null);
        resultSet.setMetaData(metaData);
    }
    return null;
}
Example 41
Project: pentaho-platform-master  File: JavaScriptResultSet.java View source code
public static Object jsFunction_setColumnHeaders(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) {
    if (args == null) {
        return null;
    }
    if (args.length == 0) {
        return null;
    }
    JavaScriptResultSet resultSet = (JavaScriptResultSet) thisObj;
    if ((args.length == 1) && (args[0] instanceof NativeArray)) {
        NativeArray array = (NativeArray) args[0];
        resultSet.setMetaData(JavaScriptResultSet.createMetadata(array, thisObj));
    } else if ((args.length == 2) && (args[0] instanceof NativeArray) && (args[1] instanceof NativeArray)) {
        NativeArray array = (NativeArray) args[0];
        MemoryMetaData metaData = JavaScriptResultSet.createMetadata(array, thisObj);
        // create some metadata objects
        array = (NativeArray) args[1];
        int length = (int) array.getLength();
        String[] columnTypes = new String[length];
        for (int i = 0; i < length; i++) {
            columnTypes[i] = array.get(i, thisObj).toString();
        }
        metaData.setColumnTypes(columnTypes);
        resultSet.setMetaData(metaData);
    } else {
        int length = args.length;
        String[] columnHeaders = new String[length];
        for (int i = 0; i < length; i++) {
            columnHeaders[i] = args[i].toString();
        }
        MemoryMetaData metaData = new MemoryMetaData(new String[][] { columnHeaders }, null);
        resultSet.setMetaData(metaData);
    }
    return null;
}
Example 42
Project: carbon-governance-master  File: CollectionHostObject.java View source code
public static NativeArray jsFunction_getChildren(Context cx, Scriptable thisObj, Object[] arguments, Function funObj) throws CarbonException {
    CollectionHostObject collectionHostObject = (CollectionHostObject) thisObj;
    if (arguments.length == 0) {
        try {
            return new NativeArray(((Collection) collectionHostObject.getResource()).getChildren());
        } catch (RegistryException e) {
            throw new CarbonException("Error occurred while creating a new Resource.", e);
        }
    } else if (arguments.length == 2) {
        if (arguments[0] instanceof Number && arguments[1] instanceof Number) {
            try {
                return new NativeArray(((Collection) collectionHostObject.getResource()).getChildren(((Number) arguments[0]).intValue(), ((Number) arguments[1]).intValue()));
            } catch (RegistryException e) {
                throw new CarbonException("Error occurred while creating a new Resource.", e);
            }
        } else {
            throw new CarbonException("Invalid argument types for getChildren() method");
        }
    } else {
        throw new CarbonException("Invalid no. of arguments for getChildren() method");
    }
}
Example 43
Project: closure-template-master  File: AbstractSoyPrintDirectiveTestCase.java View source code
public void runTests() {
    StringBuilder generatedJsExprsAsJsArray = new StringBuilder();
    ImmutableList.Builder<String> expectedOutputsListBuilder = ImmutableList.builder();
    generatedJsExprsAsJsArray.append("[");
    boolean generatedJsExprsAsJsArrayHasElements = false;
    for (TestData testData : testDataListBuilder.build()) {
        expectedOutputsListBuilder.add(testData.expectedOutput);
        ImmutableList.Builder<JsExpr> args = ImmutableList.builder();
        for (String argJs : testData.directiveArgsJs) {
            args.add(new JsExpr("(" + argJs + ")", Integer.MAX_VALUE));
        }
        if (generatedJsExprsAsJsArrayHasElements) {
            generatedJsExprsAsJsArray.append(",\n");
        }
        generatedJsExprsAsJsArray.append("String(").append(testData.directive.applyForJsSrc(new JsExpr("(" + testData.valueJs + ")", Integer.MAX_VALUE), args.build()).getText()).append(")");
        generatedJsExprsAsJsArrayHasElements = true;
    }
    generatedJsExprsAsJsArray.append("]");
    Context context = new ContextFactory().enterContext();
    // Only running once.
    context.setOptimizationLevel(-1);
    ScriptableObject globalScope = context.initStandardObjects();
    // Define a fake navigator object for Closure's userAgent library.
    NativeObject navigator = new NativeObject();
    ScriptableObject.putConstProperty(navigator, "userAgent", "testZilla");
    globalScope.defineProperty("navigator", navigator, ScriptableObject.DONTENUM);
    // Disable asserts, so that zSoyz will be returned instead of throwing an exception.
    NativeObject defines = new NativeObject();
    ScriptableObject.putConstProperty(defines, "goog.asserts.ENABLE_ASSERTS", false);
    globalScope.defineProperty("CLOSURE_UNCOMPILED_DEFINES", defines, ScriptableObject.CONST);
    try {
        String soyutilsPath = getSoyUtilsPath();
        Reader soyutils = new InputStreamReader(new FileInputStream(soyutilsPath), UTF_8);
        try {
            String basename = soyutilsPath.substring(soyutilsPath.lastIndexOf('/') + 1);
            context.evaluateReader(globalScope, soyutils, basename, 1, null);
        } finally {
            soyutils.close();
        }
    } catch (IOException ex) {
        throw new AssertionError(ex);
    }
    NativeArray outputAsJsList = (NativeArray) context.evaluateString(globalScope, generatedJsExprsAsJsArray.toString(), // File name for JS traces.
    getClass() + ":" + testName.getMethodName(), 1, null);
    long n = outputAsJsList.getLength();
    ImmutableList.Builder<String> actualOutputListBuilder = ImmutableList.builder();
    for (int i = 0; i < n; ++i) {
        actualOutputListBuilder.add((String) outputAsJsList.get(i, globalScope));
    }
    assertThat(Joiner.on('\n').join(actualOutputListBuilder.build())).isEqualTo(Joiner.on('\n').join(expectedOutputsListBuilder.build()));
}
Example 44
Project: closure-templates-master  File: AbstractSoyPrintDirectiveTestCase.java View source code
public void runTests() {
    StringBuilder generatedJsExprsAsJsArray = new StringBuilder();
    ImmutableList.Builder<String> expectedOutputsListBuilder = ImmutableList.builder();
    generatedJsExprsAsJsArray.append("[");
    boolean generatedJsExprsAsJsArrayHasElements = false;
    for (TestData testData : testDataListBuilder.build()) {
        expectedOutputsListBuilder.add(testData.expectedOutput);
        ImmutableList.Builder<JsExpr> args = ImmutableList.builder();
        for (String argJs : testData.directiveArgsJs) {
            args.add(new JsExpr("(" + argJs + ")", Integer.MAX_VALUE));
        }
        if (generatedJsExprsAsJsArrayHasElements) {
            generatedJsExprsAsJsArray.append(",\n");
        }
        generatedJsExprsAsJsArray.append("String(").append(testData.directive.applyForJsSrc(new JsExpr("(" + testData.valueJs + ")", Integer.MAX_VALUE), args.build()).getText()).append(")");
        generatedJsExprsAsJsArrayHasElements = true;
    }
    generatedJsExprsAsJsArray.append("]");
    Context context = new ContextFactory().enterContext();
    // Only running once.
    context.setOptimizationLevel(-1);
    ScriptableObject globalScope = context.initStandardObjects();
    // Define a fake navigator object for Closure's userAgent library.
    NativeObject navigator = new NativeObject();
    ScriptableObject.putConstProperty(navigator, "userAgent", "testZilla");
    globalScope.defineProperty("navigator", navigator, ScriptableObject.DONTENUM);
    // Disable asserts, so that zSoyz will be returned instead of throwing an exception.
    NativeObject defines = new NativeObject();
    ScriptableObject.putConstProperty(defines, "goog.asserts.ENABLE_ASSERTS", false);
    globalScope.defineProperty("CLOSURE_UNCOMPILED_DEFINES", defines, ScriptableObject.CONST);
    try {
        String soyutilsPath = getSoyUtilsPath();
        Reader soyutils = new InputStreamReader(new FileInputStream(soyutilsPath), UTF_8);
        try {
            String basename = soyutilsPath.substring(soyutilsPath.lastIndexOf('/') + 1);
            context.evaluateReader(globalScope, soyutils, basename, 1, null);
        } finally {
            soyutils.close();
        }
    } catch (IOException ex) {
        throw new AssertionError(ex);
    }
    NativeArray outputAsJsList = (NativeArray) context.evaluateString(globalScope, generatedJsExprsAsJsArray.toString(), // File name for JS traces.
    getClass() + ":" + testName.getMethodName(), 1, null);
    long n = outputAsJsList.getLength();
    ImmutableList.Builder<String> actualOutputListBuilder = ImmutableList.builder();
    for (int i = 0; i < n; ++i) {
        actualOutputListBuilder.add((String) outputAsJsList.get(i, globalScope));
    }
    assertThat(Joiner.on('\n').join(actualOutputListBuilder.build())).isEqualTo(Joiner.on('\n').join(expectedOutputsListBuilder.build()));
}
Example 45
Project: codehaus-mojo-master  File: JsLintReport.java View source code
/**
     * {@inheritDoc}
     * 
     * @see org.apache.maven.reporting.AbstractMavenReport#executeReport(java.util.Locale)
     * @see http://code.google.com/p/jsdoc-toolkit/wiki/CmdlineOptions
     */
protected void executeReport(Locale locale) throws MavenReportException {
    File workDirectory = getWorkDirectory();
    unpackJavascriptDependency("com.jslint:jslint", workDirectory);
    File jslint = new File(workDirectory, "fulljslint.js");
    List args = new ArrayList();
    Map context = new HashMap();
    StringBuffer options = new StringBuffer("{");
    options.append("\n  adsafe : ").append(aDsafe ? "true" : "false");
    options.append(",\n bitwise : ").append(disallowBitwiseOperators ? "true" : "false");
    options.append(",\n browser : ").append(assumeBrowser ? "true" : "false");
    options.append(",\n cap : ").append(tolerateHtmlCase ? "true" : "false");
    options.append(",\n debug : ").append(tolerateDebuggerStatements ? "true" : "false");
    options.append(",\n eqeqeq : ").append(disallowEqualEqualandNotEqual ? "true" : "false");
    options.append(",\n evil : ").append(tolerateEval ? "true" : "false");
    options.append(",\n forin : ").append(tolerateUnfilteredForIn ? "true" : "false");
    options.append(",\n fragment : ").append(tolerateHtmlFragments ? "true" : "false");
    options.append(",\n laxbreak : ").append(tolerateSloppyLineBreaking ? "true" : "false");
    options.append(",\n nomen : ").append(disallowLeadingUnderscoreInIdentifiers ? "true" : "false");
    options.append(",\n on : ").append(tolerateHtmlEventHandlers ? "true" : "false");
    options.append(",\n passfail : ").append(stopOnFirstError ? "true" : "false");
    options.append(",\n plusplus : ").append(disallowPlusPlusandMinusMinus ? "true" : "false");
    options.append(",\n rhino : true ");
    options.append(",\n undef : ").append(disallowUndefinedVariables ? "true" : "false");
    options.append(",\n white : ").append(strictWhitespace ? "true" : "false");
    options.append(",\n widget : ").append(assumeYahooWidget ? "true" : "false");
    options.append("\n}");
    getLog().debug("options : " + options);
    String[] scripts = getScripts(sourceDirectory);
    Sink sink = getSink();
    sink.head();
    sink.title();
    sink.text("JsLint Javascript Verifier report");
    sink.title_();
    sink.head_();
    sink.body();
    for (int i = 0; i < scripts.length; i++) {
        sink.section3();
        sink.sectionTitle3();
        sink.text(scripts[i]);
        sink.sectionTitle3_();
        sink.paragraph();
        try {
            String file = new File(sourceDirectory, scripts[i]).toURL().toString();
            getLog().debug("Generate jslint report for " + file);
            String script = "JSLINT( readUrl( '" + file + "', '" + encoding + "' ), " + options + " ); JSLINT.errors;";
            NativeArray errors = (NativeArray) evalScript(jslint, script, (String[]) args.toArray(new String[0]), context);
            if (errors == null || errors.getLength() == 0) {
                sink.text(getBundle(locale).getString(getName() + ".no-error"));
            } else {
                sink.table();
                sink.tableRow();
                sink.tableHeaderCell();
                sink.text("position");
                sink.tableHeaderCell_();
                sink.tableHeaderCell();
                sink.text("error");
                sink.tableHeaderCell_();
                sink.tableHeaderCell();
                sink.text("code");
                sink.tableHeaderCell_();
                sink.tableRow_();
                long length = errors.getLength();
                for (int j = 0; j < length; j++) {
                    NativeObject object = (NativeObject) errors.get(j, null);
                    sink.tableRow();
                    sink.tableCell();
                    Double line = (Double) object.get("line", null);
                    Double character = (Double) object.get("character", null);
                    sink.text(line.longValue() + ":" + character.longValue());
                    sink.tableCell_();
                    sink.tableCell();
                    String reason = String.valueOf(object.get("reason", null));
                    sink.text(reason);
                    sink.tableCell_();
                    sink.tableCell();
                    String evidence = String.valueOf(object.get("evidence", null));
                    sink.rawText(evidence);
                    sink.tableCell_();
                    sink.tableRow_();
                }
                sink.table_();
            }
        // sink.rawText( report.toString() );
        } catch (Exception e) {
            getLog().warn("Error generating report for " + scripts[i], e);
            sink.text("Error generating report for " + scripts[i]);
        }
        sink.paragraph_();
        sink.section3_();
    }
    sink.body_();
    sink.flush();
    sink.close();
}
Example 46
Project: google-closure-compiler-master  File: Main.java View source code
/**
     * Evaluate JavaScript source.
     *
     * @param cx the current context
     * @param filename the name of the file to compile, or null
     *                 for interactive mode.
     * @throws IOException if the source could not be read
     * @throws RhinoException thrown during evaluation of source
     */
public static void processSource(Context cx, String filename) throws IOException {
    if (filename == null || filename.equals("-")) {
        Scriptable scope = getShellScope();
        Charset cs;
        String charEnc = shellContextFactory.getCharacterEncoding();
        if (charEnc != null) {
            cs = Charset.forName(charEnc);
        } else {
            cs = Charset.defaultCharset();
        }
        ShellConsole console = global.getConsole(cs);
        if (filename == null) {
            // print implementation version
            console.println(cx.getImplementationVersion());
        }
        int lineno = 1;
        boolean hitEOF = false;
        while (!hitEOF) {
            String[] prompts = global.getPrompts(cx);
            String prompt = null;
            if (filename == null)
                prompt = prompts[0];
            console.flush();
            String source = "";
            // Collect lines of source to compile.
            while (true) {
                String newline;
                try {
                    newline = console.readLine(prompt);
                } catch (IOException ioe) {
                    console.println(ioe.toString());
                    break;
                }
                if (newline == null) {
                    hitEOF = true;
                    break;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source))
                    break;
                prompt = prompts[1];
            }
            try {
                Script script = cx.compileString(source, "<stdin>", lineno, null);
                if (script != null) {
                    Object result = script.exec(cx, scope);
                    // Avoid printing out undefined or function definitions.
                    if (result != Context.getUndefinedValue() && !(result instanceof Function && source.trim().startsWith("function"))) {
                        try {
                            console.println(Context.toString(result));
                        } catch (RhinoException rex) {
                            ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                        }
                    }
                    NativeArray h = global.history;
                    h.put((int) h.getLength(), h, source);
                }
            } catch (RhinoException rex) {
                ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                exitCode = EXITCODE_RUNTIME_ERROR;
            } catch (VirtualMachineError ex) {
                ex.printStackTrace();
                String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
                Context.reportError(msg);
                exitCode = EXITCODE_RUNTIME_ERROR;
            }
        }
        console.println();
        console.flush();
    } else if (useRequire && filename.equals(mainModule)) {
        require.requireMain(cx, filename);
    } else {
        processFile(cx, getScope(filename), filename);
    }
}
Example 47
Project: hifivetools-master  File: AbstractJSChecker.java View source code
@Override
public Object run(Context cx) {
    JSCheckerResult result = new JSCheckerResult();
    NativeArray errors = getErrors();
    logger.debug("error count : " + errors.getLength());
    for (int i = 0; i < errors.getLength(); i++) {
        Scriptable err = (Scriptable) errors.get(i, errors);
        if (err != null) {
            addError(result, err);
        }
    }
    return result;
}
Example 48
Project: magma-master  File: GlobalMethods.java View source code
/**
   * Creates a new value sequence.
   * <p/>
   * <pre>
   *   newSequence('Foo')
   *   newSequence(['Foo', 'Bar'])
   *   newSequence(123)
   *   newSequence('123','integer')
   *   newSequence([123, 456])
   *   newSequence(['123', '456'],'integer')
   * </pre>
   *
   * @return an instance of {@code ScriptableValue}
   */
public static ScriptableValue newSequence(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    Object value = args[0];
    ValueType valueType = args.length > 1 ? ValueType.Factory.forName((String) args[1]) : null;
    List<Value> values;
    if (value instanceof NativeArray) {
        values = nativeArrayToValueList(valueType, (NativeArray) value);
    } else {
        values = new ArrayList<>();
        value = ensurePrimitiveValue(value);
        values.add(valueType == null ? ValueType.Factory.newValue((Serializable) value) : valueType.valueOf(value));
    }
    if (valueType == null) {
        if (values.isEmpty()) {
            throw new IllegalArgumentException("cannot determine ValueType for null object");
        }
        valueType = values.get(0).getValueType();
    }
    return new ScriptableValue(thisObj, ValueType.Factory.newSequence(valueType, values));
}
Example 49
Project: mayaa-master  File: ScriptEnvironmentImpl.java View source code
public Object convertFromScriptObject(Object scriptObject, Class expectedClass) {
    if (scriptObject != null && conversionRequires(scriptObject, expectedClass)) {
        Object result = RhinoUtil.convertResult(null, expectedClass, scriptObject);
        if (result instanceof NativeArray) {
            NativeArray jsArray = (NativeArray) result;
            int length = (int) jsArray.getLength();
            Object[] array = new Object[length];
            for (int i = 0; i < length; i++) {
                array[i] = jsArray.get(i, null);
            }
            result = array;
        }
        return result;
    }
    return scriptObject;
}
Example 50
Project: servoy-client-master  File: Utils.java View source code
/**
	 * Returns a js/json string representation of the given {@link Scriptable}
	 * @param scriptable
	 * @param processed map to prevent loops in graph
	 * @return the scriptable as string
	 */
private static CharSequence getScriptableString(Scriptable scriptable, Map<Scriptable, CharSequence> processed) {
    if (scriptable instanceof Record || scriptable instanceof FoundSet)
        return scriptable.toString();
    if (scriptable instanceof XMLObject || scriptable instanceof NativeError)
        return scriptable.toString();
    CharSequence processedString = processed.get(scriptable);
    if (processedString != null) {
        return processedString;
    }
    if (processed.size() > 10)
        return scriptable.toString();
    if (//$NON-NLS-1$
    scriptable instanceof NativeArray)
        //$NON-NLS-1$
        processed.put(scriptable, "Array[SelfRef]");
    else
        //$NON-NLS-1$
        processed.put(scriptable, "Object[SelfRef]");
    Object[] ids = scriptable.getIds();
    if (ids != null && ids.length > 0) {
        StringBuilder sb = new StringBuilder();
        if (scriptable instanceof NativeArray)
            sb.append('[');
        else
            sb.append('{');
        for (Object object : ids) {
            if (!(object instanceof Integer)) {
                sb.append(object);
                sb.append(':');
            }
            Object value = null;
            if (object instanceof String) {
                value = scriptable.get((String) object, scriptable);
            } else if (object instanceof Number) {
                value = scriptable.get(((Number) object).intValue(), scriptable);
            }
            if (!(value instanceof NativeJavaMethod)) {
                if (value instanceof Scriptable) {
                    sb.append(getScriptableString((Scriptable) value, processed));
                } else {
                    sb.append(value);
                }
                sb.append(',');
            }
        }
        sb.setLength(sb.length() - 1);
        if (scriptable instanceof NativeArray)
            sb.append(']');
        else
            sb.append('}');
        processed.put(scriptable, sb);
        return sb;
    }
    Object defaultValue;
    try {
        defaultValue = scriptable.getDefaultValue(String.class);
    } catch (Exception e) {
        defaultValue = null;
    }
    if (defaultValue == null)
        defaultValue = scriptable.toString();
    processed.put(scriptable, defaultValue.toString());
    return defaultValue.toString();
}
Example 51
Project: TouchDB-Android-master  File: TDJavaScriptViewCompiler.java View source code
@Override
public void map(Map<String, Object> document, TDViewMapEmitBlock emitter) {
    Context ctx = Context.enter();
    try {
        ctx.setOptimizationLevel(-1);
        ctx.setWrapFactory(wrapFactory);
        //create a place to hold results
        String placeHolder = "var map_results = [];";
        ctx.evaluateString(globalScope, placeHolder, "placeHolder", 1, null);
        //register the emit function
        String emitFunction = "var emit = function(key, value) { map_results.push([key, value]); };";
        ctx.evaluateString(globalScope, emitFunction, "emit", 1, null);
        //register the map function
        String mapSrc = "var map = " + src + ";";
        try {
            ctx.evaluateString(globalScope, mapSrc, "map", 1, null);
        } catch (org.mozilla.javascript.EvaluatorException e) {
            Log.e(TDDatabase.TAG, "Javascript syntax error in view:\n" + src, e);
            return;
        }
        // Need to stringify the json tree, as the ContextWrapper is unable
        // to correctly convert nested json to their js representation.
        // More specifically, if a dictionary is included that contains an array as a value 
        // that array will not be wrapped correctly but you'll get the plain 
        // java.util.ArrayList instead - and then an error.
        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        try {
            json = mapper.writeValueAsString(document);
        } catch (IOException e) {
            Log.e(TDDatabase.TAG, "Error reserializing json from the db: " + document, e);
            return;
        }
        String mapInvocation = "map(" + json + ");";
        try {
            ctx.evaluateString(globalScope, mapInvocation, "map invocation", 1, null);
        } catch (org.mozilla.javascript.RhinoException e) {
            Log.e(TDDatabase.TAG, "Error in javascript view:\n" + src + "\n with document:\n" + document, e);
            return;
        }
        //now pull values out of the place holder and emit them
        NativeArray mapResults = (NativeArray) globalScope.get("map_results", globalScope);
        for (int i = 0; i < mapResults.getLength(); i++) {
            NativeArray mapResultItem = (NativeArray) mapResults.get(i);
            if (mapResultItem.getLength() == 2) {
                Object key = mapResultItem.get(0);
                Object value = mapResultItem.get(1);
                emitter.emit(key, value);
            } else {
                Log.e(TDDatabase.TAG, "Expected 2 element array with key and value");
            }
        }
    } finally {
        Context.exit();
    }
}
Example 52
Project: ef-orm-master  File: JSAdapter.java View source code
public Object[] getIds() {
    Function func = getAdapteeFunction(GET_PROPIDS);
    if (func != null) {
        Object val = call(func, new Object[0]);
        // in most cases, adaptee would return native JS array
        if (val instanceof NativeArray) {
            NativeArray array = (NativeArray) val;
            Object[] res = new Object[(int) array.getLength()];
            for (int index = 0; index < res.length; index++) {
                res[index] = mapToId(array.get(index, array));
            }
            return res;
        } else if (val instanceof NativeJavaArray) {
            // may be attempt wrapped Java array
            Object tmp = ((NativeJavaArray) val).unwrap();
            Object[] res;
            if (tmp.getClass() == Object[].class) {
                Object[] array = (Object[]) tmp;
                res = new Object[array.length];
                for (int index = 0; index < array.length; index++) {
                    res[index] = mapToId(array[index]);
                }
            } else {
                // just return an empty array
                res = Context.emptyArgs;
            }
            return res;
        } else {
            // some other return type, just return empty array
            return Context.emptyArgs;
        }
    } else {
        return getAdaptee().getIds();
    }
}
Example 53
Project: gda-dal-master  File: ScriptedRule.java View source code
/**
	 * Try to fetch the parameter descriptions from the script.
	 */
private List<String> fetchParameterDescriptions() {
    List<String> result = new ArrayList<String>();
    Object parameterDescriptionsObject = _scriptScope.get(SCRIPT_PARAMTER_DESCRIPTIONS, _scriptScope);
    if ((parameterDescriptionsObject instanceof NativeArray)) {
        NativeArray parameterDescriptions = (NativeArray) parameterDescriptionsObject;
        for (int i = 0; i < parameterDescriptions.getIds().length; i++) {
            Object o = parameterDescriptions.get(i, parameterDescriptions);
            if (o != null) {
                result.add(o.toString());
            }
        }
    }
    return result;
}
Example 54
Project: org.eclipse.birt.common-master  File: JavascriptEvalUtil.java View source code
/**
	 * Handles a Rhino script evaluation result, converting Javascript object
	 * into equivalent Java objects if necessary.
	 * @param inputObj Object returned by rhino engine.
	 * @return If inputObj is a native Javascript object, its equivalent Java object 
	 *   is returned; otherwise inputObj is returned
	 */
public static Object convertJavascriptValue(Object inputObj) {
    if (inputObj instanceof Undefined) {
        return null;
    }
    if (inputObj instanceof IdScriptableObject) {
        // Return type is possibly a Javascript native object
        // Convert to Java object with same value
        String jsClass = ((Scriptable) inputObj).getClassName();
        if ("Date".equals(jsClass)) {
            return Context.toType(inputObj, Date.class);
        } else if ("Boolean".equals(jsClass)) {
            return Boolean.valueOf(Context.toBoolean(inputObj));
        } else if ("Number".equals(jsClass)) {
            return new Double(Context.toNumber(inputObj));
        } else if ("String".equals(jsClass)) {
            return inputObj.toString();
        } else if ("Array".equals(jsClass)) {
            Object[] obj = new Object[(int) ((NativeArray) inputObj).getLength()];
            for (int i = 0; i < obj.length; i++) {
                obj[i] = convertJavascriptValue(((NativeArray) inputObj).get(i, null));
            }
            return obj;
        }
    } else if (inputObj instanceof Wrapper) {
        return ((Wrapper) inputObj).unwrap();
    } else if (inputObj instanceof Scriptable) {
        return ((Scriptable) inputObj).getDefaultValue(null);
    }
    return inputObj;
}
Example 55
Project: rhq-master  File: JavascriptCompletor.java View source code
private Map<String, List<Object>> findJavascriptContextMatches(ScriptableObject object, String start) {
    // javascript expression).
    if (object instanceof NativeArray) {
        return Collections.emptyMap();
    }
    HashMap<String, List<Object>> ret = new HashMap<String, List<Object>>();
    for (Object o : object.getIds()) {
        String key = o.toString();
        if (start == null || start.isEmpty() || key.startsWith(start)) {
            Object target = object.get(key);
            ret.put(key, new ArrayList<Object>(Arrays.asList(target)));
        }
    }
    return ret;
}
Example 56
Project: effektif-master  File: RhinoVariableScope.java View source code
/** maps variableIds to internal values */
public Map<String, TypedValueImpl> getUpdatedVariableValues() {
    Map<String, TypedValueImpl> updatedValues = new HashMap<>();
    for (String scriptVariableName : updated) {
        Object localObject = objects.get(scriptVariableName);
        String variableId = mappings != null ? mappings.get(scriptVariableName) : null;
        if (variableId == null) {
            variableId = scriptVariableName;
        }
        VariableInstanceImpl variableInstance = scopeInstance.findVariableInstance(variableId);
        if (variableInstance != null) {
            DataTypeImpl type = variableInstance.type;
            // NativeObject implements Map
            // NativeArray implements List
            // So the data type conversion from javascript to internal should work
            Object value = null;
            if (localObject instanceof DirtyCheckingNativeObject) {
                DirtyCheckingNativeObject nativeObject = (DirtyCheckingNativeObject) localObject;
                value = nativeObject.value;
            } else if (localObject instanceof DirtyCheckingNativeArray) {
                DirtyCheckingNativeArray nativeArray = (DirtyCheckingNativeArray) localObject;
                value = nativeArray.values;
            } else {
                value = localObject;
            }
            TypedValueImpl typedValue = new TypedValueImpl(type, value);
            updatedValues.put(variableId, typedValue);
        }
    }
    return updatedValues;
}
Example 57
Project: geogebra-master  File: NativeTypedArrayView.java View source code
private NativeTypedArrayView js_constructor(Context cx, Scriptable scope, Object[] args) {
    if (!isArg(args, 0)) {
        return construct(NativeArrayBuffer.EMPTY_BUFFER, 0, 0);
    } else if ((args[0] instanceof Number) || (args[0] instanceof String)) {
        // Create a zeroed-out array of a certain length
        int length = ScriptRuntime.toInt32(args[0]);
        NativeArrayBuffer buffer = makeArrayBuffer(cx, scope, length * getBytesPerElement());
        return construct(buffer, 0, length);
    } else if (args[0] instanceof NativeTypedArrayView) {
        // Copy elements from the old array and convert them into our own
        NativeTypedArrayView src = (NativeTypedArrayView) args[0];
        NativeArrayBuffer na = makeArrayBuffer(cx, scope, src.length * getBytesPerElement());
        NativeTypedArrayView v = construct(na, 0, src.length);
        for (int i = 0; i < src.length; i++) {
            v.js_set(i, src.js_get(i));
        }
        return v;
    } else if (args[0] instanceof NativeArrayBuffer) {
        // Make a slice of an existing buffer, with shared storage
        NativeArrayBuffer na = (NativeArrayBuffer) args[0];
        int byteOff = isArg(args, 1) ? ScriptRuntime.toInt32(args[1]) : 0;
        int byteLen;
        if (isArg(args, 2)) {
            byteLen = ScriptRuntime.toInt32(args[2]) * getBytesPerElement();
        } else {
            byteLen = na.getLength() - byteOff;
        }
        if ((byteOff < 0) || (byteOff > na.buffer.length)) {
            throw ScriptRuntime.constructError("RangeError", "offset out of range");
        }
        if ((byteLen < 0) || ((byteOff + byteLen) > na.buffer.length)) {
            throw ScriptRuntime.constructError("RangeError", "length out of range");
        }
        if ((byteOff % getBytesPerElement()) != 0) {
            throw ScriptRuntime.constructError("RangeError", "offset must be a multiple of the byte size");
        }
        if ((byteLen % getBytesPerElement()) != 0) {
            throw ScriptRuntime.constructError("RangeError", "offset and buffer must be a multiple of the byte size");
        }
        return construct(na, byteOff, byteLen / getBytesPerElement());
    } else if (args[0] instanceof NativeArray) {
        // Copy elements of the array and convert them to the correct type
        List l = (List) args[0];
        NativeArrayBuffer na = makeArrayBuffer(cx, scope, l.size() * getBytesPerElement());
        NativeTypedArrayView v = construct(na, 0, l.size());
        int p = 0;
        for (Object o : l) {
            v.js_set(p, o);
            p++;
        }
        return v;
    } else {
        throw ScriptRuntime.constructError("Error", "invalid argument");
    }
}
Example 58
Project: handlebars.java-master  File: RhinoHandlebars.java View source code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Object apply(final Object context, final Options options) throws IOException {
    Object jsContext = toJsObject(options.context.model(), options.context);
    Object arg0 = context;
    Integer paramSize = options.data(Context.PARAM_SIZE);
    if (paramSize == 0) {
        arg0 = "___NOT_SET_";
    } else {
        arg0 = toJsObject(arg0, options.context);
    }
    Object result = helper.apply(jsContext, arg0, new OptionsJs(options));
    if (result instanceof NativeArray) {
        return new BetterNativeArray((List) result, options.context);
    }
    return result;
}
Example 59
Project: studio2-master  File: JSLintValidator.java View source code
/**
	 * lintScript
	 * 
	 * @param JSLintScript
	 * @param cx
	 * @param script
	 * @param path
	 * @param collectErrors
	 * @param collectWarnings
	 */
private void lintScript(Script JSLintScript, Context cx, String script, String path, boolean collectErrors, boolean collectWarnings) {
    Scriptable scope = cx.initStandardObjects();
    // JSLint jsl = new JSLint();
    // jsl.exec(cx, scope);
    JSLintScript.exec(cx, scope);
    //$NON-NLS-1$
    Object fObj = scope.get("jslint", scope);
    if (!(fObj instanceof Function)) {
        IdeLog.logInfo(JSPlugin.getDefault(), Messages.JSErrorManager_JSLintUndefined);
    } else {
        //$NON-NLS-1$
        Object[] functionArgs = { script, scope.get("aptanaOptions", scope) };
        Function f = (Function) fObj;
        // PC: we ignore the result, because i have found that with some versions, there might
        // be
        // errors but this function returned true (false == errors)
        f.call(cx, scope, scope, functionArgs).toString();
        //$NON-NLS-1$
        Object errorObject = f.get("errors", scope);
        if (errorObject != null && errorObject instanceof NativeArray) {
            NativeArray errorArray = (NativeArray) errorObject;
            Object[] ids = errorArray.getIds();
            if (ids.length == 0) {
                return;
            }
            boolean lastIsError = false;
            NativeObject last = (NativeObject) errorArray.get(Integer.parseInt(ids[ids.length - 1].toString()), scope);
            if (last == null) {
                lastIsError = true;
            }
            if (lastIsError == false && collectWarnings == false) {
                return;
            }
            for (int i = 0; i < ids.length; i++) {
                try {
                    NativeObject v = (NativeObject) errorArray.get(Integer.parseInt(ids[i].toString()), scope);
                    if (v != null) {
                        int line = (int) Double.parseDouble(//$NON-NLS-1$
                        v.get("line", scope).toString()) + 1;
                        String reason = //$NON-NLS-1$
                        v.get("reason", scope).toString().trim();
                        int character = (int) Double.parseDouble(//$NON-NLS-1$
                        v.get(//$NON-NLS-1$
                        "character", //$NON-NLS-1$
                        scope).toString());
                        String evidence = //$NON-NLS-1$
                        v.get("evidence", scope).toString().trim();
                        UnifiedErrorReporter rep = (UnifiedErrorReporter) cx.getErrorReporter();
                        if (i == ids.length - 2 && lastIsError) {
                            if (collectErrors) {
                                rep.error(reason, path, line, evidence, character);
                            }
                        } else if (collectWarnings) {
                            rep.warning(reason, path, line, evidence, character);
                        }
                    }
                } catch (Exception e) {
                    IdeLog.logInfo(JSPlugin.getDefault(), "Error running JavaScript lint script", e);
                }
            }
        }
    }
}
Example 60
Project: webtools.jsdt.debug-master  File: StackFrame.java View source code
/**
	 * Serialize a function or object
	 * 
	 * @param scriptable
	 * @param result
	 * @see JSONConstants#FUNCTION
	 * @see JSONConstants#OBJECT
	 */
private void serializeFunctionOrObject(Scriptable scriptable, Map result) {
    if (scriptable instanceof BaseFunction) {
        result.put(JSONConstants.TYPE, JSONConstants.FUNCTION);
        result.put(JSONConstants.NAME, ((BaseFunction) scriptable).getFunctionName());
    } else if (scriptable instanceof NativeArray) {
        result.put(JSONConstants.TYPE, JSONConstants.ARRAY);
    } else {
        result.put(JSONConstants.TYPE, JSONConstants.OBJECT);
    }
    result.put(JSONConstants.CLASS_NAME, scriptable.getClassName());
    Object constructorFunction = null;
    if (ScriptableObject.hasProperty(scriptable, JSONConstants.CONSTRUCTOR)) {
        constructorFunction = ScriptableObject.getProperty(scriptable, JSONConstants.CONSTRUCTOR);
    }
    result.put(JSONConstants.CONSTRUCTOR_FUNCTION, createHandle(constructorFunction));
    result.put(JSONConstants.PROTOTYPE_OBJECT, createHandle(scriptable.getPrototype()));
    if (scriptable instanceof NativeJavaObject)
        result.put(JSONConstants.PROPERTIES, createJavaObjectProperties((NativeJavaObject) scriptable));
    else
        result.put(JSONConstants.PROPERTIES, createProperties(scriptable));
}
Example 61
Project: closure-compiler-old-master  File: Main.java View source code
/**
     * Evaluate JavaScript source.
     *
     * @param cx the current context
     * @param filename the name of the file to compile, or null
     *                 for interactive mode.
     * @throws IOException if the source could not be read
     * @throws RhinoException thrown during evaluation of source
     */
public static void processSource(Context cx, String filename) throws IOException {
    if (filename == null || filename.equals("-")) {
        Scriptable scope = getShellScope();
        Charset cs;
        String charEnc = shellContextFactory.getCharacterEncoding();
        if (charEnc != null) {
            cs = Charset.forName(charEnc);
        } else {
            cs = Charset.defaultCharset();
        }
        ShellConsole console = global.getConsole(cs);
        if (filename == null) {
            // print implementation version
            console.println(cx.getImplementationVersion());
        }
        int lineno = 1;
        boolean hitEOF = false;
        while (!hitEOF) {
            String[] prompts = global.getPrompts(cx);
            String prompt = null;
            if (filename == null)
                prompt = prompts[0];
            console.flush();
            String source = "";
            // Collect lines of source to compile.
            while (true) {
                String newline;
                try {
                    newline = console.readLine(prompt);
                } catch (IOException ioe) {
                    console.println(ioe.toString());
                    break;
                }
                if (newline == null) {
                    hitEOF = true;
                    break;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source))
                    break;
                prompt = prompts[1];
            }
            try {
                Script script = cx.compileString(source, "<stdin>", lineno, null);
                if (script != null) {
                    Object result = script.exec(cx, scope);
                    // Avoid printing out undefined or function definitions.
                    if (result != Context.getUndefinedValue() && !(result instanceof Function && source.trim().startsWith("function"))) {
                        try {
                            console.println(Context.toString(result));
                        } catch (RhinoException rex) {
                            ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                        }
                    }
                    NativeArray h = global.history;
                    h.put((int) h.getLength(), h, source);
                }
            } catch (RhinoException rex) {
                ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                exitCode = EXITCODE_RUNTIME_ERROR;
            } catch (VirtualMachineError ex) {
                ex.printStackTrace();
                String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
                Context.reportError(msg);
                exitCode = EXITCODE_RUNTIME_ERROR;
            }
        }
        console.println();
        console.flush();
    } else if (useRequire && filename.equals(mainModule)) {
        require.requireMain(cx, filename);
    } else {
        processFile(cx, getScope(filename), filename);
    }
}
Example 62
Project: e4x_rhino_test-master  File: Main.java View source code
/**
     * 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());
        }
        // Use the interpreter for interactive input
        cx.setOptimizationLevel(-1);
        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 {
        processFile(cx, global, filename);
    }
    System.gc();
}
Example 63
Project: jaggery-master  File: DatabaseHostObject.java View source code
@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);
    }
}
Example 64
Project: joinery-master  File: DataFrameAdapter.java View source code
public static Scriptable jsConstructor(final Context ctx, final Object[] args, final Function ctor, final boolean newExpr) {
    if (args.length == 3 && args[0] instanceof NativeArray) {
        final List<List<Object>> data = new ArrayList<>();
        final NativeArray array = NativeArray.class.cast(args[2]);
        final Object[] ids = array.getIds();
        for (int i = 0; i < array.getLength(); i++) {
            data.add(asList(array.get((int) ids[i], null)));
        }
        return new DataFrameAdapter(new DataFrame<Object>(asList(args[0]), asList(args[1]), data));
    } else if (args.length == 2 && args[0] instanceof NativeArray) {
        return new DataFrameAdapter(new DataFrame<Object>(asList(args[0]), asList(args[1])));
    } else if (args.length == 1 && args[0] instanceof NativeArray) {
        return new DataFrameAdapter(new DataFrame<Object>(asList(args[0])));
    } else if (args.length > 0) {
        final String[] columns = new String[args.length];
        for (int i = 0; i < args.length; i++) {
            columns[i] = Context.toString(args[i]);
        }
        return new DataFrameAdapter(new DataFrame<>(columns));
    }
    return new DataFrameAdapter(new DataFrame<>());
}
Example 65
Project: Loboevolution-master  File: NativeTypedArrayView.java View source code
private NativeTypedArrayView js_constructor(Context cx, Scriptable scope, Object[] args) {
    if (!isArg(args, 0)) {
        return construct(NativeArrayBuffer.EMPTY_BUFFER, 0, 0);
    } else if ((args[0] instanceof Number) || (args[0] instanceof String)) {
        // Create a zeroed-out array of a certain length
        int length = ScriptRuntime.toInt32(args[0]);
        NativeArrayBuffer buffer = makeArrayBuffer(cx, scope, length * getBytesPerElement());
        return construct(buffer, 0, length);
    } else if (args[0] instanceof NativeTypedArrayView) {
        // Copy elements from the old array and convert them into our own
        NativeTypedArrayView src = (NativeTypedArrayView) args[0];
        NativeArrayBuffer na = makeArrayBuffer(cx, scope, src.length * getBytesPerElement());
        NativeTypedArrayView v = construct(na, 0, src.length);
        for (int i = 0; i < src.length; i++) {
            v.js_set(i, src.js_get(i));
        }
        return v;
    } else if (args[0] instanceof NativeArrayBuffer) {
        // Make a slice of an existing buffer, with shared storage
        NativeArrayBuffer na = (NativeArrayBuffer) args[0];
        int byteOff = isArg(args, 1) ? ScriptRuntime.toInt32(args[1]) : 0;
        int byteLen;
        if (isArg(args, 2)) {
            byteLen = ScriptRuntime.toInt32(args[2]) * getBytesPerElement();
        } else {
            byteLen = na.getLength() - byteOff;
        }
        if ((byteOff < 0) || (byteOff > na.buffer.length)) {
            throw ScriptRuntime.constructError("RangeError", "offset out of range");
        }
        if ((byteLen < 0) || ((byteOff + byteLen) > na.buffer.length)) {
            throw ScriptRuntime.constructError("RangeError", "length out of range");
        }
        if ((byteOff % getBytesPerElement()) != 0) {
            throw ScriptRuntime.constructError("RangeError", "offset must be a multiple of the byte size");
        }
        if ((byteLen % getBytesPerElement()) != 0) {
            throw ScriptRuntime.constructError("RangeError", "offset and buffer must be a multiple of the byte size");
        }
        return construct(na, byteOff, byteLen / getBytesPerElement());
    } else if (args[0] instanceof NativeArray) {
        // Copy elements of the array and convert them to the correct type
        List l = (List) args[0];
        NativeArrayBuffer na = makeArrayBuffer(cx, scope, l.size() * getBytesPerElement());
        NativeTypedArrayView v = construct(na, 0, l.size());
        int p = 0;
        for (Object o : l) {
            v.js_set(p, o);
            p++;
        }
        return v;
    } else {
        throw ScriptRuntime.constructError("Error", "invalid argument");
    }
}
Example 66
Project: NoRootScriptDroid-master  File: Main.java View source code
/**
     * Evaluate JavaScript source.
     *
     * @param cx       the current context
     * @param filename the name of the file to compile, or null
     *                 for interactive mode.
     * @throws IOException    if the source could not be read
     * @throws RhinoException thrown during evaluation of source
     */
public static void processSource(Context cx, String filename) throws IOException {
    if (filename == null || filename.equals("-")) {
        Scriptable scope = getShellScope();
        Charset cs;
        String charEnc = shellContextFactory.getCharacterEncoding();
        if (charEnc != null) {
            cs = Charset.forName(charEnc);
        } else {
            cs = Charset.defaultCharset();
        }
        ShellConsole console = global.getConsole(cs);
        if (filename == null) {
            // print implementation version
            console.println(cx.getImplementationVersion());
        }
        int lineno = 1;
        boolean hitEOF = false;
        while (!hitEOF) {
            String[] prompts = global.getPrompts(cx);
            String prompt = null;
            if (filename == null)
                prompt = prompts[0];
            console.flush();
            String source = "";
            // Collect lines of source to compile.
            while (true) {
                String newline;
                try {
                    newline = console.readLine(prompt);
                } catch (IOException ioe) {
                    console.println(ioe.toString());
                    break;
                }
                if (newline == null) {
                    hitEOF = true;
                    break;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source))
                    break;
                prompt = prompts[1];
            }
            try {
                Script script = cx.compileString(source, "<stdin>", lineno, null);
                if (script != null) {
                    Object result = script.exec(cx, scope);
                    // Avoid printing out undefined or function definitions.
                    if (result != Context.getUndefinedValue() && !(result instanceof Function && source.trim().startsWith("function"))) {
                        try {
                            console.println(Context.toString(result));
                        } catch (RhinoException rex) {
                            ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                        }
                    }
                // NativeArray h = global.history;
                //h.put((int) h.getLength(), h, source);
                }
            } catch (RhinoException rex) {
                ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                exitCode = EXITCODE_RUNTIME_ERROR;
            } catch (VirtualMachineError ex) {
                ex.printStackTrace();
                String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
                Context.reportError(msg);
                exitCode = EXITCODE_RUNTIME_ERROR;
            }
        }
        console.println();
        console.flush();
    } else if (useRequire && filename.equals(mainModule)) {
        require.requireMain(cx, filename);
    } else {
        processFile(cx, getScope(filename), filename);
    }
}
Example 67
Project: volity-master  File: GameUI.java View source code
/**
     * Parse the various allowable arguments to a seatmeak() call. Return a Map
     * (mapping String seatids to String mark names). Some keys may be invalid
     * seat IDs, and some values may be invalid mark names, but neither will be
     * null.
     */
public static Map parseSeatMarkArgs(Object[] args) {
    Map map = new HashMap();
    if (args.length == 0)
        return map;
    if (args.length > 1)
        throw new IllegalArgumentException("seatmark must have zero or one arguments");
    Object arg = args[0];
    if (arg != null && arg instanceof NativeArray) {
        NativeArray arr = (NativeArray) arg;
        Object[] ids = arr.getIds();
        for (int ix = 0; ix < ids.length; ix++) {
            Object id = ids[ix];
            Object val;
            if (id instanceof Integer)
                val = arr.get(((Integer) id).intValue(), arr);
            else
                val = arr.get(id.toString(), arr);
            if (id == null || (id instanceof Undefined))
                throw new IllegalArgumentException("seatmark map keys may not be null.");
            if (id instanceof ScriptableObject) {
                id = ((ScriptableObject) id).getDefaultValue(String.class);
            }
            if (!(id instanceof String))
                throw new IllegalArgumentException("seatmark map keys must be convertible to strings");
            if (val == null || (val instanceof Undefined))
                continue;
            if (!(val instanceof String))
                throw new IllegalArgumentException("seatmark map values must be strings or null");
            if (val.equals(""))
                continue;
            map.put(id, val);
        }
        return map;
    }
    if (arg != null && arg instanceof String) {
        map.put(arg, "turn");
        return map;
    }
    if (arg != null && arg instanceof ScriptableObject) {
        Object val = ((ScriptableObject) arg).getDefaultValue(String.class);
        if (val instanceof String) {
            map.put((String) val, "turn");
            return map;
        }
    }
    throw new IllegalArgumentException("seatmark must take no argument, a string, or an associative array.");
}
Example 68
Project: wso2-synapse-master  File: ScriptMessageContext.java View source code
private String serializeJSON(Object obj) {
    StringWriter json = new StringWriter();
    if (obj instanceof Wrapper) {
        obj = ((Wrapper) obj).unwrap();
    }
    if (obj instanceof NativeObject) {
        json.append("{");
        NativeObject o = (NativeObject) obj;
        Object[] ids = o.getIds();
        boolean first = true;
        for (Object id : ids) {
            String key = (String) id;
            Object value = o.get((String) id, o);
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append("\"").append(key).append("\" : ").append(serializeJSON(value));
        }
        json.append("}");
    } else if (obj instanceof NativeArray) {
        json.append("[");
        NativeArray o = (NativeArray) obj;
        Object[] ids = o.getIds();
        boolean first = true;
        for (Object id : ids) {
            Object value = o.get((Integer) id, o);
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append(serializeJSON(value));
        }
        json.append("]");
    } else if (obj instanceof Object[]) {
        json.append("[");
        boolean first = true;
        for (Object value : (Object[]) obj) {
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append(serializeJSON(value));
        }
        json.append("]");
    } else if (obj instanceof String) {
        json.append("\"").append(obj.toString()).append("\"");
    } else if (obj instanceof Integer || obj instanceof Long || obj instanceof Float || obj instanceof Double || obj instanceof Short || obj instanceof BigInteger || obj instanceof BigDecimal || obj instanceof Boolean) {
        json.append(obj.toString());
    } else {
        json.append("{}");
    }
    return json.toString();
}
Example 69
Project: esxx-master  File: Application.java View source code
public JSResponse wrapResult(Context cx, Object result) {
    if (result == null || result == Context.getUndefinedValue()) {
        throw new ESXXException("No result from '" + getAppName() + "'");
    } else if (result instanceof JSResponse) {
        return (JSResponse) result;
    } else if (result instanceof NativeArray) {
        // Automatically convert an JS Array into a Response
        return (JSResponse) JSESXX.newObject(cx, applicationScope, "Response", cx.getElements((NativeArray) result));
    } else if (result instanceof Number) {
        return (JSResponse) JSESXX.newObject(cx, applicationScope, "Response", new Object[] { result, null, null, null });
    } else {
        return (JSResponse) JSESXX.newObject(cx, applicationScope, "Response", new Object[] { 200, null, result, null });
    }
}
Example 70
Project: jdbcrunner-master  File: Config.java View source code
private void loadVariables(Script script) throws ApplicationException {
    Object variable = null;
    variable = script.getVariable(VAR_JDBC_DRIVER);
    if (variable instanceof String) {
        this.jdbcDriver = (String) variable;
    }
    variable = script.getVariable(VAR_JDBC_URL);
    if (variable instanceof String) {
        this.jdbcUrl = (String) variable;
    }
    variable = script.getVariable(VAR_JDBC_USER);
    if (variable instanceof String) {
        this.jdbcUser = (String) variable;
    }
    variable = script.getVariable(VAR_JDBC_PASS);
    if (variable instanceof String) {
        this.jdbcPass = (String) variable;
    }
    variable = script.getVariable(VAR_LOAD);
    if (variable instanceof Boolean) {
        this.isLoad = ((Boolean) variable).booleanValue();
    }
    variable = script.getVariable(VAR_WARMUP_TIME);
    if (variable instanceof Number) {
        this.warmupTime = ((Number) variable).intValue();
    }
    variable = script.getVariable(VAR_MEASUREMENT_TIME);
    if (variable instanceof Number) {
        this.measurementTime = ((Number) variable).intValue();
    }
    variable = script.getVariable(VAR_N_TX_TYPES);
    if (variable instanceof Number) {
        this.nTxTypes = ((Number) variable).intValue();
        // sleepTime�throttle��列サイズをnTxTypes����る
        this.sleepTimes = new long[nTxTypes];
        this.throttles = new int[nTxTypes];
    }
    variable = script.getVariable(VAR_N_AGENTS);
    if (variable instanceof Number) {
        this.nAgents = ((Number) variable).intValue();
        // コ�クションプール�接続数をエージェント数����る
        this.connPoolSize = nAgents;
    }
    variable = script.getVariable(VAR_CONN_POOL_SIZE);
    if (variable instanceof Number) {
        this.connPoolSize = ((Number) variable).intValue();
    }
    variable = script.getVariable(VAR_STMT_CACHE_SIZE);
    if (variable instanceof Number) {
        this.stmtCacheSize = ((Number) variable).intValue();
    }
    variable = script.getVariable(VAR_AUTO_COMMIT);
    if (variable instanceof Boolean) {
        this.isAutoCommit = ((Boolean) variable).booleanValue();
    }
    variable = script.getVariable(VAR_SLEEP_TIME);
    if (variable instanceof Number) {
        // 書�1:var sleepTime = 1000;
        long value = ((Number) variable).longValue();
        for (int i = 0; i < nTxTypes; i++) {
            this.sleepTimes[i] = value;
        }
    } else if (variable instanceof NativeArray) {
        // 書�2:var sleepTime = new Array(1000,
        // 2000);
        Object[] array = (Object[]) Context.jsToJava(variable, Object[].class);
        if (array.length != nTxTypes) {
            throw new ApplicationException(Resources.getString("Config.ILLEGAL_NUMBER_OF_SLEEPTIMES"));
        }
        for (int i = 0; i < nTxTypes; i++) {
            if (array[i] instanceof Number) {
                this.sleepTimes[i] = ((Number) array[i]).longValue();
            } else {
                throw new ApplicationException(Resources.getString("Config.ILLEGAL_NUMBERS_SLEEP_TIME"));
            }
        }
    }
    variable = script.getVariable(VAR_THROTTLE);
    if (variable instanceof Number) {
        // 書�1:var throttle = 100;
        int value = ((Number) variable).intValue();
        for (int i = 0; i < nTxTypes; i++) {
            this.throttles[i] = value;
        }
        this.doThrottleByTotal = true;
    } else if (variable instanceof NativeArray) {
        // 書�2:var throttle = new Array(100,
        // 200);
        Object[] array = (Object[]) Context.jsToJava(variable, Object[].class);
        if (array.length != nTxTypes) {
            throw new ApplicationException(Resources.getString("Config.ILLEGAL_NUMBER_OF_THROTTLES"));
        }
        for (int i = 0; i < nTxTypes; i++) {
            if (array[i] instanceof Number) {
                this.throttles[i] = ((Number) array[i]).intValue();
            } else {
                throw new ApplicationException(Resources.getString("Config.ILLEGAL_NUMBERS_THROTTLE"));
            }
        }
        this.doThrottleByTotal = false;
    }
    variable = script.getVariable(VAR_DEBUG);
    if (variable instanceof Boolean) {
        this.isDebug = ((Boolean) variable).booleanValue();
    }
    variable = script.getVariable(VAR_TRACE);
    if (variable instanceof Boolean) {
        this.isTrace = ((Boolean) variable).booleanValue();
        if (isTrace) {
            this.isDebug = true;
        }
    }
    variable = script.getVariable(VAR_LOG_DIR);
    if (variable instanceof String) {
        this.logDir = (String) variable;
    }
}
Example 71
Project: JSCover-master  File: JSONDataMerger.java View source code
public SortedMap<String, FileData> jsonToMap(String data) {
    TreeMap<String, FileData> map = new TreeMap<String, FileData>();
    try {
        NativeObject json = (NativeObject) parser.parseValue(data);
        for (Object scriptURI : json.keySet()) {
            NativeObject scriptData = (NativeObject) json.get(scriptURI);
            NativeArray lineCoverageArray = (NativeArray) scriptData.get("lineData");
            NativeObject branchJSONArray = (NativeObject) scriptData.get("branchData");
            List<Integer> countData = new ArrayList<Integer>(lineCoverageArray.size());
            for (int i = 0; i < lineCoverageArray.size(); i++) countData.add((Integer) lineCoverageArray.get(i));
            // Function Coverage (HA-CA) 
            NativeArray functionCoverageArray = (NativeArray) scriptData.get("functionData");
            List<Integer> funcData = new ArrayList<Integer>();
            if (functionCoverageArray != null) {
                for (int i = 0; i < functionCoverageArray.size(); i++) funcData.add((Integer) functionCoverageArray.get(i));
            }
            SortedMap<Integer, List<BranchData>> branchLineMap = new TreeMap<Integer, List<BranchData>>();
            if (branchJSONArray != null) {
                readBranchLines(branchJSONArray, branchLineMap);
            }
            map.put((String) scriptURI, new FileData((String) scriptURI, countData, funcData, branchLineMap));
        }
    } catch (JsonParser.ParseException e) {
        throw new RuntimeException(e);
    }
    return map;
}
Example 72
Project: Protocoder-master  File: PUIGeneric.java View source code
public PGrid newGridOf(String type, NativeArray array, int cols, final addGridOfCB callbackfn) {
    PGrid gridLayout = new PGrid(a.get());
    int counter = 0;
    int num = (int) array.getLength();
    int rows = (int) Math.ceil(num / 2);
    // try {
    //cols = obj.get("cols");
    //rows = obj.get("rows");
    //num = rows * cols;
    //name = obj.getString("name");
    //prefix = obj.getString("prefix");
    //postfix = obj.getString("postfix");
    //} catch (JSONException e) {
    //    e.printStackTrace();
    //}
    PGridRow ll2 = null;
    int i = 0;
    for (int j = 0; j < cols * rows; j++) {
        if (j % cols == 0) {
            ll2 = gridLayout.addRow(cols);
            i++;
            Log.d(TAG, "added new row");
        }
        Log.d(TAG, "counter/num " + counter + " " + num + " " + i + " " + cols + " " + rows);
        final ProtocoderNativeObject cbData = new ProtocoderNativeObject();
        if (counter >= num) {
            Log.d(TAG, "this space");
            ll2.addViewInRow(new Space(a.get()));
        //   break;
        } else {
            String name = (String) array.get(counter);
            cbData.addPE("name", name);
            cbData.addPE("name", name);
            cbData.addPE("i", i);
            cbData.addPE("j", j);
            cbData.addPE("count", counter);
            //button
            if (type.equals("button")) {
                PButton btn = null;
                btn = newButton(name, new addGenericButtonCB() {

                    @Override
                    public void event() {
                        cbData.addPE("data", "");
                        callbackfn.event(cbData);
                    }
                });
                cbData.addPE("view", btn);
                ll2.addViewInRow(btn);
            //imagebutton
            } else if (type.equals("imagebutton")) {
                PImageButton btn = new PImageButton(a.get());
            //toggle
            } else if (type.equals("toggle")) {
                PToggleButton toggle = newToggle(name, false, new addGenericToggleCB() {

                    @Override
                    public void event(boolean isChecked) {
                        cbData.addPE("data", isChecked);
                        callbackfn.event(cbData);
                    }
                });
                ll2.addViewInRow(toggle);
            //hslider
            } else if (type.equals("hslider")) {
                PSlider slider = newSlider(1024, 0, new addGenericSliderCB() {

                    @Override
                    public void event(float progress) {
                        cbData.addPE("data", progress);
                        callbackfn.event(cbData);
                    }
                });
                ll2.addViewInRow(slider);
            //vslider
            } else if (type.equals("vslider")) {
            //knob
            } else if (type.equals("knob")) {
            }
            counter++;
        }
    }
    //MLog.network(a.get(), "qq", "" + gridLayout);
    return gridLayout;
}