CookieRenewingFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { String sessionCookieName = sessionCookieConfig.getName(); if (response.getCookies().containsKey(sessionCookieName)) { return; } if (!request.getCookies().containsKey(sessionCookieName)) { return; } Cookie requestCookie = request.getCookies().get(sessionCookieName); Optional<User> optionalUser = authenticator.authenticate(requestCookie); if (optionalUser.isPresent()) { sessionLoginResource.cookiesForUser(optionalUser.get()) .forEach(c -> response.getHeaders().add(HttpHeaders.SET_COOKIE, c)); } } @Inject  CookieRenewingFilter(@SessionCookie CookieConfig sessionCookieConfig,
      CookieAuthenticator authenticator, SessionLoginResource sessionLoginResource); @Override void filter(ContainerRequestContext request, ContainerResponseContext response);  }
@Test public void setsAllNewCookieWithValidCookie() throws Exception { User user = User.named("username"); when(request.getCookies()).thenReturn(ImmutableMap.of(SESSION_COOKIE, cookie)); when(authenticator.authenticate(cookie)).thenReturn(Optional.of(user)); NewCookie newCookie1 = new NewCookie(SESSION_COOKIE, "new session"); when(sessionLoginResource.cookiesForUser(user)) .thenReturn(ImmutableList.of(newCookie1)); filter.filter(request, response); assertThat(getCookieMap(response)).contains( entry(newCookie1.getName(), newCookie1.getValue())); }
@Test public void doesNothingWhenCookieInvalid() throws Exception { when(request.getCookies()).thenReturn(ImmutableMap.of(SESSION_COOKIE, cookie)); when(authenticator.authenticate(cookie)).thenReturn(Optional.empty()); filter.filter(request, response); assertThat(response.getHeaders()).doesNotContainKey(SET_COOKIE); }
@Test public void doesNothingWhenRequestHasNoCookies() throws Exception { when(request.getCookies()).thenReturn(ImmutableMap.of()); filter.filter(request, response); assertThat(response.getHeaders()).doesNotContainKey(SET_COOKIE); }
@Test public void doesNothingWhenResponseSetsSessionCookie() throws Exception { ImmutableMap<String, NewCookie> immutableResponseCookies = ImmutableMap.of(SESSION_COOKIE, NewCookie.valueOf(cookie.getValue())); when(response.getCookies()).thenReturn(immutableResponseCookies); filter.filter(request, response); assertThat(response.getCookies()).isSameAs(immutableResponseCookies); assertThat(response.getHeaders()).doesNotContainKey(SET_COOKIE); }