net.sourceforge.htmlunit.corejs.javascript.ContextAction Java Examples

The following examples show how to use net.sourceforge.htmlunit.corejs.javascript.ContextAction. 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: JavaScriptEngine.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Performs initialization for the given webWindow.
 * @param webWindow the web window to initialize for
 */
@Override
public void initialize(final WebWindow webWindow) {
    WebAssert.notNull("webWindow", webWindow);

    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            try {
                init(webWindow, cx);
            }
            catch (final Exception e) {
                LOG.error("Exception while initializing JavaScript for the page", e);
                throw new ScriptException(null, e); // BUG: null is not useful.
            }

            return null;
        }
    };

    getContextFactory().call(action);
}
 
Example #2
Source File: NodeList.java    From htmlunit 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, FF, FF68, FF60})
public void forEach(final Object callback) {
    final List<DomNode> nodes = getElements();

    final WebClient client = getWindow().getWebWindow().getWebClient();
    final HtmlUnitContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();

    final ContextAction<Object> contextAction = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            final Function function = (Function) callback;
            final Scriptable scope = getParentScope();
            for (int i = 0; i < nodes.size(); i++) {
                function.call(cx, scope, NodeList.this, new Object[] {
                        nodes.get(i).getScriptableObject(), i, NodeList.this});
            }
            return null;
        }
    };
    cf.call(contextAction);
}
 
Example #3
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
void messagePosted(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "",
                                owningWindow_, Undefined.instance);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction<Object> action = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            executeEvent(cx, event);
            return null;
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "messagePosted: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #4
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
void messagePosted(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "", owningWindow_, null);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            return executeEvent(cx, event);
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "messagePosted: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #5
Source File: DownloadBehaviorJob.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the download and calls the callback method.
 */
@Override
public void run() {
    final Scriptable scope = callback_.getParentScope();
    final WebRequest request = new WebRequest(url_);
    try {
        final WebResponse webResponse = client_.loadWebResponse(request);
        final String content = webResponse.getContentAsString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Downloaded content: " + StringUtils.abbreviate(content, 512));
        }
        final Object[] args = new Object[] {content};
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                callback_.call(cx, scope, scope, args);
                return null;
            }
        };
        final ContextFactory cf = ((JavaScriptEngine) client_.getJavaScriptEngine()).getContextFactory();
        cf.call(action);
    }
    catch (final IOException e) {
        LOG.error("Behavior #default#download: Cannot download " + url_, e);
    }
}
 
Example #6
Source File: DomElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Fires the event on the element. Nothing is done if JavaScript is disabled.
 * @param event the event to fire
 * @return the execution result, or {@code null} if nothing is executed
 */
public ScriptResult fireEvent(final Event event) {
    final WebClient client = getPage().getWebClient();
    if (!client.getOptions().isJavaScriptEnabled()) {
        return null;
    }

    if (!handles(event)) {
        return null;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Firing " + event);
    }
    final EventTarget jsElt = (EventTarget) getScriptableObject();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            return jsElt.fireEvent(event);
        }
    };

    final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final ScriptResult result = (ScriptResult) cf.call(action);
    if (event.isAborted(result)) {
        preventDefault();
    }
    return result;
}
 
Example #7
Source File: HtmlUnitContextFactory.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link ContextFactory}{@link #call(ContextAction)} but with handling
 * of some exceptions.
 *
 * @param <T> return type of the action
 * @param action the contextAction
 * @param page the page
 * @return the result of the call
 */
public final <T> T callSecured(final ContextAction<T> action, final HtmlPage page) {
    try {
        return call(action);
    }
    catch (final StackOverflowError e) {
        webClient_.getJavaScriptErrorListener().scriptException(page, new ScriptException(page, e));
        return null;
    }
}
 
Example #8
Source File: PopStateEvent.java    From htmlunit with Apache License 2.0 5 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();

        final WebClient client = getWindow().getWebWindow().getWebClient();
        final HtmlUnitContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();

        final ContextAction<Object> contextAction = new ContextAction<Object>() {
            @Override
            public Object run(final Context cx) {
                for (final Object o : ScriptableObject.getPropertyIds(old)) {
                    final String property = Context.toString(o);
                    newState.defineProperty(property, ScriptableObject.getProperty(old, property),
                            ScriptableObject.EMPTY);
                }
                return null;
            }
        };
        cf.call(contextAction);
        state_ = newState;
    }
    else {
        state_ = state;
    }
}
 
Example #9
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message to the {@link Worker} in the page's context.
 * @param message the message
 */
@JsxFunction
public void postMessage(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "",
                                owningWindow_, Undefined.instance);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    if (LOG.isDebugEnabled()) {
        LOG.debug("[DedicatedWorker] postMessage: {}" + message);
    }
    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction<Object> action = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            worker_.getEventListenersContainer().executeCapturingListeners(event, null);
            final Object[] args = {event};
            worker_.getEventListenersContainer().executeBubblingListeners(event, args);
            return null;
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "postMessage: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #10
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
void loadAndExecute(final WebClient webClient, final String url,
        final Context context, final boolean checkMimeType) throws IOException {
    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    final URL fullUrl = page.getFullyQualifiedUrl(url);

    final WebRequest webRequest = new WebRequest(fullUrl);
    final WebResponse response = webClient.loadWebResponse(webRequest);
    if (checkMimeType && !MimeType.isJavascriptMimeType(response.getContentType())) {
        throw Context.reportRuntimeError(
                "NetworkError: importScripts response is not a javascript response");
    }

    final String scriptCode = response.getContentAsString();
    final JavaScriptEngine javaScriptEngine = (JavaScriptEngine) webClient.getJavaScriptEngine();

    final DedicatedWorkerGlobalScope thisScope = this;
    final ContextAction<Object> action = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            final Script script = javaScriptEngine.compile(page, thisScope, scriptCode,
                    fullUrl.toExternalForm(), 1);
            return javaScriptEngine.execute(page, thisScope, script);
        }
    };

    final ContextFactory cf = javaScriptEngine.getContextFactory();

    if (context != null) {
        action.run(context);
    }
    else {
        final JavaScriptJob job = new WorkerJob(cf, action, "loadAndExecute " + url);

        owningWindow_.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example #11
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
void loadAndExecute(final String url, final Context context) throws IOException {
    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    final URL fullUrl = page.getFullyQualifiedUrl(url);

    final WebClient webClient = owningWindow_.getWebWindow().getWebClient();

    final WebRequest webRequest = new WebRequest(fullUrl);
    final WebResponse response = webClient.loadWebResponse(webRequest);
    final String scriptCode = response.getContentAsString();
    final JavaScriptEngine javaScriptEngine = (JavaScriptEngine) webClient.getJavaScriptEngine();

    final DedicatedWorkerGlobalScope thisScope = this;
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            final Script script = javaScriptEngine.compile(page, thisScope, scriptCode,
                    fullUrl.toExternalForm(), 1);
            return javaScriptEngine.execute(page, thisScope, script);
        }
    };

    final ContextFactory cf = javaScriptEngine.getContextFactory();

    if (context != null) {
        action.run(context);
    }
    else {
        final JavaScriptJob job = new WorkerJob(cf, action, "loadAndExecute " + url);

        owningWindow_.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example #12
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message to the {@link Worker} in the page's context.
 * @param message the message
 */
@JsxFunction
public void postMessage(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "", owningWindow_, null);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    if (LOG.isDebugEnabled()) {
        LOG.debug("[DedicatedWorker] postMessage: {}" + message);
    }
    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            worker_.getEventListenersContainer().executeCapturingListeners(event, null);
            final Object[] args = new Object[] {event};
            return worker_.getEventListenersContainer().executeBubblingListeners(event, args, args);
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "postMessage: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #13
Source File: MessagePort.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message.
 * @param message the object passed to the window
 * @param transfer an optional sequence of Transferable objects
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage">MDN documentation</a>
 */
@JsxFunction
public void postMessage(final String message, final Object transfer) {
    if (port1_ != null) {
        final Window w = getWindow();
        final URL currentURL = w.getWebWindow().getEnclosedPage().getUrl();
        final MessageEvent event = new MessageEvent();
        final String origin = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();
        event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin, "", w, transfer);
        event.setParentScope(port1_);
        event.setPrototype(getPrototype(event.getClass()));

        final JavaScriptEngine jsEngine
            = (JavaScriptEngine) w.getWebWindow().getWebClient().getJavaScriptEngine();
        final PostponedAction action = new PostponedAction(w.getWebWindow().getEnclosedPage()) {
            @Override
            public void execute() throws Exception {
                final ContextAction contextAction = new ContextAction() {
                    @Override
                    public Object run(final Context cx) {
                        return port1_.dispatchEvent(event);
                    }
                };

                final ContextFactory cf = jsEngine.getContextFactory();
                cf.call(contextAction);
            }
        };
        jsEngine.addPostponedAction(action);
    }
}
 
Example #14
Source File: WebSocket.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private void fire(final Event evt) {
    evt.setTarget(this);
    evt.setParentScope(getParentScope());
    evt.setPrototype(getPrototype(evt.getClass()));

    final JavaScriptEngine engine
        = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();
    engine.getContextFactory().call(new ContextAction() {
        @Override
        public ScriptResult run(final Context cx) {
            return executeEventLocally(evt);
        }
    });
}
 
Example #15
Source File: JavascriptXMLHttpRequestJob.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
JavascriptXMLHttpRequestJob(final ContextFactory contextFactory, final ContextAction action) {
    super();
    contextFactory_ = contextFactory;
    action_ = action;
}
 
Example #16
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
WorkerJob(final ContextFactory contextFactory, final ContextAction action, final String description) {
    contextFactory_ = contextFactory;
    action_ = action;
    description_ = description;
}
 
Example #17
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 #18
Source File: JavascriptXMLHttpRequestJob.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
JavascriptXMLHttpRequestJob(final ContextFactory contextFactory, final ContextAction<Object> action) {
    super();
    contextFactory_ = contextFactory;
    action_ = action;
}
 
Example #19
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 #20
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
WorkerJob(final ContextFactory contextFactory, final ContextAction<Object> action, final String description) {
    contextFactory_ = contextFactory;
    action_ = action;
    description_ = description;
}
 
Example #21
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 #22
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);
    }
}
 
Example #23
Source File: BackgroundJavaScriptFactory.java    From HtmlUnit-Android with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new job for XMLHttpRequestProcessing.
 * @param contextFactory the ContextFactory
 * @param action the action
 *
 * @return JavaScriptJob the created job
 */
public JavaScriptJob createJavascriptXMLHttpRequestJob(final ContextFactory contextFactory,
        final ContextAction action) {
    return new JavascriptXMLHttpRequestJob(contextFactory, action);
}
 
Example #24
Source File: BackgroundJavaScriptFactory.java    From htmlunit with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new job for XMLHttpRequestProcessing.
 * @param contextFactory the ContextFactory
 * @param action the action
 *
 * @return JavaScriptJob the created job
 */
public JavaScriptJob createJavascriptXMLHttpRequestJob(final ContextFactory contextFactory,
        final ContextAction<Object> action) {
    return new JavascriptXMLHttpRequestJob(contextFactory, action);
}