@Test public void shouldSerializeExpiresBasedOnMaxAge() { int maxAgeSeconds = 35; Cookie cookie = new Cookie("name", "value"); cookie.setMaxAge(maxAgeSeconds); String serializedCookie = cookieHeaderSerializer.serialize(cookie); Date date = new Date(System.currentTimeMillis() + Long.valueOf(maxAgeSeconds) * 1000l); String expiresValue = DateUtilities.dateFormat(date); assertThat(getExpiresValue(serializedCookie), is(expiresValue)); }
/** * Handles session storage/invalidation, sets session cookies. * * @param session * @param response * @throws IOException */ public void handleSession(final HttpSessionImpl session, final HttpServletResponseImpl response) throws IOException { Cookie cookie = new Cookie(HttpSessionImpl.COOKIE_NAME, ""); if (session.isInvalidated()) { cookie.setMaxAge(MAX_AGE_IN_PAST); sessionStorage.removeSession(session); LOGGER.log(Level.FINE, "Invalidated session {0}", new Object[]{session.getId()}); } else { cookie.setValue(session.getId()); sessionStorage.persistSession(session); } response.addCookie(cookie); }
@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 shouldSerializeCookieWithAllAttributes() { Cookie cookie = new Cookie("name", "value"); cookie.setDomain("example.com"); cookie.setMaxAge(20); cookie.setSecure(true); cookie.setHttpOnly(true); cookie.setPath("/somepath"); cookie.setComment("Some Comment"); String serializedCookie = cookieHeaderSerializer.serialize(cookie); String[] serializedCookieParts = getCookieParts(serializedCookie); assertThat(serializedCookie, startsWith("name=value")); assertThat(serializedCookie, containsString("Expires")); assertThat(getExpiresValue(serializedCookie), endsWith("GMT")); // Pseudo date validation assertThat(serializedCookieParts, hasItemInArray("Domain=example.com")); assertThat(serializedCookieParts, hasItemInArray("Path=/somepath")); assertThat(serializedCookieParts, hasItemInArray("HttpOnly")); assertThat(serializedCookieParts, hasItemInArray("Secure")); assertThat(serializedCookieParts, hasItemInArray("Comment=Some Comment")); }