com.gargoylesoftware.htmlunit.WebClient Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.WebClient. 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: Window.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a modal dialog box that displays the specified HTML document.
 * @param url the URL of the document to load and display
 * @param arguments object to be made available via <tt>window.dialogArguments</tt> in the dialog window
 * @param features string that specifies the window ornaments for the dialog window
 * @return the value of the {@code returnValue} property as set by the modal dialog's window
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536759.aspx">MSDN Documentation</a>
 * @see <a href="https://developer.mozilla.org/en/DOM/window.showModalDialog">Mozilla Documentation</a>
 */
@JsxFunction({IE, FF})
public Object showModalDialog(final String url, final Object arguments, final String features) {
    final WebWindow webWindow = getWebWindow();
    final WebClient client = webWindow.getWebClient();
    try {
        final URL completeUrl = ((HtmlPage) getDomNodeOrDie()).getFullyQualifiedUrl(url);
        final DialogWindow dialog = client.openDialogWindow(completeUrl, webWindow, arguments);
        // TODO: Theoretically, we shouldn't return until the dialog window has been close()'ed...
        // But we have to return so that the window can be close()'ed...
        // Maybe we can use Rhino's continuation support to save state and restart when
        // the dialog window is close()'ed? Would only work in interpreted mode, though.
        final ScriptableObject jsDialog = dialog.getScriptableObject();
        return jsDialog.get("returnValue", jsDialog);
    }
    catch (final IOException e) {
        throw Context.throwAsScriptRuntimeEx(e);
    }
}
 
Example #2
Source File: HtmlFileInput2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void testFileInput(final File file) throws Exception {
    final String firstContent = "<html><head></head><body>\n"
        + "<form enctype='multipart/form-data' action='" + URL_SECOND + "' method='POST'>\n"
        + "  <input type='file' name='image'>\n"
        + "  <input type='submit' id='clickMe'>\n"
        + "</form>\n"
        + "</body>\n"
        + "</html>";
    final String secondContent = "<html><head><title>second</title></head></html>";
    final WebClient client = getWebClient();

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);

    client.setWebConnection(webConnection);

    final HtmlPage firstPage = client.getPage(URL_FIRST);
    final HtmlForm f = firstPage.getForms().get(0);
    final HtmlFileInput fileInput = f.getInputByName("image");
    fileInput.setFiles(file);
    firstPage.getHtmlElementById("clickMe").click();
    final KeyDataPair pair = (KeyDataPair) webConnection.getLastParameters().get(0);
    assertNotNull(pair.getFile());
    assertTrue(pair.getFile().length() != 0);
}
 
Example #3
Source File: BearerTokenAuthorizationTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testReAuthenticateWhenSwitchingTenants() throws IOException {
    try (final WebClient webClient = createWebClient()) {
        // tenant-web-app
        HtmlPage page = webClient.getPage("http://localhost:8081/tenant/tenant-web-app/api/user");
        assertNull(getStateCookieSavedPath(webClient, "tenant-web-app"));
        assertEquals("Log in to quarkus-webapp", page.getTitleText());
        HtmlForm loginForm = page.getForms().get(0);
        loginForm.getInputByName("username").setValueAttribute("alice");
        loginForm.getInputByName("password").setValueAttribute("alice");
        page = loginForm.getInputByName("login").click();
        assertEquals("tenant-web-app:alice", page.getBody().asText());
        // tenant-web-app2
        page = webClient.getPage("http://localhost:8081/tenant/tenant-web-app2/api/user");
        assertNull(getStateCookieSavedPath(webClient, "tenant-web-app2"));
        assertEquals("Log in to quarkus-webapp2", page.getTitleText());
        loginForm = page.getForms().get(0);
        loginForm.getInputByName("username").setValueAttribute("alice");
        loginForm.getInputByName("password").setValueAttribute("alice");
        page = loginForm.getInputByName("login").click();
        assertEquals("tenant-web-app2:alice", page.getBody().asText());

        webClient.getCookieManager().clearCookies();
    }
}
 
Example #4
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 #5
Source File: XMLHttpRequest3Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
private void testMethod(final HttpMethod method) throws Exception {
    final String content = "<html><head><script>\n"
        + "function test() {\n"
        + "  var req = new XMLHttpRequest();\n"
        + "  req.open('" + method.name().toLowerCase(Locale.ROOT) + "', 'foo.xml', false);\n"
        + "  req.send('');\n"
        + "}\n"
        + "</script></head>\n"
        + "<body onload='test()'></body></html>";

    final WebClient client = getWebClient();
    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, content);
    final URL urlPage2 = new URL(URL_FIRST, "foo.xml");
    conn.setResponse(urlPage2, "<foo/>\n", MimeType.TEXT_XML);
    client.setWebConnection(conn);
    client.getPage(URL_FIRST);

    final WebRequest request = conn.getLastWebRequest();
    assertEquals(urlPage2, request.getUrl());
    assertSame(method, request.getHttpMethod());
}
 
Example #6
Source File: DelegatingWebConnectionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyExampleInClassLevelJavadoc() throws Exception {
	Assume.group(TestGroup.PERFORMANCE);

	WebClient webClient = new WebClient();

	MockMvc mockMvc = MockMvcBuilders.standaloneSetup(TestController.class).build();
	MockMvcWebConnection mockConnection = new MockMvcWebConnection(mockMvc);
	mockConnection.setWebClient(webClient);

	WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
	WebConnection httpConnection = new HttpWebConnection(webClient);
	WebConnection webConnection = new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection));

	webClient.setWebConnection(webConnection);

	Page page = webClient.getPage("http://code.jquery.com/jquery-1.11.0.min.js");
	assertThat(page.getWebResponse().getStatusCode(), equalTo(200));
	assertThat(page.getWebResponse().getContentAsString(), not(isEmptyString()));
}
 
Example #7
Source File: HtmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void onunLoadHandler() throws Exception {
    final String htmlContent = "<html><head><title>foo</title>\n"
        + "</head><body onunload='alert(\"foo\");alert(\"bar\")'>\n"
        + "</body></html>";

    final String[] expectedAlerts = {"foo", "bar"};
    final List<String> collectedAlerts = new ArrayList<>();
    final WebClient client = getWebClient();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, htmlContent);
    client.setWebConnection(conn);

    client.getPage(URL_FIRST);
    client.getPage(URL_FIRST);

    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example #8
Source File: HtmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test auto-refresh from a meta tag inside noscript.
 * @throws Exception if the test fails
 */
@Test
public void refresh_MetaTagNoScript() throws Exception {
    final String firstContent = "<html><head><title>first</title>\n"
        + "<noscript>\n"
        + "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL=" + URL_SECOND + "\">\n"
        + "</noscript>\n"
        + "</head><body></body></html>";
    final String secondContent = "<html><head><title>second</title></head><body></body></html>";

    final WebClient client = getWebClient();

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);
    client.setWebConnection(webConnection);

    HtmlPage page = client.getPage(URL_FIRST);
    assertEquals("first", page.getTitleText());

    client.getOptions().setJavaScriptEnabled(false);
    page = client.getPage(URL_FIRST);
    assertEquals("second", page.getTitleText());
}
 
Example #9
Source File: HtmlPage2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void save_css_empty_href() throws Exception {
    final String html = "<html><head>\n"
        + "<link rel='stylesheet' type='text/css' href='' /></head></html>";

    final WebClient webClient = getWebClientWithMockWebConnection();
    final MockWebConnection webConnection = getMockWebConnection();

    webConnection.setResponse(URL_FIRST, html);

    final HtmlPage page = webClient.getPage(URL_FIRST);
    final File tmpFolder = tmpFolderProvider_.newFolder("hu");
    final File file = new File(tmpFolder, "hu_HtmlPageTest_save5.html");
    page.save(file);
    assertTrue(file.exists());
    assertTrue(file.isFile());

    final HtmlLink cssLink = page.getFirstByXPath("//link");
    assertEquals(DomElement.ATTRIBUTE_NOT_DEFINED, cssLink.getHrefAttribute());
}
 
Example #10
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 #11
Source File: Window.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private URL makeUrlForOpenWindow(final String urlString) {
    if (urlString.isEmpty()) {
        return WebClient.URL_ABOUT_BLANK;
    }

    try {
        final Page page = getWebWindow().getEnclosedPage();
        if (page != null && page.isHtmlPage()) {
            return ((HtmlPage) page).getFullyQualifiedUrl(urlString);
        }
        return new URL(urlString);
    }
    catch (final MalformedURLException e) {
        if (LOG.isWarnEnabled()) {
            LOG.error("Unable to create URL for openWindow: relativeUrl=[" + urlString + "]", e);
        }
        return null;
    }
}
 
Example #12
Source File: XmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test that UTF-8 is used as default encoding for xml responses
 * (issue 3385410).
 * @throws Exception if the test fails
 */
@Test
public void defaultEncoding() throws Exception {
    final String content
        = "<?xml version=\"1.0\"?>\n"
         + "<foo>\n"
         + "\u0434\n"
         + "</foo>";

    final byte[] bytes = TextUtils.stringToByteArray(content, UTF_8);

    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setDefaultResponse(bytes, 200, "OK", MimeType.TEXT_XML);
    client.setWebConnection(webConnection);

    final Page page = client.getPage(URL_FIRST);
    assertTrue(XmlPage.class.isInstance(page));

    final XmlPage xmlPage = (XmlPage) page;
    assertEquals(content, xmlPage.getWebResponse().getContentAsString());
    assertNotNull(xmlPage.getXmlDocument());

    assertEquals("foo", xmlPage.getXmlDocument().getFirstChild().getNodeName());
}
 
Example #13
Source File: CSSStyleSheet.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the CSS at the specified input source. If anything at all goes wrong, this method
 * returns an empty stylesheet.
 *
 * @param source the source from which to retrieve the CSS to be parsed
 * @param client the client
 * @return the stylesheet parsed from the specified input source
 */
private static CSSStyleSheetImpl parseCSS(final InputSource source, final WebClient client) {
    CSSStyleSheetImpl ss;
    try {
        final CSSErrorHandler errorHandler = client.getCssErrorHandler();
        final CSSOMParser parser = new CSSOMParser(new CSS3Parser());
        parser.setErrorHandler(errorHandler);
        ss = parser.parseStyleSheet(source, null);
    }
    catch (final Throwable t) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error parsing CSS from '" + toString(source) + "': " + t.getMessage(), t);
        }
        ss = new CSSStyleSheetImpl();
    }
    return ss;
}
 
Example #14
Source File: HtmlInlineFrameTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void setSrcAttribute_ViaJavaScript() throws Exception {
    final String firstContent
        = "<html><head><title>First</title></head><body>\n"
        + "<iframe id='iframe1' src='" + URL_SECOND + "'></iframe>\n"
        + "<script type='text/javascript'>document.getElementById('iframe1').src = '" + URL_THIRD + "';\n"
        + "</script></body></html>";
    final String secondContent = "<html><head><title>Second</title></head><body></body></html>";
    final String thirdContent = "<html><head><title>Third</title></head><body></body></html>";
    final WebClient client = getWebClientWithMockWebConnection();

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);
    webConnection.setResponse(URL_THIRD, thirdContent);

    final HtmlPage page = client.getPage(URL_FIRST);
    assertEquals("First", page.getTitleText());

    final HtmlInlineFrame iframe = page.getHtmlElementById("iframe1");
    assertEquals(URL_THIRD.toExternalForm(), iframe.getSrcAttribute());
    assertEquals("Third", ((HtmlPage) iframe.getEnclosedPage()).getTitleText());
}
 
Example #15
Source File: LocationTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("c")
public void locationWithTarget() throws Exception {
    final WebClient client = getWebClient();
    final List<String> alerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(alerts));

    final URL url = getClass().getResource("LocationTest_locationWithTarget_a.html");
    assertNotNull(url);

    final HtmlPage a = client.getPage(url);
    final HtmlPage c = (HtmlPage) a.getFrameByName("c").getEnclosedPage();
    c.getHtmlElementById("anchor").click();
    assertEquals(getExpectedAlerts(), alerts);
}
 
Example #16
Source File: BaseFrameElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void setAttributeNS(final String namespaceURI, final String qualifiedName, String attributeValue,
        final boolean notifyAttributeChangeListeners, final boolean notifyMutationObserver) {
    if (null != attributeValue && SRC_ATTRIBUTE.equals(qualifiedName)) {
        attributeValue = attributeValue.trim();
    }

    super.setAttributeNS(namespaceURI, qualifiedName, attributeValue, notifyAttributeChangeListeners,
            notifyMutationObserver);

    // do not use equals() here
    // see HTMLIFrameElement2Test.documentCreateElement_onLoad_srcAboutBlank()
    if (SRC_ATTRIBUTE.equals(qualifiedName) && WebClient.ABOUT_BLANK != attributeValue) {
        if (isAttachedToPage()) {
            loadSrc();
        }
        else {
            loadSrcWhenAddedToPage_ = true;
        }
    }
}
 
Example #17
Source File: BrowserTabUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private BrowserTabUtil(WebDriver driver) {
    this.driver = driver;

    if (driver instanceof JavascriptExecutor) {
        this.jsExecutor = (JavascriptExecutor) driver;
    } else {
        throw new RuntimeException("WebDriver must be instance of JavascriptExecutor");
    }

    // HtmlUnit doesn't work very well with JS and it's recommended to use this settings.
    // HtmlUnit validates all scripts and then fails. It turned off the validation.
    if (driver instanceof HtmlUnitDriver) {
        WebClient client = ((DroneHtmlUnitDriver) driver).getWebClient();
        client.getOptions().setThrowExceptionOnScriptError(false);
        client.getOptions().setThrowExceptionOnFailingStatusCode(false);
    }

    tabs = new ArrayList<>(driver.getWindowHandles());
}
 
Example #18
Source File: HTMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * JavaScript function "open".
 *
 * See http://www.whatwg.org/specs/web-apps/current-work/multipage/section-dynamic.html for
 * a good description of the semantics of open(), write(), writeln() and close().
 *
 * @param url when a new document is opened, <i>url</i> is a String that specifies a MIME type for the document.
 *        When a new window is opened, <i>url</i> is a String that specifies the URL to render in the new window
 * @param name the name
 * @param features the features
 * @param replace whether to replace in the history list or no
 * @return a reference to the new document object.
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536652.aspx">MSDN documentation</a>
 */
@JsxFunction
public Object open(final Object url, final Object name, final Object features,
        final Object replace) {
    // Any open() invocations are ignored during the parsing stage, because write() and
    // writeln() invocations will directly append content to the current insertion point.
    final HtmlPage page = getPage();
    if (page.isBeingParsed()) {
        LOG.warn("Ignoring call to open() during the parsing stage.");
        return null;
    }

    // We're not in the parsing stage; OK to continue.
    if (!writeInCurrentDocument_) {
        LOG.warn("Function open() called when document is already open.");
    }
    writeInCurrentDocument_ = false;
    final WebWindow ww = getWindow().getWebWindow();
    if (ww instanceof FrameWindow
            && WebClient.ABOUT_BLANK.equals(getPage().getUrl().toExternalForm())) {
        final URL enclosingUrl = ((FrameWindow) ww).getEnclosingPage().getUrl();
        getPage().getWebResponse().getWebRequest().setUrl(enclosingUrl);
    }
    return this;
}
 
Example #19
Source File: XmlSerializerTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void unsupportedProtocolLink() throws Exception {
    final String html = "<html><head>"
            + "<link rel='alternate' href='android-app://somehost'>\n"
            + "</head></html>";

    final WebClient client = getWebClient();
    final MockWebConnection connection = getMockWebConnection();
    connection.setResponse(URL_FIRST, html);
    client.setWebConnection(connection);

    final HtmlPage page = client.getPage(URL_FIRST);

    final File tmpFolder = tmpFolderProvider_.newFolder("hu");
    final File file = new File(tmpFolder, "hu_XmlSerializerTest_unsupportedProtocol.html");
    page.save(file);
    assertTrue(file.exists());
    assertTrue(file.isFile());
}
 
Example #20
Source File: HtmlFrameSetTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void refererHeader() throws Exception {
    final String firstContent
        = "<html><head><title>First</title></head>\n"
        + "<frameset cols='130,*'>\n"
        + "  <frame scrolling='no' name='left' src='" + URL_SECOND + "' frameborder='1' />\n"
        + "  <noframes>\n"
        + "    <body>Frames not supported</body>\n"
        + "  </noframes>\n"
        + "</frameset>\n"
        + "</html>";
    final String secondContent = "<html><head><title>Second</title></head><body></body></html>";

    final WebClient webClient = getWebClientWithMockWebConnection();

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);

    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    assertEquals("First", firstPage.getTitleText());

    final Map<String, String> lastAdditionalHeaders = webConnection.getLastAdditionalHeaders();
    assertEquals(URL_FIRST.toString(), lastAdditionalHeaders.get(HttpHeader.REFERER));
}
 
Example #21
Source File: CSSStyleSheet.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code true} if this stylesheet is active, based on the media types it is associated with (if any).
 * @return {@code true} if this stylesheet is active, based on the media types it is associated with (if any)
 */
public boolean isActive() {
    final String media;
    final HtmlElement e = ownerNode_.getDomNodeOrNull();
    if (e instanceof HtmlStyle) {
        final HtmlStyle style = (HtmlStyle) e;
        media = style.getMediaAttribute();
    }
    else if (e instanceof HtmlLink) {
        final HtmlLink link = (HtmlLink) e;
        media = link.getMediaAttribute();
    }
    else {
        return true;
    }

    if (StringUtils.isBlank(media)) {
        return true;
    }

    final WebClient webClient = getWindow().getWebWindow().getWebClient();
    final MediaList mediaList = parseMedia(webClient.getCssErrorHandler(), media);
    return isActive(this, mediaList);
}
 
Example #22
Source File: HtmlFormTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void submit_javascriptAction() throws Exception {
    final String firstHtml
        = "<html><head><title>First</title></head><body>\n"
        + "<form method='get' action='javascript:alert(\"clicked\")'>\n"
        + "<input name='button' type='submit' value='PushMe' id='button'/></form>\n"
        + "</body></html>";
    final String secondHtml = "<html><head><title>Second</title></head><body></body></html>";

    final WebClient client = getWebClientWithMockWebConnection();
    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(URL_FIRST, firstHtml);
    webConnection.setResponse(URL_SECOND, secondHtml);

    final HtmlPage firstPage = client.getPage(URL_FIRST);
    final HtmlSubmitInput button = firstPage.getHtmlElementById("button");

    assertEquals(Collections.EMPTY_LIST, collectedAlerts);
    final HtmlPage secondPage = button.click();
    assertEquals(firstPage.getTitleText(), secondPage.getTitleText());

    assertEquals(new String[] {"clicked"}, collectedAlerts);
}
 
Example #23
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 #24
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 #25
Source File: WindowTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that <tt>window.open</tt> behaves correctly when popups are blocked.
 * @throws Exception if an error occurs
 */
@Test
public void openWindow_blocked() throws Exception {
    final String html =
        "<html>\n"
        + "<head>\n"
        + "<script>\n"
        + "  var w;\n"
        + "  function test() {\n"
        + "    w = window.open('', 'foo');\n"
        + "  }\n"
        + "</script>\n"
        + "</head>\n"
        + "<body onload='test()'>\n"
        + "<div id='d' onclick='alert(w)'>test</div>\n"
        + "</body></html>";

    final List<String> actual = new ArrayList<>();
    final WebClient client = getWebClient();
    client.getOptions().setPopupBlockerEnabled(true);
    client.setAlertHandler(new CollectingAlertHandler(actual));

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setDefaultResponse(html);
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage("http://foo");
    page.getHtmlElementById("d").click();
    final String[] expected = {"null"};
    assertEquals(expected, actual);
}
 
Example #26
Source File: JavaScriptEngineTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for https://sourceforge.net/tracker/?func=detail&atid=448266&aid=1552746&group_id=47038.
 * @throws Exception if the test fails
 */
@Test
public void externalScriptWithNewLineBeforeClosingScriptTag() throws Exception {
    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    final String htmlContent
        = "<html><head><title>foo</title>\n"
        + "</head><body>\n"
        + "<script src='test.js'>\n</script>\n" // \n between opening and closing tag is important
        + "</body></html>";

    final String jsContent
        = "function externalMethod() {\n"
        + "    alert('Got to external method');\n"
        + "}\n"
        + "externalMethod();\n";

    webConnection.setResponse(URL_FIRST, htmlContent);
    webConnection.setDefaultResponse(jsContent, 200, "OK", "text/javascript");
    client.setWebConnection(webConnection);

    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    client.getPage(URL_FIRST);
    assertEquals(new String[] {"Got to external method"}, collectedAlerts);
}
 
Example #27
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreateClientWithInvalidRegistrationURI() throws Exception {
    // Login to the client page successfully
    try (WebClient webClient = setupWebClientIDP("alice", "ecila")) {
        final HtmlPage registerPage = login(oidcEndpointBuilder("/console/clients/register"), webClient);

        // Now try to register a new client
        HtmlPage errorPage = registerConfidentialClient(registerPage, "asfxyz", "https://127.0.0.1//",
                      "https://cxf.apache.org", "https://localhost:12345");
        assertTrue(errorPage.asText().contains("Invalid Client Registration"));
    }
}
 
Example #28
Source File: HTMLDocument2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"one", "two", "three", "four"})
public void cookie_read() throws Exception {
    final WebClient webClient = getWebClientWithMockWebConnection();

    final String html
        = "<html><head><title>First</title><script>\n"
        + "function doTest() {\n"
        + "  var cookieSet = document.cookie.split('; ');\n"
        + "  var setSize = cookieSet.length;\n"
        + "  var crumbs;\n"
        + "  for (var x = 0; x < setSize; x++) {\n"
        + "    crumbs = cookieSet[x].split('=');\n"
        + "    alert(crumbs[0]);\n"
        + "    alert(crumbs[1]);\n"
        + "  }\n"
        + "}\n"
        + "</script></head><body onload='doTest()'>\n"
        + "</body></html>";

    final URL url = URL_FIRST;
    getMockWebConnection().setResponse(url, html);

    final CookieManager mgr = webClient.getCookieManager();
    mgr.addCookie(new Cookie(url.getHost(), "one", "two", "/", null, false));
    mgr.addCookie(new Cookie(url.getHost(), "three", "four", "/", null, false));

    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final HtmlPage firstPage = webClient.getPage(url);
    assertEquals("First", firstPage.getTitleText());

    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example #29
Source File: JavaScriptEngineTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test for issue #1658.
 * @throws Exception if the test fails
 */
@Test
public void nonStandardBrowserVersion() throws Exception {
    final BrowserVersion browser = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.INTERNET_EXPLORER)
            .setApplicationName("Mozilla")
            .setApplicationVersion("5.0")
            .build();

    try (WebClient client = new WebClient(browser)) {
        client.openWindow(WebClient.URL_ABOUT_BLANK, "TestWindow");
    }
}
 
Example #30
Source File: JadeIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    webClient = new WebClient();
    webClient.getOptions()
        .setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions()
        .setRedirectEnabled(true);
}