Java Code Examples for net.sourceforge.htmlunit.corejs.javascript.Context#enter()

The following examples show how to use net.sourceforge.htmlunit.corejs.javascript.Context#enter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NodeList.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Calls the {@code callback} given in parameter once for each value pair in the list, in insertion order.
 * @param callback function to execute for each element
 */
@JsxFunction({CHROME, FF52})
public void forEach(final Object callback) {
    final List<DomNode> nodes = getElements();
    final Context context = Context.enter();
    try {
        final Function function = (Function) callback;
        final Scriptable scope = getParentScope();
        for (int i = 0; i < nodes.size(); i++) {
            function.call(context, scope, this, new Object[] {
                    nodes.get(i).getScriptableObject(), i, this});
        }
    }
    finally {
        Context.exit();
    }
}
 
Example 2
Source File: PopStateEvent.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new event instance.
 *
 * @param target the event target
 * @param type the event type
 * @param state the state object
 */
public PopStateEvent(final EventTarget target, final String type, final Object state) {
    super(target, type);
    if (state instanceof NativeObject && getBrowserVersion().hasFeature(JS_POP_STATE_EVENT_CLONE_STATE)) {
        final NativeObject old = (NativeObject) state;
        final NativeObject newState = new NativeObject();
        Context.enter();
        try {
            for (final Object o : ScriptableObject.getPropertyIds(old)) {
                final String property = Context.toString(o);
                newState.defineProperty(property, ScriptableObject.getProperty(old, property),
                        ScriptableObject.EMPTY);
            }
        }
        finally {
            Context.exit();
        }
        state_ = newState;
    }
    else {
        state_ = state;
    }
}
 
Example 3
Source File: ProxyAutoConfig.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the <tt>FindProxyForURL</tt> method of the specified content.
 * @param content the JavaScript content
 * @param url the URL to be retrieved
 * @return semicolon-separated result
 */
public static String evaluate(final String content, final URL url) {
    final Context cx = Context.enter();
    try {
        final ProxyAutoConfig config = new ProxyAutoConfig();
        final Scriptable scope = cx.initSafeStandardObjects();

        config.defineMethod("isPlainHostName", scope);
        config.defineMethod("dnsDomainIs", scope);
        config.defineMethod("localHostOrDomainIs", scope);
        config.defineMethod("isResolvable", scope);
        config.defineMethod("isInNet", scope);
        config.defineMethod("dnsResolve", scope);
        config.defineMethod("myIpAddress", scope);
        config.defineMethod("dnsDomainLevels", scope);
        config.defineMethod("shExpMatch", scope);
        config.defineMethod("weekdayRange", scope);
        config.defineMethod("dateRange", scope);
        config.defineMethod("timeRange", scope);

        cx.evaluateString(scope, "var ProxyConfig = function() {}; ProxyConfig.bindings = {}", "<init>", 1, null);
        cx.evaluateString(scope, content, "<Proxy Auto-Config>", 1, null);
        final Object[] functionArgs = {url.toExternalForm(), url.getHost()};
        final Object fObj = scope.get("FindProxyForURL", scope);

        final NativeFunction f = (NativeFunction) fObj;
        final Object result = f.call(cx, scope, scope, functionArgs);
        return Context.toString(result);
    }
    finally {
        Context.exit();
    }
}
 
Example 4
Source File: ProxyAutoConfig.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the <tt>FindProxyForURL</tt> method of the specified content.
 * @param content the JavaScript content
 * @param url the URL to be retrieved
 * @return semicolon-separated result
 */
public static String evaluate(final String content, final URL url) {
    final Context cx = Context.enter();
    try {
        final ProxyAutoConfig config = new ProxyAutoConfig();
        final Scriptable scope = cx.initStandardObjects();

        config.defineMethod("isPlainHostName", scope);
        config.defineMethod("dnsDomainIs", scope);
        config.defineMethod("localHostOrDomainIs", scope);
        config.defineMethod("isResolvable", scope);
        config.defineMethod("isInNet", scope);
        config.defineMethod("dnsResolve", scope);
        config.defineMethod("myIpAddress", scope);
        config.defineMethod("dnsDomainLevels", scope);
        config.defineMethod("shExpMatch", scope);
        config.defineMethod("weekdayRange", scope);
        config.defineMethod("dateRange", scope);
        config.defineMethod("timeRange", scope);

        cx.evaluateString(scope, "var ProxyConfig = function() {}; ProxyConfig.bindings = {}", "<init>", 1, null);
        cx.evaluateString(scope, content, "<Proxy Auto-Config>", 1, null);
        final Object[] functionArgs = {url.toExternalForm(), url.getHost()};
        final Object fObj = scope.get("FindProxyForURL", scope);

        final NativeFunction f = (NativeFunction) fObj;
        final Object result = f.call(cx, scope, scope, functionArgs);
        return Context.toString(result);
    }
    finally {
        Context.exit();
    }
}
 
Example 5
Source File: Promise.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * It takes two arguments, both are callback functions for the success and failure cases of the Promise.
 *
 * @param onFulfilled success function
 * @param onRejected failure function
 * @return {@link Promise}
 */
@JsxFunction
public Promise then(final Object onFulfilled, final Object onRejected) {
    final Window window = getWindow();
    final Promise returnPromise = new Promise(window);

    final Promise thisPromise = this;

    final BasicJavaScriptJob job = new BasicJavaScriptJob() {

        @Override
        public void run() {
            final Context cx = Context.enter();
            try {
                Function toExecute = null;
                if (thisPromise.state_ == PromiseState.FULFILLED && onFulfilled instanceof Function) {
                    toExecute = (Function) onFulfilled;
                }
                else if (thisPromise.state_ == PromiseState.REJECTED && onRejected instanceof Function) {
                    toExecute = (Function) onRejected;
                }

                try {
                    final Object callbackResult;
                    if (toExecute == null) {
                        final Promise dummy = new Promise();
                        dummy.state_ = thisPromise.state_;
                        dummy.value_ = thisPromise.value_;
                        callbackResult = dummy;
                    }
                    else {
                        // KEY_STARTING_SCOPE maintains a stack of scopes
                        @SuppressWarnings("unchecked")
                        Stack<Scriptable> stack = (Stack<Scriptable>) cx.getThreadLocal(KEY_STARTING_SCOPE);
                        if (null == stack) {
                            stack = new Stack<>();
                            cx.putThreadLocal(KEY_STARTING_SCOPE, stack);
                        }
                        stack.push(window);
                        try {
                            callbackResult = toExecute.call(cx, window, thisPromise, new Object[] {value_});
                        }
                        finally {
                            stack.pop();
                        }

                        window.getWebWindow().getWebClient().getJavaScriptEngine().processPostponedActions();
                    }
                    if (callbackResult instanceof Promise) {
                        final Promise resultPromise = (Promise) callbackResult;
                        if (resultPromise.state_ == PromiseState.FULFILLED) {
                            returnPromise.settle(true, resultPromise.value_, window);
                        }
                        else if (resultPromise.state_ == PromiseState.REJECTED) {
                            returnPromise.settle(false, resultPromise.value_, window);
                        }
                        else {
                            if (resultPromise.dependentPromises_ == null) {
                                resultPromise.dependentPromises_ = new ArrayList<Promise>(2);
                            }
                            resultPromise.dependentPromises_.add(returnPromise);
                        }
                    }
                    else {
                        returnPromise.settle(true, callbackResult, window);
                    }
                }
                catch (final JavaScriptException e) {
                    returnPromise.settle(false, e.getValue(), window);
                }
            }
            finally {
                Context.exit();
            }
        }

        /** {@inheritDoc} */
        @Override
        public String toString() {
            return super.toString() + " Promise.then";
        }
    };

    if (state_ == PromiseState.FULFILLED || state_ == PromiseState.REJECTED) {
        window.getWebWindow().getJobManager().addJob(job, window.getDocument().getPage());
    }
    else {
        if (settledJobs_ == null) {
            settledJobs_ = new ArrayList<BasicJavaScriptJob>(2);
        }
        settledJobs_.add(job);
    }

    return returnPromise;
}