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

The following examples show how to use net.sourceforge.htmlunit.corejs.javascript.Context#getThreadLocal() . 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: MouseEvent.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the mouse event currently firing, or {@code null} if no mouse event is being processed.
 * @return the mouse event currently firing
 */
@SuppressWarnings("unchecked")
public static MouseEvent getCurrentMouseEvent() {
    final Context context = Context.getCurrentContext();
    if (context != null) {
        final LinkedList<Event> events = (LinkedList<Event>) context.getThreadLocal(KEY_CURRENT_EVENT);
        if (events != null && !events.isEmpty() && events.getLast() instanceof MouseEvent) {
            return (MouseEvent) events.getLast();
        }
    }
    return null;
}
 
Example 2
Source File: Event.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Called when the event starts being fired.
 */
@SuppressWarnings("unchecked")
public void startFire() {
    final Context context = Context.getCurrentContext();
    LinkedList<Event> events = (LinkedList<Event>) context.getThreadLocal(KEY_CURRENT_EVENT);
    if (events == null) {
        events = new LinkedList<>();
        context.putThreadLocal(KEY_CURRENT_EVENT, events);
    }
    events.add(this);
}
 
Example 3
Source File: DebugFrameImpl.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of this frame's source.
 *
 * @return the name of this frame's source
 */
private static String getSourceName(final Context cx) {
    String source = (String) cx.getThreadLocal(KEY_LAST_SOURCE);
    if (source == null) {
        return "unknown";
    }
    // only the file name is interesting the rest of the url is mostly noise
    source = StringUtils.substringAfterLast(source, "/");
    // embedded scripts have something like "foo.html from (3, 10) to (10, 13)"
    source = StringUtils.substringBefore(source, " ");
    return source;
}
 
Example 4
Source File: DebugFrameImpl.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the line number of the first line in this frame's function or script, or <tt>???</tt>
 * if it cannot be determined. This is necessary because the line numbers provided by Rhino are unordered.
 *
 * @return the line number of the first line in this frame's function or script, or <tt>???</tt>
 *         if it cannot be determined
 */
private static String getFirstLine(final Context cx) {
    final Object line = cx.getThreadLocal(KEY_LAST_LINE);
    final String result;
    if (line == null) {
        result = "??";
    }
    else {
        result = String.valueOf(line);
    }
    return StringUtils.leftPad(result, 5);
}
 
Example 5
Source File: MouseEvent.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the mouse event currently firing, or {@code null} if no mouse event is being processed.
 * @return the mouse event currently firing
 */
@SuppressWarnings("unchecked")
public static MouseEvent getCurrentMouseEvent() {
    final Context context = Context.getCurrentContext();
    if (context != null) {
        final LinkedList<Event> events = (LinkedList<Event>) context.getThreadLocal(KEY_CURRENT_EVENT);
        if (events != null && !events.isEmpty() && events.getLast() instanceof MouseEvent) {
            return (MouseEvent) events.getLast();
        }
    }
    return null;
}
 
Example 6
Source File: Event.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Called when the event starts being fired.
 */
@SuppressWarnings("unchecked")
public void startFire() {
    final Context context = Context.getCurrentContext();
    LinkedList<Event> events = (LinkedList<Event>) context.getThreadLocal(KEY_CURRENT_EVENT);
    if (events == null) {
        events = new LinkedList<>();
        context.putThreadLocal(KEY_CURRENT_EVENT, events);
    }
    events.add(this);
}
 
Example 7
Source File: DebugFrameImpl.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of this frame's source.
 *
 * @return the name of this frame's source
 */
private static String getSourceName(final Context cx) {
    String source = (String) cx.getThreadLocal(KEY_LAST_SOURCE);
    if (source == null) {
        return "unknown";
    }
    // only the file name is interesting the rest of the url is mostly noise
    source = StringUtils.substringAfterLast(source, "/");
    // embedded scripts have something like "foo.html from (3, 10) to (10, 13)"
    source = StringUtils.substringBefore(source, " ");
    return source;
}
 
Example 8
Source File: DebugFrameImpl.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the line number of the first line in this frame's function or script, or <tt>???</tt>
 * if it cannot be determined. This is necessary because the line numbers provided by Rhino are unordered.
 *
 * @return the line number of the first line in this frame's function or script, or <tt>???</tt>
 *         if it cannot be determined
 */
private static String getFirstLine(final Context cx) {
    final Object line = cx.getThreadLocal(KEY_LAST_LINE);
    final String result;
    if (line == null) {
        result = "??";
    }
    else {
        result = String.valueOf(line);
    }
    return StringUtils.leftPad(result, 5);
}
 
Example 9
Source File: XMLHttpRequest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the specified content to the server in an HTTP request and receives the response.
 * @param content the body of the message being sent with the request
 */
@JsxFunction
public void send(final Object content) {
    if (webRequest_ == null) {
        return;
    }
    prepareRequest(content);

    final Window w = getWindow();
    final WebWindow ww = w.getWebWindow();
    final WebClient client = ww.getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) ww.getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        if (getBrowserVersion().hasFeature(XHR_FIRE_STATE_OPENED_AGAIN_IN_ASYNC_MODE)) {
            // quite strange but IE seems to fire state loading twice
            // in async mode (at least with HTML of the unit tests)
            setState(OPENED, Context.getCurrentContext());
        }

        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction<Object> action = new ContextAction<Object>() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Deque<Scriptable> stack =
                        (Deque<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new ArrayDeque<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }

            @Override
            public String toString() {
                return "XMLHttpRequest " + webRequest_.getHttpMethod() + " '" + webRequest_.getUrl() + "'";
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHttpRequest thread for asynchronous request");
        }
        jobID_ = ww.getJobManager().addJob(job, page);
    }
}
 
Example 10
Source File: XMLHTTPRequest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Sends an HTTP request to the server and receives a response.
 * @param body the body of the message being sent with the request.
 */
@JsxFunction
public void send(final Object body) {
    if (webRequest_ == null) {
        setState(STATE_DONE, Context.getCurrentContext());
        return;
    }
    if (sent_) {
        throw Context.reportRuntimeError("Unspecified error (request already sent).");
    }
    sent_ = true;

    prepareRequest(body);

    // quite strange but IE seems to fire state loading twice
    setState(STATE_OPENED, Context.getCurrentContext());

    final Window w = getWindow();
    final WebClient client = w.getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) w.getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction<Object> action = new ContextAction<Object>() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Deque<Scriptable> stack =
                        (Deque<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new ArrayDeque<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHTTPRequest thread for asynchronous request");
        }
        jobID_ = w.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example 11
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;
}
 
Example 12
Source File: XMLHttpRequest.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the specified content to the server in an HTTP request and receives the response.
 * @param content the body of the message being sent with the request
 */
@JsxFunction
public void send(final Object content) {
    if (webRequest_ == null) {
        return;
    }
    prepareRequest(content);

    final Window w = getWindow();
    final WebClient client = w.getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) w.getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        if (getBrowserVersion().hasFeature(XHR_FIRE_STATE_OPENED_AGAIN_IN_ASYNC_MODE)) {
            // quite strange but IE seems to fire state loading twice
            // in async mode (at least with HTML of the unit tests)
            setState(OPENED, Context.getCurrentContext());
        }

        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Stack<Scriptable> stack =
                        (Stack<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new Stack<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }

            @Override
            public String toString() {
                return "XMLHttpRequest " + webRequest_.getHttpMethod() + " '" + webRequest_.getUrl() + "'";
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHttpRequest thread for asynchronous request");
        }
        jobID_ = w.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example 13
Source File: XMLHTTPRequest.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Sends an HTTP request to the server and receives a response.
 * @param body the body of the message being sent with the request.
 */
@JsxFunction
public void send(final Object body) {
    if (webRequest_ == null) {
        setState(STATE_DONE, Context.getCurrentContext());
        return;
    }
    if (sent_) {
        throw Context.reportRuntimeError("Unspecified error (request already sent).");
    }
    sent_ = true;

    prepareRequest(body);

    // quite strange but IE seems to fire state loading twice
    setState(STATE_OPENED, Context.getCurrentContext());

    final Window w = getWindow();
    final WebClient client = w.getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) w.getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Stack<Scriptable> stack =
                        (Stack<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new Stack<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHTTPRequest thread for asynchronous request");
        }
        jobID_ = w.getWebWindow().getJobManager().addJob(job, page);
    }
}