com.gargoylesoftware.htmlunit.util.NameValuePair Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.util.NameValuePair. 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: WebClientTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void redirection_AdditionalHeadersMaintained(final int statusCode) throws Exception {
    final WebClient client = getWebClient();
    final MockWebConnection conn = new MockWebConnection();
    client.setWebConnection(conn);

    final List<NameValuePair> headers = asList(new NameValuePair("Location", URL_SECOND.toString()));
    conn.setResponse(URL_FIRST, "", statusCode, "", MimeType.TEXT_HTML, headers);
    conn.setResponse(URL_SECOND, "<html><body>abc</body></html>");

    final WebRequest request = new WebRequest(URL_FIRST);
    request.setAdditionalHeader("foo", "bar");
    client.getPage(request);

    assertEquals(URL_SECOND, conn.getLastWebRequest().getUrl());
    assertEquals("bar", conn.getLastAdditionalHeaders().get("foo"));
}
 
Example #2
Source File: CookieManagerTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * A cookie set with document.cookie without path applies only for the current path
 * and overrides cookie previously set for this path.
 * @throws Exception if the test fails
 */
@Test
@Alerts("first=new")
public void cookieSetFromJSWithoutPathUsesCurrentLocation() throws Exception {
    final List<NameValuePair> responseHeader1 = new ArrayList<>();
    responseHeader1.add(new NameValuePair("Set-Cookie", "first=1"));

    final String html = "<html>\n"
        + "<head></head>\n"
        + "<body><script>\n"
        + "  document.cookie = 'first=new';\n"
        + "  location.replace('/a/b/-');\n"
        + "</script></body>\n"
        + "</html>";

    getMockWebConnection().setDefaultResponse(HTML_ALERT_COOKIE);
    final URL firstUrl = new URL(URL_FIRST, "/a/b");
    getMockWebConnection().setResponse(firstUrl, html, 200, "Ok", MimeType.TEXT_HTML, responseHeader1);

    loadPageWithAlerts2(firstUrl);
}
 
Example #3
Source File: CookieManagerTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("first=1")
public void cookie2() throws Exception {
    final List<NameValuePair> responseHeader1 = new ArrayList<>();
    responseHeader1.add(new NameValuePair("Set-Cookie", "first=1"));
    getMockWebConnection().setResponse(URL_FIRST, HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML,
            responseHeader1);

    loadPageWithAlerts2(URL_FIRST);

    final List<NameValuePair> responseHeader2 = new ArrayList<>();
    responseHeader2.add(new NameValuePair("Set-Cookie", "second=2"));
    getMockWebConnection().setResponse(URL_FIRST, HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML,
            responseHeader2);

    setExpectedAlerts("first=1; second=2");
    loadPageWithAlerts2(URL_FIRST);
}
 
Example #4
Source File: HtmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test auto-refresh from a response header.
 * @throws Exception if the test fails
 */
@Test
public void refresh_HttpResponseHeader() throws Exception {
    final String firstContent = "<html><head><title>first</title>\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, 200, "OK", MimeType.TEXT_HTML, Collections
            .singletonList(new NameValuePair("Refresh", "2;URL=" + URL_SECOND)));
    webConnection.setResponse(URL_SECOND, secondContent);
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);

    assertEquals("second", page.getTitleText());
}
 
Example #5
Source File: WebClient3Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts({"Executed", "later"})
// TODO [IE]ERRORPAGE real IE displays own error page if response is to small
public void execJavascriptOnErrorPages() throws Exception {
    final String errorHtml = "<html>\n"
            + "<head>\n"
            + "</head>\n"
            + "<body>\n"
            + "<script type='text/javascript'>\n"
            + "  alert('Executed');\n"
            + "  setTimeout(\"alert('later')\", 10);\n"
            + "</script>\n"
            + "</body></html>\n";

    final MockWebConnection conn = getMockWebConnection();
    conn.setResponse(URL_FIRST, errorHtml, 404, "Not Found", MimeType.TEXT_HTML, new ArrayList<NameValuePair>());

    loadPageWithAlerts2(URL_FIRST, 42);
}
 
Example #6
Source File: HtmlImage2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void isDisplayed(final String src) throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);
        final URL urlImage = new URL(URL_FIRST, "img.jpg");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);

        getMockWebConnection().setDefaultResponse("Error: not found", 404, "Not Found", MimeType.TEXT_HTML);
    }

    final String html = "<html><head><title>Page A</title></head>\n"
            + "<body>\n"
            + "  <img id='myImg' " + src + " >\n"
            + "</body></html>";

    final WebDriver driver = loadPage2(html);

    final boolean displayed = driver.findElement(By.id("myImg")).isDisplayed();
    assertEquals(Boolean.parseBoolean(getExpectedAlerts()[0]), displayed);
}
 
Example #7
Source File: WebClient6Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Regression test for bug 3035155.
 * Bug was fixes in HttpClient 4.1.
 * @throws Exception if an error occurs
 */
@Test
public void redirect302UrlsInQuery() throws Exception {
    final String html = "<html><body><a href='redirect.html'>redirect</a></body></html>";

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

    final List<NameValuePair> headers = new ArrayList<>();
    headers.add(new NameValuePair("Location", "/page2.html?param=http%3A//somwhere.org"));
    getMockWebConnection().setDefaultResponse("", 302, "Found", null, headers);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.tagName("a")).click();
    assertEquals(url + "?param=http%3A//somwhere.org", driver.getCurrentUrl());
}
 
Example #8
Source File: FormData.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @param name the name of the field to check
 * @return the first value found for the give name
 */
@JsxFunction({CHROME, FF, FF68, FF60})
public String get(final String name) {
    if (StringUtils.isEmpty(name)) {
        return null;
    }

    final Iterator<NameValuePair> iter = requestParameters_.iterator();
    while (iter.hasNext()) {
        final NameValuePair pair = iter.next();
        if (name.equals(pair.getName())) {
            return pair.getValue();
        }
    }
    return null;
}
 
Example #9
Source File: HtmlSubmitInputTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void submit() throws Exception {
    final String html
        = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1' method='post'>\n"
        + "<input type='submit' name='aButton' value='foo'/>\n"
        + "<input type='suBMit' name='button' value='foo'/>\n"
        + "<input type='submit' name='anotherButton' value='foo'/>\n"
        + "</form></body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);

    final WebElement button = driver.findElement(By.name("button"));
    button.click();

    assertTitle(driver, "foo");

    assertEquals(Collections.singletonList(new NameValuePair("button", "foo")),
        getMockWebConnection().getLastParameters());
}
 
Example #10
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void submitParams(final String controls) throws Exception {
    final String html = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1' method='post'>\n"
        + controls
        + "</form></body></html>";

    final WebDriver driver = loadPage2(html);
    driver.findElement(new ById("mySubmit")).click();

    final List<NameValuePair> requestedParams = getMockWebConnection().getLastWebRequest().getRequestParameters();
    Collections.sort(requestedParams, Comparator.comparing(NameValuePair::getName));

    assertEquals(getExpectedAlerts().length, requestedParams.size());

    for (int i = 0; i < requestedParams.size(); i++) {
        assertEquals(getExpectedAlerts()[i],
                requestedParams.get(i).getName() + '#' + requestedParams.get(i).getValue());
    }
}
 
Example #11
Source File: XMLHttpRequest.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the labels and values of all the HTTP headers.
 * @return the labels and values of all the HTTP headers
 */
@JsxFunction
public String getAllResponseHeaders() {
    if (state_ == UNSENT || state_ == OPENED) {
        return "";
    }
    if (webResponse_ != null) {
        final StringBuilder builder = new StringBuilder();
        for (final NameValuePair header : webResponse_.getResponseHeaders()) {
            builder.append(header.getName()).append(": ").append(header.getValue()).append("\r\n");
        }
        if (getBrowserVersion().hasFeature(XHR_ALL_RESPONSE_HEADERS_APPEND_CRLF)) {
            builder.append("\r\n");
        }
        return builder.toString();
    }

    LOG.error("XMLHttpRequest.getAllResponseHeaders() was called without a response available (readyState: "
        + state_ + ").");
    return null;
}
 
Example #12
Source File: WebClient.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private WebResponse makeWebResponseForDataUrl(final WebRequest webRequest) throws IOException {
    final URL url = webRequest.getUrl();
    final List<NameValuePair> responseHeaders = new ArrayList<>();
    final DataURLConnection connection;
    try {
        connection = new DataURLConnection(url);
    }
    catch (final DecoderException e) {
        throw new IOException(e.getMessage());
    }
    responseHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE_LC,
        connection.getMediaType() + ";charset=" + connection.getCharset()));

    try (InputStream is = connection.getInputStream()) {
        final DownloadedContent downloadedContent =
                HttpWebConnection.downloadContent(is, getOptions().getMaxInMemory());
        final WebResponseData data = new WebResponseData(downloadedContent, 200, "OK", responseHeaders);
        return new WebResponse(data, url, webRequest.getHttpMethod(), 0);
    }
}
 
Example #13
Source File: HtmlFileInput.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public NameValuePair[] getSubmitNameValuePairs() {
    if (files_ == null || files_.length == 0) {
        return new NameValuePair[] {new KeyDataPair(getNameAttribute(), null, null, null, (Charset) null)};
    }

    final List<NameValuePair> list = new ArrayList<>();
    for (File file : files_) {
        String contentType;
        if (contentType_ == null) {
            contentType = getPage().getWebClient().getBrowserVersion().getUploadMimeType(file);
            if (StringUtils.isEmpty(contentType)) {
                contentType = MimeType.APPLICATION_OCTET_STREAM;
            }
        }
        else {
            contentType = contentType_;
        }
        final Charset charset = getPage().getCharset();
        final KeyDataPair keyDataPair = new KeyDataPair(getNameAttribute(), file, null, contentType, charset);
        keyDataPair.setData(data_);
        list.add(keyDataPair);
    }
    return list.toArray(new NameValuePair[list.size()]);
}
 
Example #14
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
private List<NameValuePair> extractHeaders(HttpURLConnection conn) {
    List<NameValuePair> headers = new ArrayList<NameValuePair>();
    Set<Map.Entry<String,List<String>>> headerFields = conn.getHeaderFields().entrySet();
    for (Map.Entry<String,List<String>> headerField : headerFields) {
        String name = headerField.getKey();
        if (name != null) { // Yes, the header name can be null.
            List<String> values = headerField.getValue();
            for (String value : values) {
                if (value != null) {
                    headers.add(new NameValuePair(name, value));
                }
            }
        }
    }
    return headers;
}
 
Example #15
Source File: FormData.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @param name the name of the field to check
 * @return the first value found for the give name
 */
@JsxFunction({CHROME, FF, FF68, FF60})
public Scriptable getAll(final String name) {
    if (StringUtils.isEmpty(name)) {
        return Context.getCurrentContext().newArray(this, 0);
    }

    final List<Object> values = new ArrayList<>();
    final Iterator<NameValuePair> iter = requestParameters_.iterator();
    while (iter.hasNext()) {
        final NameValuePair pair = iter.next();
        if (name.equals(pair.getName())) {
            values.add(pair.getValue());
        }
    }

    final Object[] stringValues = values.toArray(new Object[values.size()]);
    return Context.getCurrentContext().newArray(this, stringValues);
}
 
Example #16
Source File: HttpWebConnection.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private static Charset getCharset(final Charset charset, final List<NameValuePair> pairs) {
    for (final NameValuePair pair : pairs) {
        if (pair instanceof KeyDataPair) {
            final KeyDataPair pairWithFile = (KeyDataPair) pair;
            if (pairWithFile.getData() == null && pairWithFile.getFile() != null) {
                final String fileName = pairWithFile.getFile().getName();
                for (int i = 0; i < fileName.length(); i++) {
                    if (fileName.codePointAt(i) > 127) {
                        return charset;
                    }
                }
            }
        }
    }
    return null;
}
 
Example #17
Source File: FormData.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @param name the name of the field to check
 * @return true if the name exists
 */
@JsxFunction({CHROME, FF, FF68, FF60})
public boolean has(final String name) {
    if (StringUtils.isEmpty(name)) {
        return false;
    }

    final Iterator<NameValuePair> iter = requestParameters_.iterator();
    while (iter.hasNext()) {
        final NameValuePair pair = iter.next();
        if (name.equals(pair.getName())) {
            return true;
        }
    }
    return false;
}
 
Example #18
Source File: XMLHttpRequestTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the default encoding for an XMLHttpRequest is UTF-8.
 * @throws Exception if an error occurs
 */
@Test
@Alerts("ol\u00E9")
public void defaultEncodingIsUTF8() throws Exception {
    // TODO [IE]SINGLE-VS-BULK test runs when executed as single but breaks as bulk
    shutDownRealIE();

    final String html =
          "<html>\n"
        + "  <head>\n"
        + "    <script>\n"
        + "      function test() {\n"
        + "        var request = new XMLHttpRequest();\n"
        + "        request.open('GET', '" + URL_SECOND + "', false);\n"
        + "        request.send('');\n"
        + "        alert(request.responseText);\n"
        + "      }\n"
        + "    </script>\n"
        + "  </head>\n"
        + "  <body onload='test()'>\n"
        + "  </body>\n"
        + "</html>";

    final String response = "ol\u00E9";
    final byte[] responseBytes = response.getBytes(UTF_8);

    getMockWebConnection().setResponse(URL_SECOND, responseBytes, 200, "OK", MimeType.TEXT_HTML,
        new ArrayList<NameValuePair>());
    loadPageWithAlerts2(html);
}
 
Example #19
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testOIDCLoginForPublicClientWithRefreshTokenScope() throws Exception {
    final UriBuilder authorizationUrl = oidcEndpointBuilder("/idp/authorize")
        .queryParam("client_id", publicClientId)
        .queryParam("response_type", "code")
        .queryParam("scope", "openid refreshToken")
        .queryParam("redirect_uri", REDIRECT_URL);

    // Login to the OIDC authorization endpoint + get the authorization code
    final String authorizationCode;
    try (WebClient webClient = setupWebClientIDP("alice", "ecila")) {
        final HtmlPage confirmationPage = login(authorizationUrl, webClient);
        final HtmlForm form = confirmationPage.getForms().get(0);
        authorizationCode = form.getButtonByName("oauthDecision").click().getWebResponse().getContentAsString();
    }

    // Now use the code to get an IdToken
    Map<String, Object> json = getTokenJson(authorizationCode, publicClientId, null);

    // Get the access token
    final String accessToken = json.get("access_token").toString();

    // Refresh access token
    try (WebClient webClient = setupWebClient()) {
        WebRequest request = new WebRequest(oidcEndpoint("/oauth2/token"), HttpMethod.POST);

        request.setRequestParameters(Arrays.asList(
            new NameValuePair("client_id", publicClientId),
            new NameValuePair("grant_type", "refresh_token"),
            new NameValuePair("refresh_token", json.get("refresh_token").toString())));

        json = new JsonMapObjectReaderWriter().fromJson(
            webClient.getPage(request).getWebResponse().getContentAsString());
        assertNotEquals(accessToken, json.get("access_token").toString());
    }
}
 
Example #20
Source File: HttpWebConnection2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void redirectBrokenGzip() throws Exception {
    final String html = "<html></html>";

    final List<NameValuePair> headers = Arrays.asList(new NameValuePair("Location", URL_SECOND.toString()),
            new NameValuePair("Content-Encoding", "gzip"));
    final MockWebConnection conn = getMockWebConnection();
    conn.setResponse(URL_FIRST, "12", 302, "Some error", MimeType.TEXT_HTML, headers);
    conn.setResponse(URL_SECOND, html);

    final WebDriver driver = loadPageWithAlerts2(URL_FIRST);
    assertEquals(URL_SECOND.toString(), driver.getCurrentUrl());
}
 
Example #21
Source File: CacheTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test that content retrieved with XHR is cached when right headers are here.
 * @throws Exception if the test fails
 */
@Test
@Alerts({"hello", "hello"})
public void xhrContentCached() throws Exception {
    final String html = "<html><head><title>page 1</title>\n"
        + "<script>\n"
        + "  function doTest() {\n"
        + "    var xhr = new XMLHttpRequest();\n"
        + "    xhr.open('GET', 'foo.txt', false);\n"
        + "    xhr.send('');\n"
        + "    alert(xhr.responseText);\n"
        + "    xhr.send('');\n"
        + "    alert(xhr.responseText);\n"
        + "  }\n"
        + "</script>\n"
        + "</head>\n"
        + "<body onload='doTest()'>x</body>\n"
        + "</html>";

    final MockWebConnection connection = getMockWebConnection();

    final List<NameValuePair> headers =
        Collections.singletonList(new NameValuePair("Last-Modified", "Sun, 15 Jul 2007 20:46:27 GMT"));
    connection.setResponse(new URL(URL_FIRST, "foo.txt"), "hello", 200, "OK", MimeType.TEXT_PLAIN, headers);

    loadPageWithAlerts(html);

    assertEquals(2, connection.getRequestCount());
}
 
Example #22
Source File: HtmlAnchorTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"§§URL§§bug.html?h%C3%B6=G%C3%BCnter", "h\u00F6", "G\u00FCnter"})
public void encoding() throws Exception {
    final String href = "bug.html?" + URLEncoder.encode("h\u00F6", "UTF-8")
            + '=' + URLEncoder.encode("G\u00FCnter", "UTF-8");
    final String html =
        "<html>\n"
        + "<head>\n"
        + "  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>\n"
        + "</head>\n"
        + "<body>\n"
        + "  <a href='" + href + "' id='myLink'>Click me</a>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse(html, MimeType.TEXT_HTML, UTF_8);

    expandExpectedAlertsVariables(URL_FIRST);
    final WebDriver driver = loadPage2(html, URL_FIRST);
    driver.findElement(By.id("myLink")).click();

    assertEquals(getExpectedAlerts()[0], driver.getCurrentUrl());

    final List<NameValuePair> requestedParams = getMockWebConnection().getLastWebRequest().getRequestParameters();
    assertEquals(1, requestedParams.size());
    assertEquals(getExpectedAlerts()[1], requestedParams.get(0).getName());
    assertEquals(getExpectedAlerts()[2], requestedParams.get(0).getValue());
}
 
Example #23
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testClientCredentialsSTS() throws Exception {
    final URL url = oidcEndpoint("/oauth2/token");
    WebRequest request = new WebRequest(url, HttpMethod.POST);

    request.setRequestParameters(Arrays.asList(
        new NameValuePair("client_id", "alice"),
        new NameValuePair("client_secret", "ecila"),
        new NameValuePair("grant_type", "client_credentials")));

    try (WebClient webClient = setupWebClient()) {
        final String response = webClient.getPage(request).getWebResponse().getContentAsString();
        assertTrue(response.contains("access_token"));
    }
}
 
Example #24
Source File: HTMLImageElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts({"done;onload;", "2"})
public void img_download_onloadBefore() throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);
        final URL urlImage = new URL(URL_FIRST, "img.jpg");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);
    }

    final String html = "<html><body>\n"
        + "<script>\n"
        + "  var i = new Image();\n"
        + "  i.onload = function() { document.title += 'onload;'; };\n"
        + "  i.src = 'img.jpg';\n"
        + "  document.title += 'done;';\n"
        + "</script></body></html>";

    final int count = getMockWebConnection().getRequestCount();
    final WebDriver driver = getWebDriver();
    if (driver instanceof HtmlUnitDriver) {
        ((HtmlUnitDriver) driver).setDownloadImages(true);
    }
    loadPage2(html);

    assertTitle(driver, getExpectedAlerts()[0]);
    assertEquals(Integer.parseInt(getExpectedAlerts()[1]), getMockWebConnection().getRequestCount() - count);
    assertEquals(URL_FIRST + "img.jpg", getMockWebConnection().getLastWebRequest().getUrl());
}
 
Example #25
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Adds a security crumb to the request.
 * Use {@link #createCrumbedUrl} instead if you intend to call {@link WebRequest#setRequestBody}, typical of a POST request.
 */
public WebRequest addCrumb(WebRequest req) {
    ArrayList<NameValuePair> params = new ArrayList<>();
    params.add(getCrumbHeaderNVP());
    List<NameValuePair> oldParams = req.getRequestParameters();
    if (oldParams != null) {
        params.addAll(oldParams);
    }
    req.setRequestParameters(params);
    return req;
}
 
Example #26
Source File: HTMLIFrameElement3Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void retrictByHeader(final NameValuePair header, final URL contentUrl) throws Exception {
    final String html
        = "<!DOCTYPE html>\n"
        + "<html>\n"
        + "<head>\n"
        + "  <title>Deny</title>\n"
        + "  <script>\n"
        + "    function check() {\n"
        + "      try {\n"
        + "        alert(document.getElementById(\"frame1\").contentDocument);\n"
        + "      } catch (e) { alert('error'); }\n"
        + "    }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body>\n"
        + "  <iframe id='frame1' src='" + contentUrl + "' "
                + "onLoad='alert(\"loaded\")' onError='alert(\"error\")'></iframe>\n"
        + "  <button type='button' id='clickme' onClick='check()'>Click me</a>\n"
        + "</body>\n"
        + "</html>";

    final String content = "<html><head><title>IFrame Title</title></head>\n"
            + "<body>IFrame Content</body>\n"
            + "</html>";

    final List<NameValuePair> headers = new ArrayList<>();
    headers.add(header);

    getMockWebConnection().setResponse(contentUrl, content,
            200, "OK", MimeType.TEXT_HTML, headers);

    final String[] expectedAlerts = getExpectedAlerts();
    setExpectedAlerts(Arrays.copyOf(expectedAlerts, expectedAlerts.length - 1));
    final WebDriver driver = loadPageWithAlerts2(html, new URL(URL_FIRST, "path"), DEFAULT_WAIT_TIME);

    driver.findElement(By.id("clickme")).click();
    verifyAlerts(driver, expectedAlerts[expectedAlerts.length - 1]);

    assertEquals(2, getMockWebConnection().getRequestCount());
}
 
Example #27
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public HtmlPage doRegister() throws FailingHttpStatusCodeException, IOException {
	WebRequest registerRequest = new WebRequest(new URL(codedefendersHome + Paths.LOGIN), HttpMethod.POST);
	registerRequest.setRequestParameters(Arrays.asList(
			new NameValuePair("formType", "create"),
			new NameValuePair("username", user.getUsername()),
			new NameValuePair("email", user.getEmail()),
			new NameValuePair("password", password),
			new NameValuePair("confirm", password)));
	return browser.getPage(registerRequest);

}
 
Example #28
Source File: Location2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = "null",
        CHROME = "§§URL§§a.html?p1=sieben&p2")
public void reloadGet() throws Exception {
    final String html =
          "<html>\n"
        + "  <head></head>\n"
        + "  <body>\n"
        + "    <a href='javascript:window.location.reload(true);' id='link'>reload</a>\n"
        + "  </body>\n"
        + "</html>";

    getMockWebConnection().setDefaultResponse(html);
    final WebDriver driver = loadPage2(html, new URL(URL_FIRST + "a.html?p1=sieben&p2"));
    assertEquals(1, getMockWebConnection().getRequestCount());

    driver.findElement(By.id("link")).click();
    assertEquals(2, getMockWebConnection().getRequestCount());

    assertEquals(HttpMethod.GET, getMockWebConnection().getLastWebRequest().getHttpMethod());
    assertEquals(URL_FIRST + "a.html?p1=sieben&p2", getMockWebConnection().getLastWebRequest().getUrl());

    final List<NameValuePair> params = getMockWebConnection().getLastWebRequest().getRequestParameters();
    assertEquals(2, params.size());
    assertEquals("p1", params.get(0).getName());
    assertEquals("sieben", params.get(0).getValue());
    assertEquals("p2", params.get(1).getName());
    assertEquals("", params.get(1).getValue());

    expandExpectedAlertsVariables(URL_FIRST);
    final Map<String, String> additionalHeaders = getMockWebConnection().getLastAdditionalHeaders();
    assertNull(additionalHeaders.get(HttpHeader.ORIGIN));
    assertEquals(getExpectedAlerts()[0], "" + additionalHeaders.get(HttpHeader.REFERER));
    assertEquals("localhost:" + PORT, additionalHeaders.get(HttpHeader.HOST));
}
 
Example #29
Source File: CookieManager4Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("c4=4")
public void domain2() throws Exception {
    final List<NameValuePair> responseHeader1 = new ArrayList<>();
    responseHeader1.add(new NameValuePair("Set-Cookie", "c1=1; Path=/"));
    responseHeader1.add(new NameValuePair("Set-Cookie", "c2=2; Domain=host1." + DOMAIN + "; Path=/"));
    responseHeader1.add(new NameValuePair("Set-Cookie", "c3=3; Domain=host2." + DOMAIN + "; Path=/"));
    responseHeader1.add(new NameValuePair("Set-Cookie", "c4=4; Domain=" + DOMAIN + "; Path=/"));
    responseHeader1.add(new NameValuePair("Set-Cookie", "c5=5; Domain=.org; Path=/"));

    final String html = "<html>\n"
        + "<head></head>\n"
        + "<body>\n"
        + "<p>Cookie Domain Test</p>\n"
        + "<script>\n"
        + "  location.replace('" + URL_HOST3 + "');\n"
        + "</script>\n"
        + "</body>\n"
        + "</html>";

    getMockWebConnection().setDefaultResponse(CookieManagerTest.HTML_ALERT_COOKIE);
    final URL firstUrl = new URL(URL_HOST1);
    getMockWebConnection().setResponse(firstUrl, html, 200, "Ok", MimeType.TEXT_HTML, responseHeader1);

    loadPageWithAlerts2(firstUrl);
}
 
Example #30
Source File: CookieManagerTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = "cookie1=1",
        IE = "cookie1=1; cookie2=2")
@NotYetImplemented(IE)
public void cookieExpires_GMT() throws Exception {
    final List<NameValuePair> responseHeader = new ArrayList<>();
    responseHeader.add(new NameValuePair("Set-Cookie",
                                            "cookie1=1;expires=Sun Jan 20 2042 17:45:00 GMT+0800 (CST)"));
    responseHeader.add(new NameValuePair("Set-Cookie",
                                            "cookie2=2;expires=Sun Jan 20 2004 17:45:00 GMT+0800 (CST)"));
    getMockWebConnection().setResponse(URL_FIRST, HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML, responseHeader);

    loadPageWithAlerts2(URL_FIRST);
}