Search in sources :

Example 21 with Window

use of com.gargoylesoftware.htmlunit.javascript.host.Window in project htmlunit by HtmlUnit.

the class WebClient method getPage.

/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Send a request to a server and return a Page that represents the
 * response from the server. This page will be used to populate the provided window.
 * <p>
 * The returned {@link Page} will be created by the {@link PageCreator}
 * configured by {@link #setPageCreator(PageCreator)}, if any.
 * <p>
 * The {@link DefaultPageCreator} will create a {@link Page} depending on the content type of the HTTP response,
 * basically {@link HtmlPage} for HTML content, {@link com.gargoylesoftware.htmlunit.xml.XmlPage} for XML content,
 * {@link TextPage} for other text content and {@link UnexpectedPage} for anything else.
 *
 * @param webWindow the WebWindow to load the result of the request into
 * @param webRequest the web request
 * @param addToHistory true if the page should be part of the history
 * @param <P> the page type
 * @return the page returned by the server when the specified request was made in the specified window
 * @throws IOException if an IO error occurs
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true
 *
 * @see WebRequest
 */
@SuppressWarnings("unchecked")
<P extends Page> P getPage(final WebWindow webWindow, final WebRequest webRequest, final boolean addToHistory) throws IOException, FailingHttpStatusCodeException {
    final Page page = webWindow.getEnclosedPage();
    if (page != null) {
        final URL prev = page.getUrl();
        final URL current = webRequest.getUrl();
        if (UrlUtils.sameFile(current, prev) && current.getRef() != null && !StringUtils.equals(current.getRef(), prev.getRef())) {
            // We're just navigating to an anchor within the current page.
            page.getWebResponse().getWebRequest().setUrl(current);
            if (addToHistory) {
                webWindow.getHistory().addPage(page);
            }
            // the target pseudo style
            if (page instanceof HtmlPage) {
                ((HtmlPage) page).clearComputedStyles();
            }
            final Window window = webWindow.getScriptableObject();
            if (window != null) {
                // js enabled
                window.getLocation().setHash(current.getRef());
            }
            return (P) page;
        }
        if (page.isHtmlPage()) {
            final HtmlPage htmlPage = (HtmlPage) page;
            if (!htmlPage.isOnbeforeunloadAccepted()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("The registered OnbeforeunloadHandler rejected to load a new page.");
                }
                return (P) page;
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Get page for window named '" + webWindow.getName() + "', using " + webRequest);
    }
    WebResponse webResponse;
    final String protocol = webRequest.getUrl().getProtocol();
    if ("javascript".equals(protocol)) {
        webResponse = makeWebResponseForJavaScriptUrl(webWindow, webRequest.getUrl(), webRequest.getCharset());
        if (webWindow.getEnclosedPage() != null && webWindow.getEnclosedPage().getWebResponse() == webResponse) {
            // a javascript:... url with result of type undefined didn't changed the page
            return (P) webWindow.getEnclosedPage();
        }
    } else {
        try {
            webResponse = loadWebResponse(webRequest);
        } catch (final NoHttpResponseException e) {
            webResponse = new WebResponse(RESPONSE_DATA_NO_HTTP_RESPONSE, webRequest, 0);
        }
    }
    printContentIfNecessary(webResponse);
    loadWebResponseInto(webResponse, webWindow);
    // e.g. if the server returns a 404 error page that includes javascript
    if (scriptEngine_ != null) {
        scriptEngine_.registerWindowAndMaybeStartEventLoop(webWindow);
    }
    // check and report problems if needed
    throwFailingHttpStatusCodeExceptionIfNecessary(webResponse);
    return (P) webWindow.getEnclosedPage();
}
Also used : Window(com.gargoylesoftware.htmlunit.javascript.host.Window) FrameWindow(com.gargoylesoftware.htmlunit.html.FrameWindow) NoHttpResponseException(org.apache.http.NoHttpResponseException) XHtmlPage(com.gargoylesoftware.htmlunit.html.XHtmlPage) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) XHtmlPage(com.gargoylesoftware.htmlunit.html.XHtmlPage) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) URL(java.net.URL)

Example 22 with Window

use of com.gargoylesoftware.htmlunit.javascript.host.Window in project htmlunit by HtmlUnit.

the class XMLHTTPRequest method getResponseXML.

/**
 * Returns the parsed response entity body.
 * @return the parsed response entity body
 */
@JsxGetter
public Object getResponseXML() {
    if (state_ == STATE_UNSENT) {
        throw Context.reportRuntimeError("Unspecified error (request not opened).");
    }
    final Window w = getWindow();
    if (state_ == STATE_DONE && webResponse_ != null && !(webResponse_ instanceof NetworkErrorWebResponse)) {
        final String contentType = webResponse_.getContentType();
        if (contentType.contains("xml")) {
            try {
                final XmlPage page = new XmlPage(webResponse_, w.getWebWindow(), true, false);
                final XMLDOMDocument doc = new XMLDOMDocument();
                doc.setDomNode(page);
                doc.setPrototype(getPrototype(doc.getClass()));
                doc.setEnvironment(getEnvironment());
                doc.setParentScope(w);
                return doc;
            } catch (final IOException e) {
                if (LOG.isWarnEnabled()) {
                    LOG.warn("Failed parsing XML document " + webResponse_.getWebRequest().getUrl() + ": " + e.getMessage());
                }
                return null;
            }
        }
    }
    final XMLDOMDocument doc = new XMLDOMDocument(w.getWebWindow());
    doc.setPrototype(getPrototype(doc.getClass()));
    doc.setEnvironment(getEnvironment());
    return doc;
}
Also used : Window(com.gargoylesoftware.htmlunit.javascript.host.Window) XmlPage(com.gargoylesoftware.htmlunit.xml.XmlPage) IOException(java.io.IOException) JsxGetter(com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter)

Example 23 with Window

use of com.gargoylesoftware.htmlunit.javascript.host.Window in project htmlunit by HtmlUnit.

the class XMLHttpRequest method getResponseXML.

/**
 * Returns a DOM-compatible document object version of the data retrieved from the server.
 * @return a DOM-compatible document object version of the data retrieved from the server
 */
@JsxGetter
public Object getResponseXML() {
    if (webResponse_ == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("XMLHttpRequest.responseXML returns null because there " + "in no web resonse so far (has send() been called?)");
        }
        return null;
    }
    if (webResponse_ instanceof NetworkErrorWebResponse) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("XMLHttpRequest.responseXML returns of a network error (" + ((NetworkErrorWebResponse) webResponse_).getError() + ")");
        }
        return null;
    }
    final String contentType = webResponse_.getContentType();
    if (contentType.isEmpty() || contentType.contains("xml")) {
        final Window w = getWindow();
        try {
            final XmlPage page = new XmlPage(webResponse_, w.getWebWindow());
            final XMLDocument document = new XMLDocument();
            document.setPrototype(getPrototype(document.getClass()));
            document.setParentScope(w);
            document.setDomNode(page);
            return document;
        } catch (final IOException e) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Failed parsing XML document " + webResponse_.getWebRequest().getUrl() + ": " + e.getMessage());
            }
            return null;
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("XMLHttpRequest.responseXML was called but the response is " + webResponse_.getContentType());
    }
    return null;
}
Also used : WebWindow(com.gargoylesoftware.htmlunit.WebWindow) Window(com.gargoylesoftware.htmlunit.javascript.host.Window) XmlPage(com.gargoylesoftware.htmlunit.xml.XmlPage) IOException(java.io.IOException) JsxGetter(com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter)

Example 24 with Window

use of com.gargoylesoftware.htmlunit.javascript.host.Window in project htmlunit by HtmlUnit.

the class XMLHttpRequest method send.

/**
 * 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;
    }
    if (!async_ && timeout_ > 0) {
        Context.throwAsScriptRuntimeEx(new RuntimeException("Synchronous requests must not set a timeout."));
        return;
    }
    prepareRequestContent(content);
    if (timeout_ > 0) {
        webRequest_.setTimeout(timeout_);
    }
    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();
    } else {
        // Create and start a thread in which to execute the request.
        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(w);
                try {
                    doSend();
                } 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);
        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)
            fireJavascriptEvent(Event.TYPE_READY_STATE_CHANGE);
        }
        if (!getBrowserVersion().hasFeature(XHR_LOAD_START_ASYNC)) {
            fireJavascriptEvent(Event.TYPE_LOAD_START);
        }
    }
}
Also used : WebWindow(com.gargoylesoftware.htmlunit.WebWindow) Window(com.gargoylesoftware.htmlunit.javascript.host.Window) Context(net.sourceforge.htmlunit.corejs.javascript.Context) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) WebClient(com.gargoylesoftware.htmlunit.WebClient) Deque(java.util.Deque) ArrayDeque(java.util.ArrayDeque) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) ContextAction(net.sourceforge.htmlunit.corejs.javascript.ContextAction) JavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob) AjaxController(com.gargoylesoftware.htmlunit.AjaxController) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 25 with Window

use of com.gargoylesoftware.htmlunit.javascript.host.Window in project htmlunit by HtmlUnit.

the class AppletContextImpl method showStatus.

/**
 * {@inheritDoc}
 */
@Override
public void showStatus(final String status) {
    // perhaps should we move status handling to WebWindow
    // on the other side this allows "orphaned" pages to be usable
    final Window window = htmlPage_.getEnclosingWindow().getScriptableObject();
    window.setStatus(status);
}
Also used : Window(com.gargoylesoftware.htmlunit.javascript.host.Window)

Aggregations

Window (com.gargoylesoftware.htmlunit.javascript.host.Window)33 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)13 WebWindow (com.gargoylesoftware.htmlunit.WebWindow)10 ScriptableObject (net.sourceforge.htmlunit.corejs.javascript.ScriptableObject)9 Scriptable (net.sourceforge.htmlunit.corejs.javascript.Scriptable)7 JavaScriptEngine (com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)6 JsxFunction (com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)6 WebClient (com.gargoylesoftware.htmlunit.WebClient)5 FrameWindow (com.gargoylesoftware.htmlunit.html.FrameWindow)5 JsxGetter (com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter)5 HTMLDocument (com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument)5 IOException (java.io.IOException)5 PostponedAction (com.gargoylesoftware.htmlunit.javascript.PostponedAction)4 DomNode (com.gargoylesoftware.htmlunit.html.DomNode)3 HtmlElement (com.gargoylesoftware.htmlunit.html.HtmlElement)3 XHtmlPage (com.gargoylesoftware.htmlunit.html.XHtmlPage)3 JsxConstructor (com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor)3 XmlPage (com.gargoylesoftware.htmlunit.xml.XmlPage)3 AjaxController (com.gargoylesoftware.htmlunit.AjaxController)2 BrowserVersion (com.gargoylesoftware.htmlunit.BrowserVersion)2