/** * * @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 void subscribe(String sparql,String alias,String jwt,NotificationHandler handler) throws IOException, URISyntaxException { this.handler = handler; this.sparql = sparql; this.alias = alias; this.jwt = jwt; if (!isConnected()) try { connect(); } catch (DeploymentException e) { throw new IOException(e.getMessage()); } else sendSubscribeRequest(); //Start watchdog if (watchDog == null) watchDog = new WebsocketWatchdog(handler,this,sparql); }
public void unsubscribe(String spuid,String jwt) throws IOException, URISyntaxException { logger.debug("unsubscribe"); if (!isConnected()) try { connect(); } catch (DeploymentException e) { throw new IOException(e.getMessage()); } JsonObject request = new JsonObject(); if (spuid != null) request.add("unsubscribe", new JsonPrimitive(spuid)); if (jwt != null) request.add("authorization", new JsonPrimitive(jwt)); wsClientSession.getBasicRemote().sendText(request.toString()); }
private synchronized boolean subscribing() throws DeploymentException, IOException, URISyntaxException { logger.debug("Subscribing..."); if (wsClient == null) { logger.warn("Websocket client is null"); return false; } while(state == SUBSCRIPTION_STATE.BROKEN_SOCKET) { if (wsClient.isConnected()) wsClient.close(); wsClient.subscribe(sparql,alias,token,handler); try { wait(DEFAULT_SUBSCRIPTION_DELAY); } catch (InterruptedException e) { } } return (state == SUBSCRIPTION_STATE.SUBSCRIBED); }
public static void main(String[] args) throws FileNotFoundException, NoSuchElementException, IOException, DeploymentException, URISyntaxException { ApplicationProfile profile = new ApplicationProfile("GarbageCollector.jsap"); chatServer = new GarbageCollector(profile,"GARBAGE","REMOVE"); if (chatServer.subscribe(null) == null) return; logger.info("Up and running"); logger.info("Press any key to exit..."); try { System.in.read(); } catch (IOException e) { logger.debug(e.getMessage()); } }
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()"); }
private int parseStatus(String line) throws DeploymentException { // This client only understands HTTP 1. // RFC2616 is case specific String[] parts = line.trim().split(" "); // CONNECT for proxy may return a 1.0 response if (parts.length < 2 || !("HTTP/1.0".equals(parts[0]) || "HTTP/1.1".equals(parts[0]))) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.invalidStatus", line)); } try { return Integer.parseInt(parts[1]); } catch (NumberFormatException nfe) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.invalidStatus", line)); } }
@Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(Async.class); sc.addEndpoint(Basic.class); sc.addEndpoint(BasicLimitLow.class); sc.addEndpoint(BasicLimitHigh.class); sc.addEndpoint(RootEcho.class); } catch (DeploymentException e) { throw new IllegalStateException(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( 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); } }
@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); } }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointInvalidScheme() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ftp://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); }
@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); } }
public WebsocketClient(String uri, final String sessionID, MessageHandler.Whole<String> messageHandler) throws IOException { // add session ID so the request gets through LAMS security Builder configBuilder = ClientEndpointConfig.Builder.create(); configBuilder.configurator(new Configurator() { @Override public void beforeRequest(Map<String, List<String>> headers) { headers.put("Cookie", Arrays.asList("JSESSIONID=" + sessionID)); } }); ClientEndpointConfig clientConfig = configBuilder.build(); this.websocketEndpoint = new WebsocketEndpoint(messageHandler); WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { container.connectToServer(websocketEndpoint, clientConfig, new URI(uri)); } catch (DeploymentException | URISyntaxException e) { throw new IOException("Error while connecting to websocket server", e); } }
@Test public void newJoineeGetsWelcomeMsg() throws DeploymentException, IOException, InterruptedException { controlLatch = new CountDownLatch(2); ChatClient newJoinee = new ChatClient(); String newJoineeName = "abhishek"; String endpointURL = BASE_SERVER_URL + newJoineeName + "/"; WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.connectToServer(newJoinee, ClientEndpointConfig.Builder.create().build(), URI.create(endpointURL)); assertTrue(controlLatch.await(5, TimeUnit.SECONDS)); String expectedWelcomeMessage = "Welcome " + newJoineeName; assertTrue(newJoinee.getResponse().contains(expectedWelcomeMessage)); newJoinee.closeConnection(); }
public void connect(long timeout, TimeUnit unit) throws DeploymentException, IOException, EncodeException, InterruptedException, ExecutionException, TimeoutException { if (getState() != State.DISCONNECTED) { throw new IllegalStateException("Connection open, or in progress!"); } this.session = ContainerProvider.getWebSocketContainer().connectToServer(this, this.uri); this.state = State.CONNECTING; final Frame connectFrame = Frame.connect(this.uri.getHost(), "1.2").heartbeat(5_000, 5_000).build(); sendToClient(connectFrame); this.connectFuture = new CompletableFuture<>(); final Frame connectedFrame = this.connectFuture.get(timeout, unit); this.connectFuture = null; final long readDelay = Math.max(connectedFrame.heartBeat().get().x, connectFrame.heartBeat().get().y); final long writeDelay = Math.max(connectFrame.heartBeat().get().x, connectedFrame.heartBeat().get().y); this.heartBeatMonitor.start(readDelay, writeDelay); }
/** * Sends message to the WebSocket server. * * @param endpoint The server endpoint * @param msg The message * @return a return message */ private String sendMessage(String endpoint, String msg) { LOGGER.config(() -> "Sending message: " + msg); String returnValue = "-1"; try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = serviceUrl + endpoint; Session session = container.connectToServer(this, URI.create(uri)); session.getBasicRemote().sendText(msg != null ? msg : ""); returnValue = session.getId(); session.close(); } catch (DeploymentException | IOException ex) { LOGGER.warning(ex.getMessage()); } return returnValue; }
@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); } }
@Override public Object createdEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider, WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException { DirectFieldAccessor accessor = new DirectFieldAccessor(engine); Object sessionListener = accessor.getPropertyValue("sessionListener"); Object clusterContext = accessor.getPropertyValue("clusterContext"); try { if (constructorWithBooleanArgument) { // Tyrus 1.11+ return constructor.newInstance(registration.getEndpoint(), registration, provider, container, "/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE); } else { return constructor.newInstance(registration.getEndpoint(), registration, provider, container, "/", registration.getConfigurator(), sessionListener, clusterContext, null); } } catch (Exception ex) { throw new HandshakeFailureException("Failed to register " + registration, ex); } }
/** * Connects the current agent to a server. * * @param serverAddress * - address of the agent we want to connect to. * @param webSocketPort * - the port number, on which the Server is listening * @param agentId * - An identifier of the current agent * @throws URISyntaxException * - thrown to indicate that a string could not be parsed as a URI reference * @throws IOException * - thrown when I/O exception of some sort has occurred * @throws DeploymentException * - failure to publish an endpoint on its server, or a failure to connect a client to its server */ public void connectToServer(String serverAddress, int webSocketPort, String agentId) throws DeploymentException, IOException, URISyntaxException { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.setDefaultMaxTextMessageBufferSize(Integer.MAX_VALUE); String uriAddress = String.format(SERVER_URI, serverAddress, webSocketPort); this.session = container.connectToServer(AgentEndpoint.class, new URI(uriAddress)); List<DeviceInformation> connectedDevicesInformation = deviceManager.getDevicesInformation(); DeviceInformation[] devicesInformationArray = connectedDevicesInformation.toArray(new DeviceInformation[0]); RequestMessage registerAgentRequest = new RequestMessage(MessageAction.REGISTER_AGENT, agentId, devicesInformationArray); String registerAgentJsonRequest = jsonUtil.serialize(registerAgentRequest); sendText(registerAgentJsonRequest, session); LOGGER.debug("Connected to server address: " + uriAddress); agentManager.registerServer(); LOGGER.info("The Server(" + serverAddress + ":" + webSocketPort + ") is registered for the device changed event notifications."); }
/** * Creates a new {@link ComputeRealtimeServer} * * @param config * The chatalytics config * @return A newly created {@link ComputeRealtimeServer} */ public ComputeRealtimeServer createComputeRealtimeServer() { Server server = new Server(config.computeConfig.rtComputePort); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*"); jerseyServlet.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, StatusResource.class.getPackage().toString()); server.setHandler(context); ServerContainer wscontainer; try { wscontainer = WebSocketServerContainerInitializer.configureContext(context); wscontainer.addEndpoint(RealtimeResource.class); } catch (ServletException | DeploymentException e) { throw new RuntimeException("Can't instantiate websocket. Reason: " + e.getMessage()); } return new ComputeRealtimeServer(server); }
/** * Starts the WebSocket server on the address and port from the config file. * * @param serverAddress * - an IP address for the WebSocket connection * @param websocketPort * - a port for the WebSocket connection */ public void startWebSocketServer(String serverAddress, int websocketPort) { server = new org.glassfish.tyrus.server.Server(serverAddress, websocketPort, null, null, ClientServerEndpoint.class, ServerAgentEndpoint.class); LOGGER.info("Websocket Server started on port " + websocketPort); try { server.start(); } catch (DeploymentException e) { LOGGER.error("Could not start WebSocket server.", e); } }
@Test(timeout = 0) public void testSessions() throws DeploymentException, IOException, InterruptedException{ Thread.sleep(500); assertTrue(WebsocketServer.isRunning()); WebsocketClient client = new WebsocketClient("ws://localhost:8787/websocket"); WebsocketClient client2 = new WebsocketClient("ws://localhost:8787/websocket"); WebsocketClient client3 = new WebsocketClient("ws://localhost:8787/websocket"); WebsocketClient client4 = new WebsocketClient("ws://localhost:8787/websocket"); int actualClients = WebsocketServer.getSessions().size(); assertSame(actualClients, 4 * 2); //why *2? every client is added twice to session list (server and client connection). client.close(); client2.close(); client3.close(); client4.close(); Thread.sleep(200); actualClients = WebsocketServer.getSessions().size(); assertSame(actualClients, 0); }
@Test @InSequence(2) public void testNotificationWhenBecameAWriter() throws URISyntaxException, DeploymentException, IOException, InterruptedException { final String writer = "@mgreau"; final String JSONNotificationWhenBecameAWriter = "{\"type\":\"notification\",\"adocId\":\"" + ADOC_ID + "\",\"data\":{\"nbConnected\":0,\"nbWriters\":1,\"writers\":{\"" + writer + "\":\"" + writer + "\"}}}"; // notifOnOpen - notifWhenSend Adoc - output MyBasicEndpointClient endpoint = new MyBasicEndpointClient(); Session session = connectToServer(MyBasicEndpointClient.class, ADOC_URL + ADOC_ID); assertNotNull(session); session.getBasicRemote().sendText(dataConvertToPDF); await().timeout(50000, TimeUnit.MILLISECONDS).untilCall(to(endpoint).getNotificationMessage(), is(equalTo(JSONNotificationWhenBecameAWriter))); }
public static void connect(String clientString) throws IOException { if (clientString.startsWith(NEW_CLIENT) ) { clientString = clientString.substring(NEW_CLIENT.length()); WebSocketContainer c = ContainerProvider.getWebSocketContainer(); Hello.log(AnnotatedClientEndpoint.class, "Starting the client for " + clientString); URI uriServerEP = URI.create(clientString); try { Session s = c.connectToServer(AnnotatedClientEndpoint.class, uriServerEP); // we're just going to maintain one client at a time, so reading the output // can be somewhat sane.. Set the new session, and close the old one. s = clientConnection.getAndSet(s); if ( s != null ) s.close(); } catch (DeploymentException e) { e.printStackTrace(); } } }
/** * Sends message to the WebSocket server. * * @param endpoint The server endpoint * @param msg The message * @return a return message */ private String sendMessage(String endpoint, String msg) { LOGGER.config(() -> "Sending message: " + msg); String returnValue = "-1"; try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = serviceUrl + endpoint; Session session = container.connectToServer(this, URI.create(uri)); session.getBasicRemote().sendText(msg != null ? msg : ""); returnValue = session.getId(); } catch (DeploymentException | IOException ex) { LOGGER.warning(ex.getMessage()); } return returnValue; }
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext context = servletContextEvent.getServletContext(); final ServerContainer serverContainer = (ServerContainer) context .getAttribute("javax.websocket.server.ServerContainer"); try { context.setAttribute("protocol", new MetadataProtocol()); //attach the WebSockets Endpoint to the web container serverContainer.addEndpoint(WebSocketEndpoint.class); logger.log(Level.INFO, "HOPSWORKS DEPLOYED"); } catch (DeploymentException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } }
@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 void connect() throws DeploymentException, IOException { ConnectionDetails details = info.getConnectionDetails(); Log.log(Level.FINE, drain, "Creating websocket to {0}", details.getTarget()); URI uriServerEP = URI.create(details.getTarget()); authConfigurator = new GameOnHeaderAuthConfigurator(details.getToken(), uriServerEP.getRawPath()); final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create() .decoders(Arrays.asList(RoutedMessageDecoder.class)).encoders(Arrays.asList(RoutedMessageEncoder.class)) .configurator(authConfigurator) .build(); WebSocketContainer c = ContainerProvider.getWebSocketContainer(); this.session = c.connectToServer(this, cec, uriServerEP); }
/** * Create session * * @param jsessionid * @param userpwd * @return */ protected Session createAndGetSession(String jsessionid, String userpwd) { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { StringBuilder sb = new StringBuilder("ws://localhost:"); sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH).append("ocelot-endpoint"); URI uri = new URI(sb.toString()); return container.connectToServer(new Endpoint() { @Override public void onOpen(Session session, EndpointConfig config) { } }, createClientEndpointConfigWithJsession(jsessionid, userpwd), uri); } catch (URISyntaxException | DeploymentException | IOException ex) { ex.getCause().printStackTrace(); fail("CONNEXION FAILED " + ex.getMessage()); } return null; }