ServletContextImpl implements ServletContext { 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); } ServletContextImpl(final String contextPath,
                              final List<ServletMapping> servletMappings,
                              final List<FilterMapping> filterMappings,
                              final Map<String, Object> attributes,
                              final ServerConfig serverConfig,
                              final SessionStorage sessionStorage); @Override String getMimeType(final String file); @Override void setAttribute(final String name, final Object value); @Override Object getAttribute(final String name); @Override Enumeration getAttributeNames(); HttpSessionImpl getSession(final String id); HttpSessionImpl createNewSession(); void handleSession(final HttpSessionImpl session, final HttpServletResponseImpl response); @Override List<ServletMapping> getServletMappings(); @Override List<FilterMapping> getFilterMappings(); @Override String getContextPath(); static final int MAX_AGE_IN_PAST; }
@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."); }