HttpSessionResolver { public HttpSession resolve(ServerSocket socket) { ServerTransport transport = socket.unwrap(ServerTransport.class); ServerWebSocket ws = transport.unwrap(ServerWebSocket.class); if (ws != null) { String key = HttpSession.class.getName(); return (HttpSession) ws.unwrap(Session.class).getUserProperties().get(key); } ServerHttpExchange http = transport.unwrap(ServerHttpExchange.class); if (http != null) { return http.unwrap(HttpServletRequest.class).getSession(false); } return null; }  HttpSession resolve(ServerSocket socket);  }
@Test public void resolveFromHttpBasedTransport() { ServerSocket socket = mock(ServerSocket.class); ServerTransport transport = mock(ServerTransport.class); when(socket.unwrap(ServerTransport.class)).thenReturn(transport); ServerHttpExchange http = mock(ServerHttpExchange.class); when(transport.unwrap(ServerHttpExchange.class)).thenReturn(http); HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); when(http.unwrap(HttpServletRequest.class)).thenReturn(httpServletRequest); HttpSession httpSession = mock(HttpSession.class); when(httpServletRequest.getSession(false)).thenReturn(httpSession); HttpSessionResolver resolver = new HttpSessionResolver(); HttpSession actualHttpSession = resolver.resolve(socket); assertThat(actualHttpSession, is(httpSession)); }
@Test public void resolveFromWebSocketTransport() { ServerSocket socket = mock(ServerSocket.class); ServerTransport transport = mock(ServerTransport.class); when(socket.unwrap(ServerTransport.class)).thenReturn(transport); ServerWebSocket ws = mock(ServerWebSocket.class); when(transport.unwrap(ServerWebSocket.class)).thenReturn(ws); Session session = mock(Session.class); when(ws.unwrap(Session.class)).thenReturn(session); Map<String, Object> userProperties = new LinkedHashMap<>(); HttpSession httpSession = mock(HttpSession.class); userProperties.put(HttpSession.class.getName(), httpSession); when(session.getUserProperties()).thenReturn(userProperties); HttpSessionResolver resolver = new HttpSessionResolver(); HttpSession actualHttpSession = resolver.resolve(socket); assertThat(actualHttpSession, is(httpSession)); }