com.gargoylesoftware.htmlunit.WebResponse Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.WebResponse. 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: HtmlUnitNekoDOMBuilder.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Parses and then inserts the specified HTML content into the HTML content currently being parsed.
 * @param html the HTML content to push
 */
@Override
public void pushInputString(final String html) {
    page_.registerParsingStart();
    page_.registerInlineSnippetParsingStart();
    try {
        final WebResponse webResponse = page_.getWebResponse();
        final Charset charset = webResponse.getContentCharset();
        final String url = webResponse.getWebRequest().getUrl().toString();
        final XMLInputSource in = new XMLInputSource(null, url, null, new StringReader(html), charset.name());
        ((HTMLConfiguration) fConfiguration).evaluateInputSource(in);
    }
    finally {
        page_.registerParsingEnd();
        page_.registerInlineSnippetParsingEnd();
    }
}
 
Example #2
Source File: RepositoryServletNoProxyTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoProxyVersionedMetadataDefaultLayout()
    throws Exception
{
    String commonsLangMetadata = "commons-lang/commons-lang/2.1/maven-metadata.xml";
    String expectedMetadataContents = "dummy-versioned-metadata";

    Path metadataFile = repoRootInternal.resolve(commonsLangMetadata);
    Files.createDirectories(metadataFile.getParent());

    org.apache.archiva.common.utils.FileUtils.writeStringToFile( metadataFile, Charset.defaultCharset(), expectedMetadataContents );

    //WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" + commonsLangMetadata );
    WebResponse response = getWebResponse( "/repository/internal/" + commonsLangMetadata );
    assertResponseOK( response );

    assertEquals( "Expected file contents", expectedMetadataContents, response.getContentAsString() );
}
 
Example #3
Source File: HTMLParserTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception failure
 */
@Test
public void tableWithoutColgroup() throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html><head>\n"
        + "</head>\n"
        + "<body>\n"
        + "  <table><col width='7'/><col width='1'/><tbody><tr><td>seven</td><td>One</td></tr></tbody></table>\n"
        + "</body></html>";

    final WebClient webClient = getWebClient();
    final WebResponse webResponse = new StringWebResponse(html, URL_FIRST);

    final XHtmlPage page = webClient.getPageCreator().getHtmlParser()
                                .parseXHtml(webResponse, webClient.getCurrentWindow());

    final DomElement col = page.getElementsByTagName("col").get(0);
    assertEquals(col.getParentNode().getNodeName(), HtmlTableColumnGroup.TAG_NAME);
}
 
Example #4
Source File: MockWebResponseBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void buildResponseHeaders() throws Exception {
	this.response.addHeader("Content-Type", "text/html");
	this.response.addHeader("X-Test", "value");
	Cookie cookie = new Cookie("cookieA", "valueA");
	cookie.setDomain("domain");
	cookie.setPath("/path");
	cookie.setMaxAge(1800);
	cookie.setSecure(true);
	cookie.setHttpOnly(true);
	this.response.addCookie(cookie);
	WebResponse webResponse = this.responseBuilder.build();

	List<NameValuePair> responseHeaders = webResponse.getResponseHeaders();
	assertThat(responseHeaders.size(), equalTo(3));
	NameValuePair header = responseHeaders.get(0);
	assertThat(header.getName(), equalTo("Content-Type"));
	assertThat(header.getValue(), equalTo("text/html"));
	header = responseHeaders.get(1);
	assertThat(header.getName(), equalTo("X-Test"));
	assertThat(header.getValue(), equalTo("value"));
	header = responseHeaders.get(2);
	assertThat(header.getName(), equalTo("Set-Cookie"));
	assertThat(header.getValue(), startsWith("cookieA=valueA; Path=/path; Domain=domain; Max-Age=1800; Expires="));
	assertThat(header.getValue(), endsWith("; Secure; HttpOnly"));
}
 
Example #5
Source File: RepositoryServletNoProxyTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoProxySnapshotArtifactDefaultLayout()
    throws Exception
{
    String commonsLangJar = "commons-lang/commons-lang/2.1-SNAPSHOT/commons-lang-2.1-SNAPSHOT.jar";
    String expectedArtifactContents = "dummy-commons-lang-snapshot-artifact";

    Path artifactFile = repoRootInternal.resolve(commonsLangJar);
    Files.createDirectories(artifactFile.getParent());

    org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);

    //WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" + commonsLangJar );
    WebResponse response = getWebResponse( "/repository/internal/" + commonsLangJar );
    assertResponseOK( response );

    assertEquals( "Expected file contents", expectedArtifactContents, response.getContentAsString() );
}
 
Example #6
Source File: RepositoryServletNoProxyTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoProxySnapshotArtifactLegacyLayoutManagedLegacy()
    throws Exception
{
    String commonsLangJar = "commons-lang/jars/commons-lang-2.1-SNAPSHOT.jar";
    String expectedArtifactContents = "dummy-commons-lang-snapshot-artifact";

    Path artifactFile = repoRootLegacy.resolve(commonsLangJar);
    Files.createDirectories(artifactFile.getParent());

    org.apache.archiva.common.utils.FileUtils.writeStringToFile(artifactFile, Charset.defaultCharset(), expectedArtifactContents);

    WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/legacy/" + commonsLangJar );
    WebResponse response = getServletUnitClient().getResponse( request );
    assertResponseNotFound( response );
}
 
Example #7
Source File: XMLHttpRequest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private boolean isPreflightAuthorized(final WebResponse preflightResponse) {
    final String originHeader = preflightResponse.getResponseHeaderValue(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN);
    if (!ALLOW_ORIGIN_ALL.equals(originHeader)
            && !webRequest_.getAdditionalHeaders().get(HttpHeader.ORIGIN).equals(originHeader)) {
        return false;
    }
    String headersHeader = preflightResponse.getResponseHeaderValue(HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS);
    if (headersHeader == null) {
        headersHeader = "";
    }
    else {
        headersHeader = headersHeader.toLowerCase(Locale.ROOT);
    }
    for (final Entry<String, String> header : webRequest_.getAdditionalHeaders().entrySet()) {
        final String key = header.getKey().toLowerCase(Locale.ROOT);
        if (isPreflightHeader(key, header.getValue())
                && !headersHeader.contains(key)) {
            return false;
        }
    }
    return true;
}
 
Example #8
Source File: XMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Loads an XML document from the specified location.
 *
 * @param xmlSource a string containing a URL that specifies the location of the XML file
 * @return true if the load succeeded; false if the load failed
 */
@JsxFunction({FF68, FF60})
public boolean load(final String xmlSource) {
    if (async_) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("XMLDocument.load(): 'async' is true, currently treated as false.");
        }
    }
    try {
        final WebWindow ww = getWindow().getWebWindow();
        final HtmlPage htmlPage = (HtmlPage) ww.getEnclosedPage();
        final WebRequest request = new WebRequest(htmlPage.getFullyQualifiedUrl(xmlSource));
        final WebResponse webResponse = ww.getWebClient().loadWebResponse(request);
        final XmlPage page = new XmlPage(webResponse, ww, false);
        setDomNode(page);
        return true;
    }
    catch (final IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error parsing XML from '" + xmlSource + "'", e);
        }
        return false;
    }
}
 
Example #9
Source File: HtmlEmbed.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Saves this content as the specified file.
 * @param file the file to save to
 * @throws IOException if an IO error occurs
 */
public void saveAs(final File file) throws IOException {
    final HtmlPage page = (HtmlPage) getPage();
    final WebClient webclient = page.getWebClient();

    final URL url = page.getFullyQualifiedUrl(getAttributeDirect(SRC_ATTRIBUTE));
    final WebRequest request = new WebRequest(url);
    request.setCharset(page.getCharset());
    request.setAdditionalHeader(HttpHeader.REFERER, page.getUrl().toExternalForm());
    final WebResponse webResponse = webclient.loadWebResponse(request);

    try (OutputStream fos = Files.newOutputStream(file.toPath());
            InputStream content =  webResponse.getContentAsStream()) {
        IOUtils.copy(content, fos);
    }
}
 
Example #10
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testSwagger() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/services/rs/swagger.json";

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    final UnexpectedPage swaggerPage = webClient.getPage(url);
    WebResponse response = swaggerPage.getWebResponse();
    Assert.assertEquals("application/json", response.getContentType());
    String json = response.getContentAsString();
    Assert.assertTrue(json.contains("Claims"));

    webClient.close();
}
 
Example #11
Source File: HtmlLink.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * If the linked content is not already downloaded it triggers a download. Then it stores the response
 * for later use.<br>
 *
 * @param downloadIfNeeded indicates if a request should be performed this hasn't been done previously
 * @param request the request; if null getWebRequest() is called to create one
 * @return {@code null} if no download should be performed and when this wasn't already done; the response
 * received when performing a request for the content referenced by this tag otherwise
 * @throws IOException if an error occurs while downloading the content
 */
public WebResponse getWebResponse(final boolean downloadIfNeeded, WebRequest request) throws IOException {
    if (downloadIfNeeded && cachedWebResponse_ == null) {
        final WebClient webclient = getPage().getWebClient();
        if (null == request) {
            request = getWebRequest();
        }
        try {
            cachedWebResponse_ = webclient.loadWebResponse(request);
            final int statusCode = cachedWebResponse_.getStatusCode();
            final boolean successful = statusCode >= HttpStatus.SC_OK
                                            && statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
            if (successful) {
                executeEvent(Event.TYPE_LOAD);
            }
            else {
                executeEvent(Event.TYPE_ERROR);
            }
        }
        catch (final IOException e) {
            executeEvent(Event.TYPE_ERROR);
            throw e;
        }
    }
    return cachedWebResponse_;
}
 
Example #12
Source File: RepositoryServletNoProxyTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoProxyProjectMetadataDefaultLayout()
    throws Exception
{
    String commonsLangMetadata = "commons-lang/commons-lang/maven-metadata.xml";
    String expectedMetadataContents = "dummy-project-metadata";

    Path metadataFile = repoRootInternal.resolve(commonsLangMetadata);
    Files.createDirectories(metadataFile.getParent());

    org.apache.archiva.common.utils.FileUtils.writeStringToFile( metadataFile, Charset.defaultCharset(), expectedMetadataContents );

    //WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" + commonsLangMetadata );
    WebResponse response = getWebResponse( "/repository/internal/" + commonsLangMetadata );
    assertResponseOK( response );

    assertEquals( "Expected file contents", expectedMetadataContents, response.getContentAsString() );
}
 
Example #13
Source File: RepositoryServletNoProxyTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoProxyDistributionLegacyLayoutManagedLegacy()
    throws Exception
{
    String expectedContents = "the-contents-of-the-dual-extension";
    String dualExtensionPath = "org.project/distributions/example-presentation-3.2.zip";

    Path checksumFile = repoRootLegacy.resolve(dualExtensionPath);
    Files.createDirectories(checksumFile.getParent());

    org.apache.archiva.common.utils.FileUtils.writeStringToFile(checksumFile, Charset.defaultCharset(), expectedContents);

    WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/legacy/" + dualExtensionPath );
    WebResponse response = getServletUnitClient().getResponse( request );
    assertResponseNotFound( response );
}
 
Example #14
Source File: RepositoryServletNoProxyTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoProxyProjectMetadataDefaultLayoutManagedLegacy()
    throws Exception
{
    // TODO: find out what it is meant to be from maven-artifact
    String commonsLangMetadata = "commons-lang/commons-lang/maven-metadata.xml";
    String expectedMetadataContents = "dummy-project-metadata";

    Path metadataFile = repoRootLegacy.resolve(commonsLangMetadata);
    Files.createDirectories(metadataFile.getParent());

    org.apache.archiva.common.utils.FileUtils.writeStringToFile(metadataFile, Charset.defaultCharset(), expectedMetadataContents);

    WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/legacy/" + commonsLangMetadata );
    WebResponse response = getServletUnitClient().getResponse( request );
    assertResponseNotFound( response );
}
 
Example #15
Source File: RepositoryServletBrowseTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testBrowse()
    throws Exception
{
    WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" );
    WebResponse response = getServletUnitClient().getResponse( request );
    assertEquals( "Response", HttpServletResponse.SC_OK, response.getStatusCode() );

    // dumpResponse( response );

    List<String> expectedLinks = Arrays.asList( ".indexer/", "commons-lang/", "net/", "org/" );

    Document document = Jsoup.parse( response.getContentAsString() );
    Elements elements = document.getElementsByTag( "a" );

    assertLinks( expectedLinks, elements );
}
 
Example #16
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 #17
Source File: Attachment.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the attachment's filename, as suggested by the <tt>Content-Disposition</tt>
 * header, or {@code null} if no filename was suggested.
 * @return the attachment's suggested filename, or {@code null} if none was suggested
 */
public String getSuggestedFilename() {
    final WebResponse response = page_.getWebResponse();
    final String disp = response.getResponseHeaderValue(HttpHeader.CONTENT_DISPOSITION);
    int start = disp.indexOf("filename=");
    if (start == -1) {
        return null;
    }
    start += "filename=".length();
    if (start >= disp.length()) {
        return null;
    }

    int end = disp.indexOf(';', start);
    if (end == -1) {
        end = disp.length();
    }
    if (disp.charAt(start) == '"' && disp.charAt(end - 1) == '"') {
        start++;
        end--;
    }
    return disp.substring(start, end);
}
 
Example #18
Source File: RepositoryServletRepositoryGroupTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFromLastManagedRepositoryReturnOk()
    throws Exception
{
    String resourceName = "dummy/dummy-last-resource/1.0/dummy-last-resource-1.0.txt";

    Path dummyReleasesResourceFile = repoRootLast.resolve( resourceName );
    Files.createDirectories(dummyReleasesResourceFile.getParent());
    org.apache.archiva.common.utils.FileUtils.writeStringToFile(dummyReleasesResourceFile, Charset.defaultCharset(), "last");

    WebRequest request = new GetMethodWebRequest(
        "http://machine.com/repository/" + REPO_GROUP_WITH_VALID_REPOS + "/" + resourceName );
    WebResponse response = getServletUnitClient().getResponse( request );

    assertResponseOK( response );

    assertThat( response.getContentAsString() ).isEqualTo( "last" );
}
 
Example #19
Source File: DebuggingWebConnection.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Calls the wrapped webconnection and save the received response.
 * {@inheritDoc}
 */
@Override
public WebResponse getResponse(final WebRequest request) throws IOException {
    WebResponse response = wrappedWebConnection_.getResponse(request);
    if (isUncompressJavaScript() && isJavaScript(response.getContentType())) {
        response = uncompressJavaScript(response);
    }
    saveResponse(response, request);
    return response;
}
 
Example #20
Source File: CodeFlowTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdTokenInjectionJwtMethod() throws IOException, InterruptedException {
    try (final WebClient webClient = createWebClient()) {
        webClient.getOptions().setRedirectEnabled(false);
        WebResponse webResponse = webClient
                .loadWebResponse(
                        new WebRequest(URI.create("http://localhost:8081/web-app/callback-jwt-before-redirect").toURL()));
        assertNotNull(getStateCookie(webClient, "tenant-jwt"));
        assertNotNull(getStateCookieStateParam(webClient, "tenant-jwt"));
        assertNull(getStateCookieSavedPath(webClient, "tenant-jwt"));

        HtmlPage page = webClient.getPage(webResponse.getResponseHeaderValue("location"));
        assertEquals("Log in to quarkus", page.getTitleText());
        HtmlForm loginForm = page.getForms().get(0);
        loginForm.getInputByName("username").setValueAttribute("alice");
        loginForm.getInputByName("password").setValueAttribute("alice");

        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webResponse = loginForm.getInputByName("login").click().getWebResponse();
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(true);

        // This is a redirect from the OIDC server to the endpoint
        URI endpointLocationUri = URI.create(webResponse.getResponseHeaderValue("location"));
        assertNotNull(endpointLocationUri.getRawQuery());
        webResponse = webClient.loadWebResponse(new WebRequest(endpointLocationUri.toURL()));

        // This is a redirect from quarkus-oidc which drops the query parameters
        URI endpointLocationUri2 = URI.create(webResponse.getResponseHeaderValue("location"));
        assertNull(endpointLocationUri2.getRawQuery());

        page = webClient.getPage(endpointLocationUri2.toString());
        assertEquals("callback-jwt:alice", page.getBody().asText());
        webClient.getCookieManager().clearCookies();
    }
}
 
Example #21
Source File: WebResponseWrapper.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a WebResponse object wrapping provided WebResponse.
 * @param webResponse the webResponse that does the real work
 * @throws IllegalArgumentException if the webResponse is {@code null}
 */
public WebResponseWrapper(final WebResponse webResponse) throws IllegalArgumentException {
    super(null, null, 0);
    if (webResponse == null) {
        throw new IllegalArgumentException("Wrapped WebResponse can't be null");
    }
    wrappedWebResponse_ = webResponse;
}
 
Example #22
Source File: ProducesIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void otherProduces1() throws Exception {
    final WebResponse wr = webClient.loadWebResponse(
            new WebRequest(new URL(webUrl + "resources/other_produces1"), ACCEPT_HEADER));
    assertEquals(Response.Status.OK.getStatusCode(), wr.getStatusCode());
    assertEquals(MediaType.APPLICATION_XHTML_XML, wr.getContentType());
}
 
Example #23
Source File: ProducesIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleProduces2() throws Exception {
    final WebResponse wr = webClient.loadWebResponse(
            new WebRequest(new URL(webUrl + "resources/multiple_produces2"), ACCEPT_HEADER));
    assertEquals(Response.Status.OK.getStatusCode(), wr.getStatusCode());
    assertEquals(MediaType.APPLICATION_XHTML_XML, wr.getContentType());
}
 
Example #24
Source File: Document.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the {@code referrer} property.
 * @return the value of the {@code referrer} property
 */
@JsxGetter
public String getReferrer() {
    String referrer = "";
    final WebResponse webResponse = getPage().getWebResponse();
    if (webResponse != null) {
        referrer = webResponse.getWebRequest().getAdditionalHeaders().get(HttpHeader.REFERER);
        if (referrer == null) {
            referrer = "";
        }
    }
    return referrer;
}
 
Example #25
Source File: FalsifyingWebConnection.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Delivers the content for an alternate URL as if it comes from the requested URL.
 * @param webRequest the original web request
 * @param url the URL from which the content should be retrieved
 * @return the response
 * @throws IOException if a problem occurred
 */
protected WebResponse deliverFromAlternateUrl(final WebRequest webRequest, final URL url)
    throws IOException {
    final URL originalUrl = webRequest.getUrl();
    webRequest.setUrl(url);
    final WebResponse resp = super.getResponse(webRequest);
    resp.getWebRequest().setUrl(originalUrl);
    return resp;
}
 
Example #26
Source File: FalsifyingWebConnection.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a WebResponse with new content, preserving all other information.
 * @param wr the web response to adapt
 * @param newContent the new content to place in the response
 * @return a web response with the new content
 * @throws IOException if an encoding problem occurred
 */
protected WebResponse replaceContent(final WebResponse wr, final String newContent) throws IOException {
    final byte[] body = newContent.getBytes(wr.getContentCharset());
    final WebResponseData wrd = new WebResponseData(body, wr.getStatusCode(), wr.getStatusMessage(),
        wr.getResponseHeaders());
    return new WebResponse(wrd, wr.getWebRequest().getUrl(), wr.getWebRequest().getHttpMethod(),
            wr.getLoadTime());
}
 
Example #27
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 #28
Source File: DOMImplementation.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an {@link HTMLDocument}.
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createHTMLDocument">
 *   createHTMLDocument (MDN)</a>
 *
 * @param titleObj the document title
 * @return the newly created {@link HTMLDocument}
 */
@JsxFunction
public HTMLDocument createHTMLDocument(final Object titleObj) {
    if (titleObj == Undefined.instance
            && getBrowserVersion().hasFeature(JS_DOMIMPLEMENTATION_CREATE_HTMLDOCOMENT_REQUIRES_TITLE)) {
        throw Context.reportRuntimeError("Title is required");
    }

    final HTMLDocument document = new HTMLDocument();
    document.setParentScope(getParentScope());
    document.setPrototype(getPrototype(document.getClass()));

    // According to spec and behavior of function in browsers new document
    // has no location object and is not connected with any window
    final WebResponse resp = new StringWebResponse("", WebClient.URL_ABOUT_BLANK);
    final HtmlPage page = new HtmlPage(resp, getWindow().getWebWindow());
    page.setEnclosingWindow(null);
    document.setDomNode(page);

    final HTMLHtmlElement html = (HTMLHtmlElement) document.createElement("html");
    page.appendChild(html.getDomNodeOrDie());

    final HTMLHeadElement head = (HTMLHeadElement) document.createElement("head");
    html.appendChild(head);

    if (titleObj != Undefined.instance) {
        final HTMLTitleElement title = (HTMLTitleElement) document.createElement("title");
        head.appendChild(title);
        title.setTextContent(Context.toString(titleObj));
    }

    final HTMLBodyElement body = (HTMLBodyElement) document.createElement("body");
    html.appendChild(body);

    return document;
}
 
Example #29
Source File: WebClientUtils.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Attaches a visual (GUI) debugger to the specified client.
 * @param client the client to which the visual debugger is to be attached
 * @see <a href="http://www.mozilla.org/rhino/debugger.html">Mozilla Rhino Debugger Documentation</a>
 */
public static void attachVisualDebugger(final WebClient client) {
    final ScopeProvider sp = null;
    final HtmlUnitContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final Main main = Main.mainEmbedded(cf, sp, "HtmlUnit JavaScript Debugger");
    main.getDebugFrame().setExtendedState(Frame.MAXIMIZED_BOTH);

    final SourceProvider sourceProvider = new SourceProvider() {
        @Override
        public String getSource(final DebuggableScript script) {
            String sourceName = script.getSourceName();
            if (sourceName.endsWith("(eval)") || sourceName.endsWith("(Function)")) {
                return null; // script is result of eval call. Rhino already knows the source and we don't
            }
            if (sourceName.startsWith("script in ")) {
                sourceName = StringUtils.substringBetween(sourceName, "script in ", " from");
                for (final WebWindow ww : client.getWebWindows()) {
                    final WebResponse wr = ww.getEnclosedPage().getWebResponse();
                    if (sourceName.equals(wr.getWebRequest().getUrl().toString())) {
                        return wr.getContentAsString();
                    }
                }
            }
            return null;
        }
    };
    main.setSourceProvider(sourceProvider);
}
 
Example #30
Source File: AttachmentHandler.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@code true} if the specified response represents an attachment.
 * @param response the response to check
 * @return {@code true} if the specified response represents an attachment, {@code false} otherwise
 * @see <a href="http://www.ietf.org/rfc/rfc2183.txt">RFC 2183</a>
 */
default boolean isAttachment(final WebResponse response) {
    final String disp = response.getResponseHeaderValue(HttpHeader.CONTENT_DISPOSITION);
    if (disp == null) {
        return false;
    }
    return disp.toLowerCase(Locale.ROOT).startsWith("attachment");
}