java类javax.websocket.server.HandshakeRequest的实例源码

WSServerForIndexPage.java 文件源码 项目:tomcat-8-wffweb-demo-apps 阅读 27 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig config,
        HandshakeRequest request, HandshakeResponse response) {

    HttpSession httpSession = (HttpSession) request.getHttpSession();

    super.modifyHandshake(config, request, response);

    if (httpSession == null) {
        LOGGER.info("httpSession == null after modifyHandshake");
        httpSession = (HttpSession) request.getHttpSession();
    }

    if (httpSession == null) {
        LOGGER.info("httpSession == null");
        return;
    }

    config.getUserProperties().put("httpSession", httpSession);

    httpSession = (HttpSession) request.getHttpSession();
    LOGGER.info("modifyHandshake " + httpSession.getId());

}
LifecycleManager.java 文件源码 项目:gameon-room 阅读 29 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    super.modifyHandshake(sec, request, response);

    if ( token == null || token.isEmpty() ) {
        Log.log(Level.FINEST, this, "No token set for room, skipping validation");
    } else {
        Log.log(Level.FINEST, this, "Validating WS handshake");
        SignedRequestHmac wsHmac = new SignedRequestHmac("", token, "", request.getRequestURI().getRawPath());

        try {
            wsHmac.checkHeaders(new SignedRequestMap.MLS_StringMap(request.getHeaders()))
                    .verifyFullSignature()
                    .wsResignRequest(new SignedRequestMap.MLS_StringMap(response.getHeaders()));

            Log.log(Level.INFO, this, "validated and resigned", wsHmac);
        } catch(Exception e) {
            Log.log(Level.WARNING, this, "Failed to validate HMAC, unable to establish connection", e);

            response.getHeaders().replace(HandshakeResponse.SEC_WEBSOCKET_ACCEPT, Collections.emptyList());
        }
    }
}
ZeppelinEndpointConfig.java 文件源码 项目:hopsworks 阅读 32 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig config,
        HandshakeRequest request, HandshakeResponse response) {

  Map<String, List<String>> headers = request.getHeaders();
  if (headers != null && headers.containsKey(WatcherSecurityKey.HTTP_HEADER)) {
    List<String> header = headers.get(WatcherSecurityKey.HTTP_HEADER);
    if (header.size() > 0) {
      config.getUserProperties().put(WatcherSecurityKey.HTTP_HEADER, header.
              get(0));
    }
  }
  HttpSession httpSession = (HttpSession) request.getHttpSession();
  String user = request.getUserPrincipal().getName();
  config.getUserProperties().put("httpSession", httpSession);
  config.getUserProperties().put("user", user);
  logger.log(Level.INFO, "Hand shake for upgrade to websocket by: {0}", user);
}
ServletAwareConfig.java 文件源码 项目:hopsworks 阅读 32 收藏 0 点赞 0 评论 0
/**
 * Intercept the handshake operation so that we can take a hold of the
 * ServletContext instance to be able to retrieve attributes stored to it
 * such as the database object and other similar class instances
 * <p/>
 * @param config
 * @param request
 * @param response
 */
@Override
public void modifyHandshake(ServerEndpointConfig config,
        HandshakeRequest request, HandshakeResponse response) {

  HttpSession httpSession = (HttpSession) request.getHttpSession();
  ServletContext context = (ServletContext) httpSession.getServletContext();

  config.getUserProperties().put("httpSession", httpSession);
  config.getUserProperties().put("user", request.getUserPrincipal().getName());

  /*
   * store these attributes to servletContext so that they are available to
   * every created user socket session
   */
  config.getUserProperties().put("protocol", context.getAttribute("protocol"));
}
IWSControllerMonitorTest.java 文件源码 项目:ocelot 阅读 25 收藏 0 点赞 0 评论 0
/**
 * Test of handleOpenConnexion method, of class IWSControllerMonitor.
 * @throws java.lang.Exception
 */
@Test
public void testHandleOpenConnexion() throws Exception {
    System.out.println("handleOpenConnexion");
    Session session = mock(Session.class);
    EndpointConfig config = mock(EndpointConfig.class);
    HandshakeRequest handshakeRequest = mock(HandshakeRequest.class);
    HttpSession httpSession = mock(HttpSession.class);
    Map<String, Object> configProperties = mock(Map.class);

    when(config.getUserProperties()).thenReturn(configProperties);
    when(handshakeRequest.getHttpSession()).thenReturn(httpSession);
    when(httpSession.getId()).thenReturn("SESSIONID");
    when(configProperties.get(eq(Constants.HANDSHAKEREQUEST))).thenReturn(handshakeRequest);

    instance.handleOpenConnexion(session, config);

    verify(httpSessionManager).addSession(eq(session), eq("SESSIONID"));
    verify(iwse).handleOpenConnexion(eq(session), eq(config));
}
WSController.java 文件源码 项目:ocelot 阅读 24 收藏 0 点赞 0 评论 0
/**
 * Return locale of client
 *
 * @param request
 * @return
 */
Locale getLocale(HandshakeRequest request) {
    if(null != request) {
        Map<String, List<String>> headers = request.getHeaders();
        if(null != headers) {
            List<String> accepts = headers.get(HttpHeaders.ACCEPT_LANGUAGE);
            logger.debug("Get accept-language from client headers : {}", accepts);
            if (null != accepts) {
                for (String accept : accepts) {
                    try {
                        return localeExtractor.extractFromAccept(accept);
                    } catch (LocaleNotFoundException ex) {
                    }
                }
            }
        }
    }
    return Locale.US;
}
WSControllerTest.java 文件源码 项目:ocelot 阅读 26 收藏 0 点赞 0 评论 0
/**
 * Test of handleOpenConnexion method, of class WSEndpoint.
 *
 * @throws java.io.IOException
 */
@Test
public void testHandleOpenConnexionFromBrowser() throws IOException {
    System.out.println("handleOpenConnexion");
    HandshakeRequest request = mock(HandshakeRequest.class);
    EndpointConfig config = mock(EndpointConfig.class);
    Map<String, Object> map = new HashMap<>();
    map.put(Constants.HANDSHAKEREQUEST, request);
    Session session = mock(Session.class);

    when(config.getUserProperties()).thenReturn(map);
    when(session.getId()).thenReturn("WSSESSIONID");
    doNothing().when(instance).setContext(eq(request));

    instance.handleOpenConnexion(session, config);

    verify(userContextFactory).createUserContext(any(HandshakeRequest.class), eq("WSSESSIONID"));
}
IWSDecoratorTest.java 文件源码 项目:ocelot 阅读 95 收藏 0 点赞 0 评论 0
/**
 * Test of handleOpenConnexion method, of class IWSDecorator.
 * @throws java.lang.Exception
 */
@Test
public void testHandleOpenConnexion() throws Exception {
    System.out.println("handleOpenConnexion");
    Session session = mock(Session.class);
    EndpointConfig config = mock(EndpointConfig.class);
    Map map = mock(Map.class);
    HandshakeRequest request = mock(HandshakeRequest.class);
    HttpSession httpSession = mock(HttpSession.class);
    when(session.getId()).thenReturn("WSID");
    when(config.getUserProperties()).thenReturn(map);
    when(map.get(eq(Constants.HANDSHAKEREQUEST))).thenReturn(request);
    when(request.getHttpSession()).thenReturn(httpSession);
    when(httpSession.getId()).thenReturn("HTTPID");
    instance.handleOpenConnexion(session, config);
    verify(sessionManager).linkWsToHttp(eq(session), eq("HTTPID"));
    verify(iwse).handleOpenConnexion(eq(session), eq(config));
}
PrincipalToolsTest.java 文件源码 项目:ocelot 阅读 25 收藏 0 点赞 0 评论 0
/**
 * Test of getPrincipal method, of class PrincipalTools.
 */
@Test
public void testGetPrincipal_HandshakeRequest() {
    System.out.println("getPrincipal");
    HandshakeRequest handshakeRequest = mock(HandshakeRequest.class);
    Principal principal = mock(Principal.class);
    when(principal.getName()).thenReturn("FOO");
    when(handshakeRequest.getUserPrincipal()).thenReturn(null).thenReturn(principal);
    Principal result = instance.getPrincipal(handshakeRequest);
    assertThat(result).isNotNull();
    assertThat(result.getName()).isEqualTo(Constants.ANONYMOUS);

    result = instance.getPrincipal(handshakeRequest);
    assertThat(result).isEqualTo(principal);
    assertThat(result.getName()).isEqualTo("FOO");

    handshakeRequest = null;
    result = instance.getPrincipal(handshakeRequest);
    assertThat(result).isNotNull();
    assertThat(result.getName()).isEqualTo(Constants.ANONYMOUS);
}
WsUserContextTest.java 文件源码 项目:ocelot 阅读 35 收藏 0 点赞 0 评论 0
/**
 * Test of getPrincipal method, of class WsUserContext.
 */
@Test
public void testGetPrincipal() {
    System.out.println("getPrincipal");
    Principal principal = mock(Principal.class);
    PrincipalTools principalTools = mock(PrincipalTools.class);
    HandshakeRequest handshakeRequest = mock(HandshakeRequest.class);
    when(principalTools.getPrincipal(eq(handshakeRequest))).thenReturn(principal);

    WsUserContext instance = new WsUserContext(handshakeRequest);
    instance.principalTools = principalTools;

    Principal result = instance.getPrincipal();

    assertThat(result).isNotNull();
    assertThat(result).isEqualTo(principal);
}
MyApplicationConfig.java 文件源码 项目:JavaIncrementalParser 阅读 34 收藏 0 点赞 0 评论 0
@Override
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> set) {
    return new HashSet<ServerEndpointConfig>() {{
        add(ServerEndpointConfig.Builder
                .create(MyEndpoint.class, "/websocket")
                .configurator(new ServerEndpointConfig.Configurator() {

                    @Override
                    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
                        HttpSession session = (HttpSession)request.getHttpSession();
                        System.out.println("HttpSession id: " + session.getId());
                        System.out.println("HttpSession creation time: " + session.getCreationTime());
                        super.modifyHandshake(sec, request, response);
                    }

                })
                .build());
    }};
}
WebSocketConfigurator.java 文件源码 项目:jRender 阅读 37 收藏 0 点赞 0 评论 0
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
    HttpServletRequest _request = (HttpServletRequest) GenericReflection.NoThrow.getValue(_HandshakeRequest, request);
    Request _requestFaced = (Request) GenericReflection.NoThrow.getValue(Core.requestField, _request);

    MimeHeaders mime = new MimeHeaders();

    Enumeration<String> enuns = _requestFaced.getHeaderNames();
    while(enuns.hasMoreElements()){
        String param = (String) enuns.nextElement();        
        mime.addValue(param).setString(_requestFaced.getHeader(param));
    }

    Map<String, Object> properties = config.getUserProperties();

    properties.put("httpRequest", _request);
    properties.put("httpResponse", _request.getAttribute("httpResponse"));
    properties.put("httpSession", _request.getSession());
    properties.put("context", _requestFaced.getContext());
    properties.put("headers", mime);
    properties.put("remoteHost", _request.getRemoteHost());
    properties.put("localPort", _request.getLocalPort());       
    properties.put("remoteAddr", _request.getRemoteAddr());
}
SpringSecurityAuthenticationProvider.java 文件源码 项目:Ka-Websocket 阅读 32 收藏 0 点赞 0 评论 0
@Override
public String authenticate(HandshakeRequest request) throws AuthenticationException {
    SecurityContext context = SecurityContextHolder.getContext();
    if (context == null) {
        throw new AuthenticationException("User not authenticateded", "Anonymous");
    }

    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        throw new AuthenticationException("User not authenticateded", "Anonymous");
    }
    if (authentication.isAuthenticated()) {
        return authentication.getName();
    } else {
        throw new AuthenticationException("User not authenticateded", authentication.getName());
    }
}
ClientChannelImpl.java 文件源码 项目:Ka-Websocket 阅读 25 收藏 0 点赞 0 评论 0
@Override
public String authenticate(AuthenticationProvider provider, HandshakeRequest request) throws AuthenticationException {
    AuthenticationProvider auth = resolveAuthenticationProvider(provider);
    if (auth != null) {
        try {
            String username = auth.authenticate(request);
            fireAuthentication(username, request, null);
            return username;
        } catch(AuthenticationException ae) {
            LOG.warn("Unauthorized access by " + ae.getUsername() + " : " +ae.getMessage());
            fireAuthentication(ae.getUsername(), request, ae);
            throw ae;
        }    

    }
    return null;

}
ClientIdGeneratorImpl.java 文件源码 项目:Ka-Websocket 阅读 29 收藏 0 点赞 0 评论 0
@Override
public String getId(HandshakeRequest request,
                    ClientChannel manager) {
    String clientId = getIdValue(request);

    if (manager.hasClient(clientId)) {
        clientId = clientId + "-" + getUuid();
    }
    if (clientId == null) {
        clientId = getUuid();
    }



    return clientId;
}
HttpSessionConfigurator.java 文件源码 项目:OftenPorter 阅读 35 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig sec,
        HandshakeRequest request, HandshakeResponse response)
{
    HttpSession httpSession = (HttpSession) request.getHttpSession();
    sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
HttpChatSessionConfigurator.java 文件源码 项目:belling-admin 阅读 30 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
    HttpSession httpSession = (HttpSession) request.getHttpSession();
    if (null != httpSession) {
        config.getUserProperties().put(HttpSession.class.getName(), httpSession);
    }
}
HttpSessionConfigurator.java 文件源码 项目:websocket-http-session 阅读 33 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    System.out.println("modifyHandshake() Current thread " + Thread.currentThread().getName());
    String user = request.getParameterMap().get("user").get(0);
    sec.getUserProperties().put(user, request.getHttpSession());
    System.out.println("modifyHandshake() User " + user + " with http session ID " + ((HttpSession) request.getHttpSession()).getId());
}
WebSocketConfigurator.java 文件源码 项目:cito 阅读 31 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    final HttpSession httpSession = (HttpSession) request.getHttpSession();
    if (request.getUserPrincipal() == null) {
        return;
    }

    final SecurityContext securityCtx = new WebSocketSecurityContext(request);
    sec.getUserProperties().put(key(httpSession.getId()), securityCtx);
}
RestrictedGuacamoleWebSocketTunnelEndpoint.java 文件源码 项目:guacamole-client 阅读 26 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig config,
        HandshakeRequest request, HandshakeResponse response) {

    super.modifyHandshake(config, request, response);

    // Store tunnel request and tunnel request service for retrieval
    // upon WebSocket open
    Map<String, Object> userProperties = config.getUserProperties();
    userProperties.clear();
    userProperties.put(TUNNEL_REQUEST_PROPERTY, new WebSocketTunnelRequest(request));
    userProperties.put(TUNNEL_REQUEST_SERVICE_PROPERTY, tunnelRequestServiceProvider.get());

}
Channels.java 文件源码 项目:symphonyx 阅读 28 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(final ServerEndpointConfig config,
        final HandshakeRequest request, final HandshakeResponse response) {
    final HttpSession httpSession = (HttpSession) request.getHttpSession();

    config.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
WebsocketSecurityConfigurator.java 文件源码 项目:jboss-security-extended 阅读 28 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    final Principal principal = request.getUserPrincipal();
    final Subject subject = SecurityActions.getSubject();
    final Object credential = SecurityActions.getCredential();

    sec.getUserProperties().put(WebsocketSecurityInterceptor.SESSION_PRINCIPAL, principal);
    sec.getUserProperties().put(WebsocketSecurityInterceptor.SESSION_SUBJECT, subject);
    sec.getUserProperties().put(WebsocketSecurityInterceptor.SESSION_CREDENTIAL, credential);
}
SessionConfigurator.java 文件源码 项目:bootstrap-quickstart 阅读 27 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
    HttpSession session = (HttpSession) request.getHttpSession();
    if (null != session) {
        config.getUserProperties().put("demo", 1L);
    }
}
ServerContainerInitializeListener.java 文件源码 项目:che 阅读 29 收藏 0 点赞 0 评论 0
private Configurator createConfigurator() {
  return new Configurator() {
    @Override
    public void modifyHandshake(
        ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
      super.modifyHandshake(sec, request, response);
      final HttpSession httpSession = (HttpSession) request.getHttpSession();
      if (httpSession != null) {
        sec.getUserProperties().put(HTTP_SESSION_ATTRIBUTE, httpSession);
      }
      sec.getUserProperties().put(SECURITY_CONTEXT, createSecurityContext(request));
      sec.getUserProperties().put(ENVIRONMENT_CONTEXT, EnvironmentContext.getCurrent());
    }
  };
}
ServerContainerInitializeListener.java 文件源码 项目:che 阅读 31 收藏 0 点赞 0 评论 0
protected SecurityContext createSecurityContext(final HandshakeRequest req) {
  final boolean isSecure = false; // todo: get somehow from request
  final String authType = "BASIC";
  final Subject subject = EnvironmentContext.getCurrent().getSubject();

  final Principal principal = new SimplePrincipal(subject.getUserName());
  return new SecurityContext() {

    @Override
    public Principal getUserPrincipal() {
      return principal;
    }

    @Override
    public boolean isUserInRole(String role) {
      return false;
    }

    @Override
    public boolean isSecure() {
      return isSecure;
    }

    @Override
    public String getAuthenticationScheme() {
      return authType;
    }
  };
}
AngularBeansServletContextListener.java 文件源码 项目:AngularBeans 阅读 27 收藏 0 点赞 0 评论 0
private ServerEndpointConfig.Configurator configuratorFor(final String prefix, final boolean isRaw) {
    return new ServerEndpointConfig.Configurator() {

        @Override
        public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
            try {
                return endpointClass.getConstructor(SockJsServer.class, String.class, String.class)
                        .newInstance(sockJsServer, context.getContextPath(), prefix);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request,
                HandshakeResponse response) {
            if (isRaw) {
                // We have no reliable key (like session id) to save
                // headers with for raw websocket requests
                return;
            }
            String path = request.getRequestURI().getPath();
            Matcher matcher = SESSION_PATTERN.matcher(path);
            if (matcher.matches()) {
                String sessionId = matcher.group(1);
                saveHeaders(sessionId, request.getHeaders());
            }
        }
    };
}
GetHttpSessionConfigurator.java 文件源码 项目:AngularBeans 阅读 31 收藏 0 点赞 0 评论 0
@Override
public void modifyHandshake(ServerEndpointConfig config,
        HandshakeRequest request, HandshakeResponse response) {
    HttpSession httpSession = (HttpSession) request.getHttpSession();
    config.getUserProperties()
            .put(HttpSession.class.getName(), httpSession);
}
SockJsServlet.java 文件源码 项目:AngularBeans 阅读 29 收藏 0 点赞 0 评论 0
private ServerEndpointConfig.Configurator configuratorFor(final String prefix, final boolean isRaw) {
    return new ServerEndpointConfig.Configurator() {

        @Override
        public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
            try {
                return endpointClass.getConstructor(SockJsServer.class, String.class, String.class)
                        .newInstance(sockJsServer, getServletContext().getContextPath(), prefix);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request,
                HandshakeResponse response) {

            if (isRaw) {
                // We have no reliable key (like session id) to save
                // headers with for raw websocket requests
                return;
            }

            String path = request.getRequestURI().getPath();
            Matcher matcher = SESSION_PATTERN.matcher(path);
            if (matcher.matches()) {
                String sessionId = matcher.group(1);
                saveHeaders(sessionId, request.getHeaders());
            }
        }
    };
}
ServerContext.java 文件源码 项目:firefly 阅读 31 收藏 0 点赞 0 评论 0
public static final RequestAgent getWsRequestAgent(HandshakeRequest request, HandshakeResponse response) {
    // this is an abstraction point.  this class can be loaded from configuration.
    if (request instanceof HttpServletRequest) {
        return new RequestAgent.HTTP((HttpServletRequest) request, (HttpServletResponse) response);
    } else {
        return null;
    }
}
IWSControllerMonitor.java 文件源码 项目:ocelot 阅读 24 收藏 0 点赞 0 评论 0
@Override
public void handleOpenConnexion(Session session, EndpointConfig config) throws IOException {
    logger.debug("Decorate websocket, open connexion '{}'", session.getId());
    Map<String, Object> configProperties = config.getUserProperties();
    HandshakeRequest request = (HandshakeRequest) configProperties.get(Constants.HANDSHAKEREQUEST);
    httpSessionManager.addSession(session, ((HttpSession) request.getHttpSession()).getId());
    iwse.handleOpenConnexion(session, config);
}


问题


面经


文章

微信
公众号

扫码关注公众号