Search in sources :

Example 71 with Context

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

the class RhinoCallable method call.

public Object call(Object obj, Object[] args) throws RhinoScriptException {
    // function on it.
    try {
        Scriptable scope = ScriptableObject.getTopLevelScope(function);
        Scriptable wrapper = RhinoEngine.getWrapper(obj, scope);
        for (int i = 0; i < args.length; i++) args[i] = Context.javaToJS(args[i], scope);
        Context cx = Context.getCurrentContext();
        Object ret = function.call(cx, wrapper, wrapper, args);
        if (ret == Undefined.instance) {
            // Do not return undefined, as it cannot be handled by the
            // native side, e.g. ConversionUtils.toBoolean would produce
            // true.
            ret = null;
        } else if (ret instanceof Wrapper) {
            // Unwrap if the return value is a native java object:
            ret = ((Wrapper) ret).unwrap();
        }
        return ret;
    } catch (Throwable t) {
        // Re-throw if it was a RhinoScriptException already
        if (t.getCause() instanceof RhinoScriptException)
            throw (RhinoScriptException) t.getCause();
        throw new RhinoScriptException(engine, t);
    }
}
Also used : Context(org.mozilla.javascript.Context) Wrapper(org.mozilla.javascript.Wrapper) ScriptableObject(org.mozilla.javascript.ScriptableObject) Scriptable(org.mozilla.javascript.Scriptable)

Example 72 with Context

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

the class RhinoEngine method observe.

@Override
public boolean observe(Map object, Object key, PropertyObserver observer) {
    if (object instanceof ScriptableObject) {
        ScriptableObject obj = (ScriptableObject) object;
        Context cx = Context.getCurrentContext();
        PropertyDescriptor desc = obj.getOwnPropertyDescriptor(cx, key);
        if (desc != null && desc.isDataDescriptor()) {
            ObserverGetterSetter getterSetter = new ObserverGetterSetter(obj, key, desc, observer);
            obj.defineOwnProperty(cx, key, new PropertyDescriptor(getterSetter, getterSetter, desc.isEnumerable(), desc.isConfigurable(), true));
        }
        return true;
    }
    return false;
}
Also used : Context(org.mozilla.javascript.Context) ScriptableObject(org.mozilla.javascript.ScriptableObject) PropertyDescriptor(org.mozilla.javascript.PropertyDescriptor)

Example 73 with Context

use of org.mozilla.javascript.Context in project jslint4java by happygiraffe.

the class JSLint method callReport.

/**
 * Construct a JSLint error report. This is in two parts: a list of errors, and an optional
 * function report.
 *
 * @param errorsOnly
 *            if the function report should be omitted.
 * @return the report, an HTML string.
 */
@NeedsContext
private String callReport(final boolean errorsOnly) {
    return (String) contextFactory.call(new ContextAction() {

        // TODO: This would probably benefit from injecting an API to manage JSLint.
        public Object run(Context cx) {
            Function fn = null;
            Object value = null;
            StringBuilder sb = new StringBuilder();
            // Look up JSLINT.data.
            value = lintFunc.get("data", lintFunc);
            if (value == UniqueTag.NOT_FOUND) {
                return "";
            }
            fn = (Function) value;
            // Call JSLINT.data().  This returns a JS data structure that we need below.
            Object data = fn.call(cx, lintFunc, null, Context.emptyArgs);
            // Look up JSLINT.error_report.
            value = lintFunc.get("error_report", lintFunc);
            // Shouldn't happen ordinarily, but some of my tests don't have it.
            if (value != UniqueTag.NOT_FOUND) {
                fn = (Function) value;
                // Call JSLint.report().
                sb.append(fn.call(cx, lintFunc, null, new Object[] { data }));
            }
            if (!errorsOnly) {
                // Look up JSLINT.report.
                value = lintFunc.get("report", lintFunc);
                // Shouldn't happen ordinarily, but some of my tests don't have it.
                if (value != UniqueTag.NOT_FOUND) {
                    fn = (Function) value;
                    // Call JSLint.report().
                    sb.append(fn.call(cx, lintFunc, null, new Object[] { data }));
                }
            }
            return sb.toString();
        }
    });
}
Also used : Context(org.mozilla.javascript.Context) Function(org.mozilla.javascript.Function) ContextAction(org.mozilla.javascript.ContextAction) ScriptableObject(org.mozilla.javascript.ScriptableObject)

Example 74 with Context

use of org.mozilla.javascript.Context in project jslint4java by happygiraffe.

the class JSLint method buildResults.

/**
 * Assemble the {@link JSLintResult} object.
 */
@NeedsContext
private JSLintResult buildResults(final String systemId, final long startNanos, final long endNanos) {
    return (JSLintResult) contextFactory.call(new ContextAction() {

        public Object run(Context cx) {
            ResultBuilder b = new JSLintResult.ResultBuilder(systemId);
            b.duration(TimeUnit.NANOSECONDS.toMillis(endNanos - startNanos));
            for (Issue issue : readErrors(systemId)) {
                b.addIssue(issue);
            }
            // Collect a report on what we've just linted.
            b.report(callReport(false));
            // Extract JSLINT.data() output and set it on the result.
            Object o = lintFunc.get("data", lintFunc);
            // Real JSLINT will always have this, but some of my test stubs don't.
            if (o != UniqueTag.NOT_FOUND) {
                Function reportFunc = (Function) o;
                Scriptable data = (Scriptable) reportFunc.call(cx, lintFunc, null, Context.emptyArgs);
                for (String global : Util.listValueOfType("global", String.class, data)) {
                    b.addGlobal(global);
                }
                b.json(Util.booleanValue("json", data));
                for (JSFunction f : Util.listValue("functions", data, new JSFunctionConverter())) {
                    b.addFunction(f);
                }
            }
            // Extract the list of properties. Note that we don't expose the counts, as it
            // doesn't seem that useful.
            Object properties = lintFunc.get("property", lintFunc);
            if (properties != UniqueTag.NOT_FOUND) {
                for (Object id : ScriptableObject.getPropertyIds((Scriptable) properties)) {
                    b.addProperty(id.toString());
                }
            }
            return b.build();
        }
    });
}
Also used : Context(org.mozilla.javascript.Context) ResultBuilder(com.googlecode.jslint4java.JSLintResult.ResultBuilder) Function(org.mozilla.javascript.Function) ContextAction(org.mozilla.javascript.ContextAction) ScriptableObject(org.mozilla.javascript.ScriptableObject) Scriptable(org.mozilla.javascript.Scriptable)

Example 75 with Context

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

the class ContinuationsApiTest method testSerializationWithContinuations.

public void testSerializationWithContinuations() throws IOException, ClassNotFoundException {
    Context cx = Context.enter();
    try {
        // must use interpreter mode
        cx.setOptimizationLevel(-1);
        cx.evaluateString(globalScope, "function f(a) { var k = myObject.f(a); var t = []; return k; }", "function test source", 1, null);
        Function f = (Function) globalScope.get("f", globalScope);
        Object[] args = { 7 };
        cx.callFunctionWithContinuations(f, globalScope, args);
        fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {
        // serialize
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ScriptableOutputStream sos = new ScriptableOutputStream(baos, globalScope);
        sos.writeObject(globalScope);
        sos.writeObject(pending.getContinuation());
        sos.close();
        baos.close();
        byte[] serializedData = baos.toByteArray();
        // deserialize
        ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
        ScriptableInputStream sis = new ScriptableInputStream(bais, globalScope);
        globalScope = (Scriptable) sis.readObject();
        Object continuation = sis.readObject();
        sis.close();
        bais.close();
        Object result = cx.resumeContinuation(continuation, globalScope, 8);
        assertEquals(8, ((Number) result).intValue());
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) Function(org.mozilla.javascript.Function) ContinuationPending(org.mozilla.javascript.ContinuationPending) ScriptableInputStream(org.mozilla.javascript.serialize.ScriptableInputStream) ScriptableOutputStream(org.mozilla.javascript.serialize.ScriptableOutputStream) Scriptable(org.mozilla.javascript.Scriptable)

Aggregations

Context (org.mozilla.javascript.Context)152 Scriptable (org.mozilla.javascript.Scriptable)68 ScriptableObject (org.mozilla.javascript.ScriptableObject)62 ContextAction (org.mozilla.javascript.ContextAction)23 ContextFactory (org.mozilla.javascript.ContextFactory)22 Script (org.mozilla.javascript.Script)17 IOException (java.io.IOException)14 Function (org.mozilla.javascript.Function)13 ScriptContext (javax.script.ScriptContext)10 Test (org.junit.Test)8 RhinoException (org.mozilla.javascript.RhinoException)8 ArrayList (java.util.ArrayList)7 ContinuationPending (org.mozilla.javascript.ContinuationPending)7 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)7 InputStreamReader (java.io.InputStreamReader)6 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)6 JavaScriptException (org.mozilla.javascript.JavaScriptException)6 Date (java.util.Date)5 HashSet (java.util.HashSet)5 List (java.util.List)5