WebUtils { @Nonnull public static Optional<SUser> retrieveUserFromWSSession(@Nonnull Session session) { DockerCloudUtils.requireNonNull(session, "Session cannot be null."); String userKey = null; List<String> params = session.getRequestParameterMap().get(USER_KEY_PARAM); if (params != null && !params.isEmpty()) { userKey = params.get(0); } if (userKey == null) { userKey = DEFAULT_USER_KEY; } Optional<HttpSession> httpSession = retrieveHttpSessionFromWSSession(session); if (!httpSession.isPresent()) { return Optional.empty(); } try { Object user = httpSession.get().getAttribute(userKey); if (user instanceof SUser) { return Optional.of((SUser) user); } } catch (IllegalStateException e) { } return Optional.empty(); } private  WebUtils(); @Nonnull static Optional<HttpSession> retrieveHttpSessionFromWSSession(@Nonnull Session session); @Nonnull static Optional<SUser> retrieveUserFromWSSession(@Nonnull Session session); static boolean isAuthorizedToRunContainerTests(@Nonnull Session session); static boolean isAuthorizedToRunContainerTests(@Nullable SUser user);  }
@Test public void retrieveUserFromWSSession() { TestSession session = new TestSession(); TestHttpSession httpSession = new TestHttpSession(); TestSUser user = new TestSUser(); session.getUserProperties().put(HttpSession.class.getName(), httpSession); httpSession.setAttribute(WebUtils.DEFAULT_USER_KEY, user); assertThat(WebUtils.retrieveUserFromWSSession(session).get()).isSameAs(user); }
@Test public void retrieveUserFromWSSessionWithNonDefaultUserKey() { TestSession session = new TestSession(); TestHttpSession httpSession = new TestHttpSession(); TestSUser user1 = new TestSUser(); TestSUser user2 = new TestSUser(); session.getUserProperties().put(HttpSession.class.getName(), httpSession); httpSession.setAttribute(WebUtils.DEFAULT_USER_KEY, user1); httpSession.setAttribute("nonDefaultUserKey", user2); session.addRequestParameter(WebUtils.USER_KEY_PARAM, "nonDefaultUserKey"); assertThat(WebUtils.retrieveUserFromWSSession(session).get()).isSameAs(user2); }
@Test public void retrieveUserFromWSSessionWithInvalidatedSession() { TestSession session = new TestSession(); TestHttpSession httpSession = new TestHttpSession(); TestSUser user = new TestSUser(); session.getUserProperties().put(HttpSession.class.getName(), httpSession); httpSession.setAttribute(WebUtils.DEFAULT_USER_KEY, user); httpSession.invalidate(); assertThat(WebUtils.retrieveUserFromWSSession(session).isPresent()).isFalse(); }
@Test public void retrieveUserFromWSSessionInvalidInput() { assertThatExceptionOfType(NullPointerException.class). isThrownBy(() -> WebUtils.retrieveUserFromWSSession(null)); }