@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)); }
/** * 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())); if (cookie.getMaxAge() != -1) { sb.append(SEPARATOR) .append("Expires") .append(EQUALS) .append(getExpires(cookie.getMaxAge())); if (cookie.getPath() != null) { sb.append(SEPARATOR) .append("Path") .append(EQUALS) .append(cookie.getPath()); if (cookie.getDomain() != null) { sb.append(SEPARATOR) .append("Domain") .append(EQUALS) .append(cookie.getDomain()); if (cookie.getComment() != null) { sb.append(SEPARATOR) .append("Comment") .append(EQUALS) .append(cookie.getComment());
@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")); }
/** * 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(expected = IllegalArgumentException.class) public void shouldNotAllowIllegalName() { new Cookie(";illegal", "somevalue"); }
@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)); }
@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 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."); }
/** * {@inheritDoc} */ @Override public String getRequestedSessionId() { Cookie sessionCookie = getCookie(HttpSessionImpl.COOKIE_NAME); if (sessionCookie == null) { return null; } return sessionCookie.getValue(); }
@Test public void shouldReturnSession() { Map<String, Cookie> cookies = new HashMap<>(); Cookie sessionCookie = new Cookie(HttpSessionImpl.COOKIE_NAME, "sessionId"); cookies.put(HttpSessionImpl.COOKIE_NAME, sessionCookie); httpServletRequestImpl = builder.withCookies(cookies).withServletContext(servletContext).build(); when(servletContext.getSession("sessionId")).thenReturn(new HttpSessionImpl("sessionId", System.currentTimeMillis())); assertThat(httpServletRequestImpl.getSession(), is(instanceOf(HttpSessionImpl.class))); }
@Test public void shouldParseCookieHavingSpaceInValue() throws MalformedInputException { String value = "value containing spaces"; Map<String, Cookie> cookies = cookieParser.parse("name=" + value); assertThat(cookies, hasKey("name")); assertThat(cookies.get("name").getValue(), is(value)); }
@Test public void shouldReturnCookies() { Map<String, Cookie> cookies = new HashMap<>(); Cookie cookie1 = new Cookie("someName", "someValue"); Cookie cookie2 = new Cookie("someOtherName", "someOtherValue"); Cookie sessionCookie = new Cookie(HttpSessionImpl.COOKIE_NAME, "sessionId"); cookies.put("someName", cookie1); cookies.put("someOtherName", cookie2); cookies.put(HttpSessionImpl.COOKIE_NAME, sessionCookie); httpServletRequestImpl = builder.withCookies(cookies).build(); assertThat(httpServletRequestImpl.getCookies().length, is(cookies.size())); assertThat(Arrays.asList(httpServletRequestImpl.getCookies()), hasItems(cookie1, cookie2, sessionCookie)); assertThat(httpServletRequestImpl.getCookie("someName"), is(cookie1)); assertThat(httpServletRequestImpl.getCookie("someOtherName"), is(cookie2)); assertThat(httpServletRequestImpl.getCookie(HttpSessionImpl.COOKIE_NAME), is(sessionCookie)); assertThat(httpServletRequestImpl.getRequestedSessionId(), is("sessionId")); assertThat(httpServletRequestImpl.getCookie("inexistingName"), is(nullValue())); }
@Test public void shouldParseCookieHavingUrlEncodedValue() throws MalformedInputException { String value = "&<>some value"; Map<String, Cookie> cookies = cookieParser.parse("name=" + StringUtilities.urlEncode(value)); assertThat(cookies, hasKey("name")); assertThat(cookies.get("name").getValue(), is(value)); }
@Test public void shouldReturnTheSameSessionForConsecutiveCalls() { Map<String, Cookie> cookies = new HashMap<>(); Cookie sessionCookie = new Cookie(HttpSessionImpl.COOKIE_NAME, "sessionId"); cookies.put(HttpSessionImpl.COOKIE_NAME, sessionCookie); httpServletRequestImpl = builder.withCookies(cookies).withServletContext(servletContext).build(); when(servletContext.getSession("sessionId")).thenReturn(new HttpSessionImpl("sessionId", System.currentTimeMillis())); assertThat(httpServletRequestImpl.getSession(), is(instanceOf(HttpSessionImpl.class))); assertThat(httpServletRequestImpl.getSession().equals(httpServletRequestImpl.getSession()), is(true)); }
/** * {@inheritDoc} */ @Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { int pageHits = 0; if (request.getCookie(PAGE_HITS_COOKIE_NAME) != null) { pageHits = Integer.parseInt(request.getCookie(PAGE_HITS_COOKIE_NAME).getValue()); } ++pageHits; response.addCookie(new Cookie(PAGE_HITS_COOKIE_NAME, pageHits)); String firstVisitedAt; if (request.getCookie(FIRST_VISITED_AT_COOKIE_NAME) != null) { firstVisitedAt = request.getCookie(FIRST_VISITED_AT_COOKIE_NAME).getValue(); } else { firstVisitedAt = (new Date()).toString(); response.addCookie(new Cookie(FIRST_VISITED_AT_COOKIE_NAME, firstVisitedAt)); } response.getWriter().println("<p>Cookie page hits: " + pageHits + "</p>"); response.getWriter().println("<p>First visited at: " + firstVisitedAt + "</p>"); } }