com.gargoylesoftware.htmlunit.util.Cookie Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.util.Cookie. 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: CookieManager2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("my_key=")
public void cookie_nullValue() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    final URL url = URL_FIRST;
    webConnection.setResponse(url, CookieManagerTest.HTML_ALERT_COOKIE);
    webClient.setWebConnection(webConnection);

    final CookieManager mgr = webClient.getCookieManager();
    mgr.addCookie(new Cookie(URL_FIRST.getHost(), "my_key", null, "/", null, false));

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

    webClient.getPage(URL_FIRST);
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example #2
Source File: TapestrySecurityIntegrationTest.java    From tapestry-security with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"notLoggedIn"})
public void testInterceptComponentMethodWithAjaxDeny() throws Exception
{
	CookieManager cookieManager = webClient.getCookieManager();
	cookieManager.clearCookies();
	clickOnBasePage("componentMethodInterceptorWithAjax");
	// this executes window.location.replace so we have to wait for it. is there an event we could listen instead?
	webClient.waitForBackgroundJavaScript(500);
	page = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();
	assertLoginPage();

	for (Cookie cookie : cookieManager.getCookies())
		if (cookie.getName().equals("shiroSavedRequest")) {
			// test we've stored a page render request, not the component event request. Could also just test for existence of a dot
			assertEquals(cookie.getPath() + "/", APP_CONTEXT);
			return;
		}
	fail();
}
 
Example #3
Source File: HTMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@JsxGetter
public String getCookie() {
    final HtmlPage page = getPage();

    final URL url = page.getUrl();

    final StringBuilder builder = new StringBuilder();
    final Set<Cookie> cookies = page.getWebClient().getCookies(url);
    for (final Cookie cookie : cookies) {
        if (cookie.isHttpOnly()) {
            continue;
        }
        if (builder.length() != 0) {
            builder.append("; ");
        }
        if (!HtmlUnitBrowserCompatCookieSpec.EMPTY_COOKIE_NAME.equals(cookie.getName())) {
            builder.append(cookie.getName());
            builder.append("=");
        }
        builder.append(cookie.getValue());
    }

    return builder.toString();
}
 
Example #4
Source File: WebSocketCookieStore.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<HttpCookie> get(final URI uri) {
    final List<HttpCookie> cookies = new ArrayList<>();
    try {
        final String urlString = uri.toString().replace("ws://", "http://").replace("wss://", "https://");
        final java.net.URL url = new java.net.URL(urlString);
        for (final Cookie cookie : webClient_.getCookies(url)) {
            final HttpCookie httpCookie = new HttpCookie(cookie.getName(), cookie.getValue());
            httpCookie.setVersion(0);
            cookies.add(httpCookie);
        }
    }
    catch (final Exception e) {
        throw new RuntimeException(e);
    }
    return cookies;
}
 
Example #5
Source File: UrlFetchWebConnection.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private void addCookies(final HttpURLConnection connection) {
    final StringBuilder cookieHeader = new StringBuilder();
    boolean isFirst = true;
    for (Cookie cookie : webClient_.getCookies(connection.getURL())) {
        if (isFirst) {
            isFirst = false;
        }
        else {
            cookieHeader.append("; ");
        }

        cookieHeader.append(cookie.getName()).append('=').append(cookie.getValue());
    }
    if (!isFirst) {
        connection.setRequestProperty(HttpHeader.COOKIE, cookieHeader.toString());
    }
}
 
Example #6
Source File: CookieManager.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Clears all cookies that have expired before supplied date.
 * If disabled, this returns false.
 * @param date the date to use for comparison when clearing expired cookies
 * @return whether any cookies were found expired, and were cleared
 */
public synchronized boolean clearExpired(final Date date) {
    if (!isCookiesEnabled()) {
        return false;
    }

    if (date == null) {
        return false;
    }

    boolean foundExpired = false;
    for (final Iterator<Cookie> iter = cookies_.iterator(); iter.hasNext();) {
        final Cookie cookie = iter.next();
        if (cookie.getExpires() != null && date.after(cookie.getExpires())) {
            iter.remove();
            foundExpired = true;
        }
    }
    return foundExpired;
}
 
Example #7
Source File: HtmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test the "set-cookie" meta tag.
 * @throws Exception if the test fails
 */
@Test
public void setCookieMetaTag() throws Exception {
    final String content = "<html><head><title>first</title>\n"
        + "<meta http-equiv='set-cookie' content='webm=none; path=/;'>\n"
        + "</head><body>\n"
        + "<script>alert(document.cookie)</script>\n"
        + "</body></html>";

    final String[] expectedAlerts = {"webm=none"};
    createTestPageForRealBrowserIfNeeded(content, expectedAlerts);

    final List<String> collectedAlerts = new ArrayList<>();
    final HtmlPage page = loadPage(content, collectedAlerts);
    assertEquals(expectedAlerts, collectedAlerts);

    final Set<Cookie> cookies = page.getWebClient().getCookieManager().getCookies();
    assertEquals(1, cookies.size());
    final Cookie cookie = cookies.iterator().next();
    assertEquals(page.getUrl().getHost(), cookie.getDomain());
    assertEquals("webm", cookie.getName());
    assertEquals("none", cookie.getValue());
    assertEquals("/", cookie.getPath());
}
 
Example #8
Source File: CookieManager2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * This was causing a ConcurrentModificationException.
 * In "real life" the problem was arising due to changes to the cookies made from
 * the JS processing thread.
 * @throws Exception if the test fails
 */
@Test
public void getCookiesShouldReturnACopyOfCurentState() throws Exception {
    final String html = "<html><body>\n"
            + "<button id='it' onclick=\"document.cookie = 'foo=bla'\">click me</button>\n"
            + "<script>\n"
            + "document.cookie = 'cookie1=value1';\n"
            + "</script></body></html>";

    final WebClient webClient = getWebClient();

    final HtmlPage page = loadPage(html);
    final Set<Cookie> initialCookies = webClient.getCookieManager().getCookies();
    assertEquals(1, initialCookies.size());
    final Iterator<Cookie> iterator = initialCookies.iterator();

    page.getHtmlElementById("it").click();
    iterator.next(); // ConcurrentModificationException was here
    assertEquals(1, initialCookies.size());
    assertEquals(2, webClient.getCookieManager().getCookies().size());
}
 
Example #9
Source File: CookieManager2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("my_name=my_data")
public void cookie_maxAgeMinusOne() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    final URL url = URL_FIRST;
    webConnection.setResponse(url, CookieManagerTest.HTML_ALERT_COOKIE);
    webClient.setWebConnection(webConnection);

    final CookieManager mgr = webClient.getCookieManager();
    mgr.addCookie(new Cookie(URL_FIRST.getHost(), "my_name", "my_data", "/", -1, false));

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

    webClient.getPage(URL_FIRST);
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example #10
Source File: MockMvcWebConnection.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void storeCookies(WebRequest webRequest, javax.servlet.http.Cookie[] cookies) {
	Date now = new Date();
	CookieManager cookieManager = this.webClient.getCookieManager();
	for (javax.servlet.http.Cookie cookie : cookies) {
		if (cookie.getDomain() == null) {
			cookie.setDomain(webRequest.getUrl().getHost());
		}
		Cookie toManage = createCookie(cookie);
		Date expires = toManage.getExpires();
		if (expires == null || expires.after(now)) {
			cookieManager.addCookie(toManage);
		}
		else {
			cookieManager.removeCookie(toManage);
		}
	}
}
 
Example #11
Source File: WebClient2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void checkCookie(final String cookieString, final String name, final String value,
        final String path, final boolean secure, final Date date) {

    final String domain = URL_FIRST.getHost();

    getWebClient().getCookieManager().clearCookies();
    getWebClient().addCookie(cookieString, URL_FIRST, this);
    final Cookie cookie = getWebClient().getCookieManager().getCookies().iterator().next();

    assertEquals(name, cookie.getName());
    assertEquals(value, cookie.getValue());
    assertEquals(path, cookie.getPath());
    assertEquals(domain, cookie.getDomain());
    assertEquals(secure, cookie.isSecure());
    assertEquals(date, cookie.getExpires());
}
 
Example #12
Source File: HTMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@JsxGetter
public String getCookie() {
    final HtmlPage page = getPage();

    final URL url = page.getUrl();

    final StringBuilder builder = new StringBuilder();
    final Set<Cookie> cookies = page.getWebClient().getCookies(url);
    for (final Cookie cookie : cookies) {
        if (cookie.isHttpOnly()) {
            continue;
        }
        if (builder.length() != 0) {
            builder.append("; ");
        }
        if (!HtmlUnitBrowserCompatCookieSpec.EMPTY_COOKIE_NAME.equals(cookie.getName())) {
            builder.append(cookie.getName());
            builder.append('=');
        }
        builder.append(cookie.getValue());
    }

    return builder.toString();
}
 
Example #13
Source File: WebSocketCookieStore.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<HttpCookie> get(final URI uri) {
    final List<HttpCookie> cookies = new ArrayList<>();
    try {
        final String urlString = uri.toString().replace("ws://", "http://").replace("wss://", "https://");
        final java.net.URL url = new java.net.URL(urlString);
        for (final Cookie cookie : webClient_.getCookies(url)) {
            final HttpCookie httpCookie = new HttpCookie(cookie.getName(), cookie.getValue());
            httpCookie.setVersion(0);
            cookies.add(httpCookie);
        }
    }
    catch (final Exception e) {
        throw new RuntimeException(e);
    }
    return cookies;
}
 
Example #14
Source File: CookieManager.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Clears all cookies that have expired before supplied date.
 * If disabled, this returns false.
 * @param date the date to use for comparison when clearing expired cookies
 * @return whether any cookies were found expired, and were cleared
 */
public synchronized boolean clearExpired(final Date date) {
    if (!isCookiesEnabled()) {
        return false;
    }

    if (date == null) {
        return false;
    }

    boolean foundExpired = false;
    for (final Iterator<Cookie> iter = cookies_.iterator(); iter.hasNext();) {
        final Cookie cookie = iter.next();
        if (cookie.getExpires() != null && date.after(cookie.getExpires())) {
            iter.remove();
            foundExpired = true;
        }
    }
    return foundExpired;
}
 
Example #15
Source File: MockMvcWebConnection.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void storeCookies(WebRequest webRequest, javax.servlet.http.Cookie[] cookies) {
	Date now = new Date();
	CookieManager cookieManager = this.webClient.getCookieManager();
	for (javax.servlet.http.Cookie cookie : cookies) {
		if (cookie.getDomain() == null) {
			cookie.setDomain(webRequest.getUrl().getHost());
		}
		Cookie toManage = createCookie(cookie);
		Date expires = toManage.getExpires();
		if (expires == null || expires.after(now)) {
			cookieManager.addCookie(toManage);
		}
		else {
			cookieManager.removeCookie(toManage);
		}
	}
}
 
Example #16
Source File: MockMvcWebClientBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-14066
public void cookieManagerShared() throws Exception {
	this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build();
	WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).build();

	assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("NA"));
	client.getCookieManager().addCookie(new Cookie("localhost", "cookie", "cookieManagerShared"));
	assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("cookieManagerShared"));
}
 
Example #17
Source File: JwtAuthenticationServiceImplTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private String getToken(JenkinsRule.WebClient webClient) throws IOException {
    URL tokenUrl = new URL(webClient.getContextPath() + "jwt-auth/token/");
    HttpURLConnection  connection = (HttpURLConnection) tokenUrl.openConnection();
    Set<Cookie> cookies = webClient.getCookies(tokenUrl);
    for (Cookie cookie : cookies) {
        connection.addRequestProperty("Cookie", cookie.getName() + "=" + cookie.getValue());
    }
    Assert.assertEquals(connection.getResponseCode(), 204);
    String token = connection.getHeaderField("X-BLUEOCEAN-JWT");
    connection.disconnect();
    return token;
}
 
Example #18
Source File: MockMvcWebClientBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@DeleteMapping(path = "/", produces = "text/plain")
String deleteCookie(HttpServletResponse response) {
	javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(COOKIE_NAME, "");
	cookie.setMaxAge(0);
	response.addCookie(cookie);
	return "Delete";
}
 
Example #19
Source File: UrlFetchWebConnection.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given string into cookies.
 * Very limited implementation.
 * All created cookies apply to all paths, never expire and are not secure.
 * Will not work when there's a comma in the cookie value (because there's a bug in the Url Fetch Service)
 * @see "http://code.google.com/p/googleappengine/issues/detail?id=3379"
 * @param cookieHeaderString The cookie string to parse
 * @param domain the domain of the current request
 * @return The parsed cookies
 */
static Set<Cookie> parseCookies(final String domain, final String cookieHeaderString) {
    final Set<Cookie> cookies = new HashSet<>();
    final String[] cookieStrings = cookieHeaderString.split(",");
    for (int i = 0; i < cookieStrings.length; i++) {
        final String[] nameAndValue = cookieStrings[i].split(";")[0].split("=");
        if (nameAndValue.length > 1) {
            cookies.add(new Cookie(domain, nameAndValue[0], nameAndValue[1]));
        }
    }
    return cookies;
}
 
Example #20
Source File: UrlFetchWebConnection.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private void saveCookies(final String domain, final List<NameValuePair> headers) {
    for (final NameValuePair nvp : headers) {
        if ("Set-Cookie".equalsIgnoreCase(nvp.getName())) {
            final Set<Cookie> cookies = parseCookies(domain, nvp.getValue());
            for (Cookie cookie : cookies) {
                webClient_.getCookieManager().addCookie(cookie);
            }
        }
    }
}
 
Example #21
Source File: MockMvcHtmlUnitDriverBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-14066
public void cookieManagerShared() throws Exception {
	WebConnectionHtmlUnitDriver otherDriver = new WebConnectionHtmlUnitDriver();
	this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build();
	this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc)
			.withDelegate(otherDriver).build();

	assertThat(get("http://localhost/"), equalTo(""));
	Cookie cookie = new Cookie("localhost", "cookie", "cookieManagerShared");
	otherDriver.getWebClient().getCookieManager().addCookie(cookie);
	assertThat(get("http://localhost/"), equalTo("cookieManagerShared"));
}
 
Example #22
Source File: CookieManager.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the specified cookie.
 * If disabled, this does nothing.
 * @param cookie the cookie to remove
 */
public synchronized void removeCookie(final Cookie cookie) {
    if (!isCookiesEnabled()) {
        return;
    }

    cookies_.remove(cookie);
}
 
Example #23
Source File: CookieManager.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified cookie.
 * If disabled, this does nothing.
 * @param cookie the cookie to add
 */
public synchronized void addCookie(final Cookie cookie) {
    if (!isCookiesEnabled()) {
        return;
    }

    cookies_.remove(cookie);

    // don't add expired cookie
    if (cookie.getExpires() == null || cookie.getExpires().after(new Date())) {
        cookies_.add(cookie);
    }
}
 
Example #24
Source File: CookieManager.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the currently configured cookie with the specified name, or {@code null} if one does not exist.
 * If disabled, this returns null.
 * @param name the name of the cookie to return
 * @return the currently configured cookie with the specified name, or {@code null} if one does not exist
 */
public synchronized Cookie getCookie(final String name) {
    if (!isCookiesEnabled()) {
        return null;
    }

    for (Cookie cookie : cookies_) {
        if (StringUtils.equals(cookie.getName(), name)) {
            return cookie;
        }
    }
    return null;
}
 
Example #25
Source File: CookieManager.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the currently configured cookies, in an unmodifiable set.
 * If disabled, this returns an empty set.
 * @return the currently configured cookies, in an unmodifiable set
 */
public synchronized Set<Cookie> getCookies() {
    if (!isCookiesEnabled()) {
        return Collections.<Cookie>emptySet();
    }

    final Set<Cookie> copy = new LinkedHashSet<>();
    copy.addAll(cookies_);
    return Collections.unmodifiableSet(copy);
}
 
Example #26
Source File: MockMvcWebClientBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test // SPR-14066
public void cookieManagerShared() throws Exception {
	this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build();
	WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).build();

	assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("NA"));
	client.getCookieManager().addCookie(new Cookie("localhost", "cookie", "cookieManagerShared"));
	assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("cookieManagerShared"));
}
 
Example #27
Source File: CookieManager2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for bug 3053526: HtmlUnit was throwing an Exception when asking for cookies
 * of "about:blank".
 * @throws Exception if the test fails
 */
@Test
public void cookiesForAboutBlank() throws Exception {
    final WebClient webClient = getWebClient();
    final HtmlPage htmlPage = webClient.getPage("about:blank");

    final Set<Cookie> cookies = webClient.getCookies(htmlPage.getUrl());
    assertTrue(cookies.toString(), cookies.isEmpty());
}
 
Example #28
Source File: CookieManager.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the specified cookie.
 * If disabled, this does nothing.
 * @param cookie the cookie to remove
 */
public synchronized void removeCookie(final Cookie cookie) {
    if (!isCookiesEnabled()) {
        return;
    }

    cookies_.remove(cookie);
}
 
Example #29
Source File: CookieManager.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the currently configured cookie with the specified name, or {@code null} if one does not exist.
 * If disabled, this returns null.
 * @param name the name of the cookie to return
 * @return the currently configured cookie with the specified name, or {@code null} if one does not exist
 */
public synchronized Cookie getCookie(final String name) {
    if (!isCookiesEnabled()) {
        return null;
    }

    for (Cookie cookie : cookies_) {
        if (StringUtils.equals(cookie.getName(), name)) {
            return cookie;
        }
    }
    return null;
}
 
Example #30
Source File: CookieManager.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified cookie.
 * If disabled, this does nothing.
 * @param cookie the cookie to add
 */
public synchronized void addCookie(final Cookie cookie) {
    if (!isCookiesEnabled()) {
        return;
    }

    cookies_.remove(cookie);

    // don't add expired cookie
    if (cookie.getExpires() == null || cookie.getExpires().after(new Date())) {
        cookies_.add(cookie);
    }
}