/** * 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; } }
@Test(expected = IllegalArgumentException.class) public void shouldNotAllowIllegalName() { new Cookie(";illegal", "somevalue"); }
@Test public void shouldAllowDoubleValues() { Cookie cookie = new Cookie("someName", 22.33); assertThat(cookie.getValue(), is("22.33")); } }
@Test public void shouldAllowBooleanValues() { Cookie cookie = new Cookie("someName", true); assertThat(cookie.getValue(), is("true")); }
@Test public void shouldAllowIntValues() { Cookie cookie = new Cookie("someName", 14); assertThat(cookie.getValue(), is("14")); }
@Test public void shouldAllowLongValues() { Cookie cookie = new Cookie("someName", 1545454454544844l); assertThat(cookie.getValue(), is("1545454454544844")); }
/** * {@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>"); } }
@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 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 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)); }
@Test public void shouldSerializeCookieWithNoAttributes() { Cookie cookie = new Cookie("name", "value"); String serializedCookie = cookieHeaderSerializer.serialize(cookie); assertThat(serializedCookie, is("name=value")); }
@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 shouldSerializeCookieWithUrlEncode() { String value = "= &"; Cookie cookie = new Cookie("name", value); String serializedCookie = cookieHeaderSerializer.serialize(cookie); assertThat(serializedCookie, is("name=" + StringUtilities.urlEncode(value))); }
/** * 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")); }