/** * * @param context the context to add the web socket endpoints to * @param rtEventResource The instance of the websocket endpoint to return * @throws DeploymentException */ private static void setWebSocketEndpoints(ServletContextHandler context, EventsResource rtEventResource) throws DeploymentException, ServletException { ServerContainer wsContainer = WebSocketServerContainerInitializer.configureContext(context); ServerEndpointConfig serverConfig = ServerEndpointConfig.Builder .create(EventsResource.class, EventsResource.RT_EVENT_ENDPOINT) .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(rtEventResource); } }).build(); wsContainer.addEndpoint(serverConfig); }
public static void configureEndpoint(String endpointPath, Class endpointClass, Class handshakeHandlerClass, LuceeApp app) throws ClassNotFoundException, IllegalAccessException, InstantiationException, DeploymentException, PageException { ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(endpointClass, endpointPath).configurator( (ServerEndpointConfig.Configurator) handshakeHandlerClass.newInstance()).build(); try { ServerContainer serverContainer = (ServerContainer) app.getServletContext().getAttribute( "javax.websocket.server.ServerContainer"); serverContainer.addEndpoint(serverEndpointConfig); } catch (DeploymentException ex) { app.log(Log.LEVEL_DEBUG, "Failed to register endpoint " + endpointPath + ": " + ex.getMessage(), app.getName(), "websocket"); } // System.out.println(Configurator.class.getName() + " >>> exit configureEndpoint()"); }
@Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( Bug58624ServerEndpoint.class, PATH).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( TesterEchoServer.Basic.class, "/{param}").build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Test public void testSpecExample3() throws Exception { WsServerContainer sc = new WsServerContainer(new TesterServletContext()); ServerEndpointConfig configA = ServerEndpointConfig.Builder.create( Object.class, "/a/{var}/c").build(); ServerEndpointConfig configB = ServerEndpointConfig.Builder.create( Object.class, "/a/b/c").build(); ServerEndpointConfig configC = ServerEndpointConfig.Builder.create( Object.class, "/a/{var1}/{var2}").build(); sc.addEndpoint(configA); sc.addEndpoint(configB); sc.addEndpoint(configC); Assert.assertEquals(configB, sc.findMapping("/a/b/c").getConfig()); Assert.assertEquals(configA, sc.findMapping("/a/d/c").getConfig()); Assert.assertEquals(configC, sc.findMapping("/a/x/y").getConfig()); }
@Test public void testDuplicatePaths_04() throws Exception { WsServerContainer sc = new WsServerContainer(new TesterServletContext()); ServerEndpointConfig configA = ServerEndpointConfig.Builder.create( Object.class, "/a/{var1}/{var2}").build(); ServerEndpointConfig configB = ServerEndpointConfig.Builder.create( Object.class, "/a/b/{var2}").build(); sc.addEndpoint(configA); sc.addEndpoint(configB); Assert.assertEquals(configA, sc.findMapping("/a/x/y").getConfig()); Assert.assertEquals(configB, sc.findMapping("/a/b/y").getConfig()); }
@Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); List<Class<? extends Encoder>> encoders = new ArrayList<Class<? extends Encoder>>(); encoders.add(Bug58624Encoder.class); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( Bug58624Endpoint.class, PATH).encoders(encoders).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce .getServletContext() .getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( getEndpointClass(), PATH).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(ServerEndpointConfig.Builder.create( ConstantTxEndpoint.class, PATH).build()); if (TestWsWebSocketContainer.timeoutOnContainer) { sc.setAsyncSendTimeout(TIMEOUT_MS); } } catch (DeploymentException e) { throw new IllegalStateException(e); } }
@Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) { Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>(); if (scanned.contains(EchoEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( EchoEndpoint.class, "/websocket/echoProgrammatic").build()); } if (scanned.contains(DrawboardEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( DrawboardEndpoint.class, "/websocket/drawboard").build()); } return result; }
@Override public void onOpen(Session session, EndpointConfig endpointConfig) { ServerEndpointConfig sec = (ServerEndpointConfig) endpointConfig; Object pojo; try { pojo = sec.getConfigurator().getEndpointInstance(sec.getEndpointClass()); } catch (InstantiationException e) { throw new IllegalArgumentException( sm.getString("pojoEndpointServer.getPojoInstanceFail", sec.getEndpointClass().getName()), e); } setPojo(pojo); @SuppressWarnings("unchecked") Map<String, String> pathParameters = (Map<String, String>) sec.getUserProperties().get(POJO_PATH_PARAM_KEY); setPathParameters(pathParameters); PojoMethodMapping methodMapping = (PojoMethodMapping) sec.getUserProperties().get(POJO_METHOD_MAPPING_KEY); setMethodMapping(methodMapping); doOnOpen(session, endpointConfig); }
@Override public void contextInitialized(final ServletContextEvent servletContextEvent) { super.contextInitialized(servletContextEvent); final ServerContainer serverContainer = (ServerContainer) servletContextEvent.getServletContext() .getAttribute("javax.websocket.server.ServerContainer"); if (serverContainer != null) { try { serverContainer.addEndpoint(ServerEndpointConfig.Builder .create(SubscriptionEndpoint.class, "/ContextManager/{" + PATH_NAME + "}").build()); // serverContainer.addEndpoint(ServerEndpointConfig.Builder // .create(ExtendedSubscriptionEndpoint.class, // "/ContextManager/{contextParticipantId}") // .configurator(new WebSocketsConfigurator()).build()); } catch (final DeploymentException e) { throw new RuntimeException(e.getMessage(), e); } } }
protected void addEndpoint(final Class<?> cls) { final ServerContainer container = getServerContainer(); if (container == null) { LOG.warn("ServerContainer is null. Skip registration of websocket endpoint {}", cls); return; } try { LOG.debug("Register endpoint {}", cls); final ServerEndpointConfig config = createEndpointConfig(cls); container.addEndpoint(config); } catch (final DeploymentException e) { addError(e); } }
/** * Actually register the endpoints. Called by {@link #afterSingletonsInstantiated()}. */ protected void registerEndpoints() { Set<Class<?>> endpointClasses = new LinkedHashSet<Class<?>>(); if (this.annotatedEndpointClasses != null) { endpointClasses.addAll(this.annotatedEndpointClasses); } ApplicationContext context = getApplicationContext(); if (context != null) { String[] endpointBeanNames = context.getBeanNamesForAnnotation(ServerEndpoint.class); for (String beanName : endpointBeanNames) { endpointClasses.add(context.getType(beanName)); } } for (Class<?> endpointClass : endpointClasses) { registerEndpoint(endpointClass); } if (context != null) { Map<String, ServerEndpointConfig> endpointConfigMap = context.getBeansOfType(ServerEndpointConfig.class); for (ServerEndpointConfig endpointConfig : endpointConfigMap.values()) { registerEndpoint(endpointConfig); } } }
@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()); }
@Override public void run(AppConfiguration configuration, Environment environment) throws Exception { /* Configure WebSockets */ ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(WebCrawlerEndpoint.class, "/webCrawler").build(); serverEndpointConfig.getUserProperties().put("config", configuration.webCrawler); websocketBundle.addEndpoint(serverEndpointConfig); final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); /* Configure CORS parameters */ cors.setInitParameter("allowedOrigins", "*"); cors.setInitParameter("allowedHeaders", "*"); cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD"); cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); environment.healthChecks().register("dummy", new DummyHealthCheck()); }
@Override public void run(IntegrationConfiguration configuration, Environment environment) throws Exception { //Annotated endpoint websocket.addEndpoint(PingPongServerEndpoint.class); //programmatic endpoint ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(ProgrammaticServerEndpoint.class, "/programmatic").build(); websocket.addEndpoint(serverEndpointConfig); // healthcheck to keep output quiet environment.healthChecks().register("healthy", new HealthCheck() { @Override protected Result check() throws Exception { return Result.healthy(); } }); initLatch.countDown(); }
@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()); } } }
private Set<ServerEndpointConfig> registerRooms(Collection<Room> rooms) { Set<ServerEndpointConfig> endpoints = new HashSet<ServerEndpointConfig>(); for (Room room : rooms) { RoomRegistrationHandler roomRegistration = new RoomRegistrationHandler(room, systemId, registrationSecret); try{ roomRegistration.performRegistration(); }catch(Exception e){ Log.log(Level.SEVERE, this, "Room Registration FAILED", e); //we keep running, maybe we were registered ok before... } //now regardless of our registration, open our websocket. SessionRoomResponseProcessor srrp = new SessionRoomResponseProcessor(); ServerEndpointConfig.Configurator config = new RoomWSConfig(room, srrp, roomRegistration.getToken()); endpoints.add(ServerEndpointConfig.Builder.create(RoomWS.class, "/ws/" + room.getRoomId()) .configurator(config).build()); } return endpoints; }
@Override protected void startServer(int port, final Action<ServerWebSocket> websocketAction) throws Exception { server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(port); server.addConnector(connector); ServletContextHandler handler = new ServletContextHandler(); server.setHandler(handler); ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler); ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class, TEST_URI) .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(new AsityServerEndpoint().onwebsocket(websocketAction)); } }) .build(); container.addEndpoint(config); server.start(); }
protected ServerEndpointConfig createWsServerEndpointConfig(ServletContext servletContext) { final List<Class<? extends Encoder>> encoders = new LinkedList<>(); final List<Class<? extends Decoder>> decoders = new LinkedList<>(); encoders.add(OutputMessageEncoder.class); decoders.add(InputMessageDecoder.class); final ServerEndpointConfig endpointConfig = create(CheWSConnection.class, websocketContext + websocketEndPoint) .configurator(createConfigurator()) .encoders(encoders) .decoders(decoders) .build(); endpointConfig .getUserProperties() .put(EVERREST_PROCESSOR_ATTRIBUTE, getEverrestProcessor(servletContext)); endpointConfig .getUserProperties() .put(EVERREST_CONFIG_ATTRIBUTE, getEverrestConfiguration(servletContext)); endpointConfig.getUserProperties().put(EXECUTOR_ATTRIBUTE, createExecutor(servletContext)); return endpointConfig; }
protected ServerEndpointConfig createEventbusServerEndpointConfig(ServletContext servletContext) { final List<Class<? extends Encoder>> encoders = new LinkedList<>(); final List<Class<? extends Decoder>> decoders = new LinkedList<>(); encoders.add(OutputMessageEncoder.class); decoders.add(InputMessageDecoder.class); final ServerEndpointConfig endpointConfig = create(CheWSConnection.class, websocketContext + eventBusEndPoint) .configurator(createConfigurator()) .encoders(encoders) .decoders(decoders) .build(); endpointConfig .getUserProperties() .put(EVERREST_PROCESSOR_ATTRIBUTE, getEverrestProcessor(servletContext)); endpointConfig .getUserProperties() .put(EVERREST_CONFIG_ATTRIBUTE, getEverrestConfiguration(servletContext)); endpointConfig.getUserProperties().put(EXECUTOR_ATTRIBUTE, createExecutor(servletContext)); return endpointConfig; }
@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); }
/** * 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")); }
@Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) { Set<ServerEndpointConfig> result = new HashSet<>(); // Endpoint subclass config if (scanned.contains(MyEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( MyEndpoint.class, "/MyEndpoint").build()); } if (scanned.contains(GameEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( GameEndpoint.class, "/Game").build()); } return result; }
@Override public void contextInitialized(ServletContextEvent sce) { // initialize DiqubeServletConfig WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext()); ctx.getBean(DiqubeServletConfig.class).initialize(sce.getServletContext()); // register our Websocket Endpoint ServerContainer serverContainer = (ServerContainer) sce.getServletContext().getAttribute(ATTR_SERVER_CONTAINER); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(WebSocketEndpoint.class, WebSocketEndpoint.ENDPOINT_URL_MAPPING).build(); sec.getUserProperties().put(WebSocketEndpoint.PROP_BEAN_CONTEXT, ctx); try { serverContainer.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException("DeploymentException when deploying Websocket endpoint", e); } }
@Override public EventDriver create(Object websocket, WebSocketPolicy policy) { if (!(websocket instanceof EndpointInstance)) { throw new IllegalStateException(String.format("Websocket %s must be an %s",websocket.getClass().getName(),EndpointInstance.class.getName())); } EndpointInstance ei = (EndpointInstance)websocket; JsrEndpointEventDriver driver = new InstJsrEndpointEventDriver(policy, ei, metrics); ServerEndpointConfig config = (ServerEndpointConfig)ei.getConfig(); if (config instanceof PathParamServerEndpointConfig) { PathParamServerEndpointConfig ppconfig = (PathParamServerEndpointConfig)config; driver.setPathParameters(ppconfig.getPathParamMap()); } return driver; }
@Override public void run(Configuration configuration, Environment environment) throws InvalidKeySpecException, NoSuchAlgorithmException, ServletException, DeploymentException { environment.lifecycle().addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() { @Override public void lifeCycleStarted(LifeCycle event) { cdl.countDown(); } }); environment.jersey().register(new MyResource()); environment.healthChecks().register("alive", new HealthCheck() { @Override protected HealthCheck.Result check() throws Exception { return HealthCheck.Result.healthy(); } }); // Using ServerEndpointConfig lets you inject objects to the websocket endpoint: final ServerEndpointConfig config = ServerEndpointConfig.Builder.create(EchoServer.class, "/extends-ws").build(); // config.getUserProperties().put(Environment.class.getName(), environment); // Then you can get it from the Session object // - obj = session.getUserProperties().get("objectName"); websocketBundle.addEndpoint(config); }