/** * Parses cookie string, returns an array representing cookies read. * * @param input * @return * @throws MalformedInputException */ @Override public Map<String, Cookie> parse(final String input) throws MalformedInputException { Map<String, Cookie> cookies = new HashMap<>(); // Splitting separate cookies array String[] cookiesStr = input.split(COOKIE_SEPARATOR); for (int i = 0; i < cookiesStr.length; i++) { // Splitting cookie name=value pair String[] cookieValues = cookiesStr[i].split(VALUE_SEPARATOR, 2); String cookieName = cookieValues[0].trim(); if (cookieValues.length > 1 && cookieName.length() > 0) { Cookie cookie = new Cookie(cookieName, StringUtilities.urlDecode(cookieValues[1])); cookies.put(cookie.getName(), cookie); } } return cookies; } }
public String serialize(final Cookie cookie) { StringBuilder sb = new StringBuilder(); sb.append(cookie.getName()) .append(EQUALS) .append(StringUtilities.urlEncode(cookie.getValue()));
@Test public void shouldSetCookieAndPersistForValidSession() throws IOException { HttpSessionImpl session = new HttpSessionImpl("123", System.currentTimeMillis()); servletContext.handleSession(session, response); verify(sessionStorage, times(1)).persistSession(session); assertThat(response.getCookies().size(), is(greaterThan(0))); for (Cookie cookie : response.getCookies()) { if (cookie.getName().equals(HttpSessionImpl.COOKIE_NAME)) { assertThat(cookie.getValue(), is(not(nullValue()))); return; } } fail("Session cookie was not set."); }
@Test public void shouldWorkGettersAndSetters() { Cookie cookie = new Cookie("someName", "someValue"); cookie.setComment("comment"); cookie.setDomain("example.com"); cookie.setPath("/somepath"); cookie.setSecure(true); cookie.setHttpOnly(true); assertThat(cookie.getName(), is("someName")); assertThat(cookie.getValue(), is("someValue")); cookie.setValue("SomeValue2"); assertThat(cookie.getValue(), is("SomeValue2")); assertThat(cookie.getComment(), is("comment")); assertThat(cookie.getDomain(), is("example.com")); assertThat(cookie.getPath(), is("/somepath")); assertThat(cookie.isSecure(), is(true)); assertThat(cookie.isHttpOnly(), is(true)); assertThat(cookie.getMaxAge(), is(-1)); cookie.setMaxAge(125); assertThat(cookie.getMaxAge(), is(125)); }
@Test public void shouldEraseCookieAndRemoveForInvalidatedSession() throws IOException { HttpSessionImpl session = new HttpSessionImpl("123", System.currentTimeMillis()); session.invalidate(); servletContext.handleSession(session, response); verify(sessionStorage, times(1)).removeSession(session); assertThat(response.getCookies().size(), is(greaterThan(0))); for (Cookie cookie : response.getCookies()) { if (cookie.getName().equals(HttpSessionImpl.COOKIE_NAME)) { assertThat(cookie.getMaxAge(), lessThan(-1)); return; } } fail("Session DELETE cookie was not set."); }