@Test public void shouldNotHandleSessionOnTerminateIfSessionExists() throws IOException { when(request.getSession(false)).thenReturn(null); servletResourceProvider.load("/", request, response); verify(servletContext, times(0)).handleSession(any(HttpSessionImpl.class), any(HttpServletResponseImpl.class)); }
@Test public void shouldHandleSessionOnTerminateIfSessionExists() throws IOException { when(request.getSession(false)).thenReturn(new HttpSessionImpl("1", System.currentTimeMillis())); servletResourceProvider.load("/", request, response); verify(servletContext, times(1)).handleSession(any(HttpSessionImpl.class), any(HttpServletResponseImpl.class)); }
@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."); }
/** * Terminates servlet. Sets all necessary headers, flushes content. * * @param request * @param response * @throws IOException */ private void terminate(final HttpServletRequestImpl request, final HttpServletResponseImpl response) throws IOException { freeUploadedUnprocessedFiles(request.getUploadedFiles()); HttpSessionImpl session = (HttpSessionImpl) request.getSession(false); if (session != null) { try { ((ServletContextImpl) request.getServletContext()).handleSession(session, response); } catch (IOException e) { LOGGER.log(Level.WARNING, "Unable to persist session", e); } } if (!response.isCommitted()) { if (response.getContentType() == null) { response.setContentType(DEFAULT_RESPONSE_CONTENT_TYPE); } response.getHeaders().setHeader(Headers.HEADER_CACHE_CONTROL, HEADER_VALUE_NO_CACHE); response.getHeaders().setHeader(Headers.HEADER_PRAGMA, HEADER_VALUE_NO_CACHE); } response.flush(); }