Java Code Examples for org.eclipse.jetty.websocket.client.WebSocketClient#stop()
The following examples show how to use
org.eclipse.jetty.websocket.client.WebSocketClient#stop() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NotebookServerTest.java From submarine with Apache License 2.0 | 7 votes |
@Test public void testWebsocketConnection() throws Exception{ URI uri = URI.create( AbstractSubmarineServerTest.getWebsocketApiUrlToTest()); WebSocketClient client = new WebSocketClient(); try { client.start(); // The socket that receives events EventSocket socket = new EventSocket(); // Attempt Connect Future<Session> fut = client.connect(socket, uri); // Wait for Connect Session session = fut.get(); // Send a message session.getRemote().sendString("Hello"); // Close session //session.close(); session.close(StatusCode.NORMAL, "I'm done"); } finally { client.stop(); } }
Example 2
Source File: LoggregatorClient.java From orion.server with Eclipse Public License 1.0 | 6 votes |
public void start(Target target, String loggregatorLocation, LoggregatorListener listener) throws Exception { logger.debug(NLS.bind("About to connect: {0}", loggregatorLocation)); SslContextFactory sslContextFactory = new SslContextFactory(true); WebSocketClient client = new WebSocketClient(sslContextFactory); LoggregatorSocket socket = new LoggregatorSocket(listener); try { client.start(); URI loggregatorUri = new URI(loggregatorLocation); ClientUpgradeRequest request = new ClientUpgradeRequest(); request.setHeader("Authorization", "bearer " + target.getCloud().getAccessToken().getString("access_token")); client.connect(socket, loggregatorUri, request); logger.debug(NLS.bind("Connecting to: {0}", loggregatorUri)); socket.awaitClose(25, TimeUnit.SECONDS); } finally { client.stop(); } }
Example 3
Source File: SimpleEchoClient.java From java_rosbridge with GNU Lesser General Public License v3.0 | 6 votes |
public static void main(String[] args) { String destUri = "ws://echo.websocket.org"; if (args.length > 0) { destUri = args[0]; } WebSocketClient client = new WebSocketClient(); SimpleEchoSocket socket = new SimpleEchoSocket(); try { client.start(); URI echoUri = new URI(destUri); ClientUpgradeRequest request = new ClientUpgradeRequest(); client.connect(socket, echoUri, request); System.out.printf("Connecting to : %s%n", echoUri); socket.awaitClose(15, TimeUnit.SECONDS); } catch (Throwable t) { t.printStackTrace(); } finally { try { client.stop(); } catch (Exception e) { e.printStackTrace(); } } }
Example 4
Source File: WebsocketAppenderTest.java From karaf-decanter with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { // install decanter System.out.println(executeCommand("feature:repo-add decanter " + System.getProperty("decanter.version"))); System.out.println(executeCommand("feature:install decanter-appender-websocket-servlet", new RolePrincipal("admin"))); String httpList = executeCommand("http:list"); while (!httpList.contains("Deployed")) { Thread.sleep(500); httpList = executeCommand("http:list"); } System.out.println(httpList); // websocket WebSocketClient client = new WebSocketClient(); DecanterSocket decanterSocket = new DecanterSocket(); client.start(); URI uri = new URI("ws://localhost:" + getHttpPort() + "/decanter-websocket"); ClientUpgradeRequest request = new ClientUpgradeRequest(); client.connect(decanterSocket, uri, request).get(); // sending event EventAdmin eventAdmin = getOsgiService(EventAdmin.class); HashMap<String, String> data = new HashMap<>(); data.put("foo", "bar"); Event event = new Event("decanter/collect/test", data); eventAdmin.sendEvent(event); decanterSocket.awaitClose(20, TimeUnit.SECONDS); Assert.assertEquals(1, decanterSocket.messages.size()); Assert.assertTrue(decanterSocket.messages.get(0).contains("\"foo\":\"bar\"")); Assert.assertTrue(decanterSocket.messages.get(0).contains("\"event_topics\":\"decanter/collect/test\"")); client.stop(); }
Example 5
Source File: WebClientFactoryTest.java From smarthome with Eclipse Public License 2.0 | 5 votes |
@Test public void testGetWebSocketClientWithEndpoint() throws Exception { when(trustmanagerProvider.getTrustManagers("https://www.heise.de")).thenReturn(Stream.empty()); WebSocketClient webSocketClient = webClientFactory.createWebSocketClient("consumer", TEST_URL); assertThat(webSocketClient, is(notNullValue())); verify(trustmanagerProvider).getTrustManagers(TEST_URL); webSocketClient.stop(); }
Example 6
Source File: EventClientTest.java From dawnsci with Eclipse Public License 1.0 | 5 votes |
@Test public void checkClientConnection() throws Exception { URI uri = URI.create("ws://localhost:8080/event/?path=c%3A/Work/results/Test.txt"); WebSocketClient client = new WebSocketClient(); client.start(); try { Session connection = null; try { final EventClientSocket clientSocket = new EventClientSocket(); // Attempt Connect Future<Session> fut = client.connect(clientSocket, uri); // Wait for Connect connection = fut.get(); // Send a message connection.getRemote().sendString("Hello World"); // Close session from the server while(connection.isOpen()) { Thread.sleep(100); } } finally { if (connection!=null) connection.close(); } } catch (Throwable t) { t.printStackTrace(System.err); throw t; } finally { client.stop(); } }
Example 7
Source File: V1_ProxyAuthenticationTest.java From pulsar with Apache License 2.0 | 4 votes |
@Test(timeOut=10000) public void statsTest() throws Exception { final String topic = "prop/use/my-ns/my-topic2"; final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/consumer/persistent/" + topic + "/my-sub"; final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/producer/persistent/" + topic; URI consumeUri = URI.create(consumerUri); URI produceUri = URI.create(producerUri); WebSocketClient consumeClient = new WebSocketClient(); SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket(); WebSocketClient produceClient = new WebSocketClient(); SimpleProducerSocket produceSocket = new SimpleProducerSocket(); final String baseUrl = "http://localhost:" + proxyServer.getListenPortHTTP().get() + "/admin/proxy-stats/"; Client client = ClientBuilder.newClient(); try { consumeClient.start(); ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest(); Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest); Assert.assertTrue(consumerFuture.get().isOpen()); produceClient.start(); ClientUpgradeRequest produceRequest = new ClientUpgradeRequest(); Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest); Assert.assertTrue(producerFuture.get().isOpen()); int retry = 0; int maxRetry = 500; while (consumeSocket.getReceivedMessagesCount() < 3) { Thread.sleep(10); if (retry++ > maxRetry) { break; } } service.getProxyStats().generate(); verifyResponseStatus(client, baseUrl + "metrics"); verifyResponseStatus(client, baseUrl + "stats"); verifyResponseStatus(client, baseUrl + topic + "/stats"); } finally { consumeClient.stop(); produceClient.stop(); client.close(); } }
Example 8
Source File: ProxyAuthenticationTest.java From pulsar with Apache License 2.0 | 4 votes |
@Test(timeOut=10000) public void statsTest() throws Exception { final String topic = "persistent/my-property/my-ns/my-topic2"; final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/consumer/" + topic + "/my-sub"; final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/producer/" + topic; URI consumeUri = URI.create(consumerUri); URI produceUri = URI.create(producerUri); WebSocketClient consumeClient = new WebSocketClient(); SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket(); WebSocketClient produceClient = new WebSocketClient(); SimpleProducerSocket produceSocket = new SimpleProducerSocket(); final String baseUrl = "http://localhost:" + proxyServer.getListenPortHTTP().get() + "/admin/v2/proxy-stats/"; Client client = ClientBuilder.newClient(); try { consumeClient.start(); ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest(); Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest); Assert.assertTrue(consumerFuture.get().isOpen()); produceClient.start(); ClientUpgradeRequest produceRequest = new ClientUpgradeRequest(); Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest); Assert.assertTrue(producerFuture.get().isOpen()); int retry = 0; int maxRetry = 500; while (consumeSocket.getReceivedMessagesCount() < 3) { Thread.sleep(10); if (retry++ > maxRetry) { break; } } service.getProxyStats().generate(); verifyResponseStatus(client, baseUrl + "metrics"); verifyResponseStatus(client, baseUrl + "stats"); verifyResponseStatus(client, baseUrl + topic + "/stats"); } finally { consumeClient.stop(); produceClient.stop(); client.close(); } }
Example 9
Source File: TestWebSocketServerPushSource.java From datacollector with Apache License 2.0 | 4 votes |
@Test public void testSource() throws Exception { WebSocketConfigs webSocketConfigs = new WebSocketConfigs(); webSocketConfigs.appId = () -> "appId"; webSocketConfigs.port = NetworkUtils.getRandomPort(); webSocketConfigs.maxConcurrentRequests = 1; webSocketConfigs.tlsConfigBean.tlsEnabled = false; WebSocketServerPushSource source = new WebSocketServerPushSource( webSocketConfigs, DataFormat.JSON, new DataParserFormatConfig(), new ResponseConfigBean() ); final PushSourceRunner runner = new PushSourceRunner.Builder(WebSocketServerDPushSource.class, source).addOutputLane("a").build(); runner.runInit(); try { final List<Record> records = new ArrayList<>(); runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() { @Override public void processBatch(StageRunner.Output output) { records.clear(); runner.getSourceResponseSink().getResponseRecords().clear(); records.addAll(output.getRecords().get("a")); records.forEach(record -> { runner.getSourceResponseSink().addResponse(record); }); runner.setStop(); } }); // wait for the HTTP server up and running WebSocketReceiverServer httpServer = (WebSocketReceiverServer) Whitebox.getInternalState(source, "server"); await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer)); WebSocketClient client = new WebSocketClient(); SimpleEchoSocket socket = new SimpleEchoSocket(); try { client.start(); URI echoUri = new URI("ws://localhost:" + webSocketConfigs.getPort()); ClientUpgradeRequest request = new ClientUpgradeRequest(); request.setHeader(HttpConstants.X_SDC_APPLICATION_ID_HEADER, "appId"); Future<Session> future = client.connect(socket, echoUri, request); future.get(); // wait for closed socket connection. socket.awaitClose(5, TimeUnit.SECONDS); } catch (Throwable t) { t.printStackTrace(); } finally { try { client.stop(); } catch (Exception e) { e.printStackTrace(); } } runner.waitOnProduce(); Assert.assertEquals(1, records.size()); Assert.assertEquals("value", records.get(0).get("/field1").getValue()); // check response from WebSocket Server Assert.assertNotNull(socket.receivedMessage); Assert.assertEquals( "{\"httpStatusCode\":200,\"data\":[{\"field1\":\"value\"}],\"error\":[]}", socket.receivedMessage ); } finally { runner.runDestroy(); } }
Example 10
Source File: TestWebSocketServerPushSource.java From datacollector with Apache License 2.0 | 4 votes |
@Test public void testWithAppIdViaQueryParam() throws Exception { WebSocketConfigs webSocketConfigs = new WebSocketConfigs(); webSocketConfigs.appId = () -> "appId"; webSocketConfigs.port = NetworkUtils.getRandomPort(); webSocketConfigs.maxConcurrentRequests = 1; webSocketConfigs.tlsConfigBean.tlsEnabled = false; webSocketConfigs.appIdViaQueryParamAllowed = true; WebSocketServerPushSource source = new WebSocketServerPushSource( webSocketConfigs, DataFormat.JSON, new DataParserFormatConfig(), new ResponseConfigBean() ); final PushSourceRunner runner = new PushSourceRunner.Builder(WebSocketServerDPushSource.class, source).addOutputLane("a").build(); runner.runInit(); try { final List<Record> records = new ArrayList<>(); runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() { @Override public void processBatch(StageRunner.Output output) { records.clear(); records.addAll(output.getRecords().get("a")); runner.setStop(); } }); // wait for the HTTP server up and running WebSocketReceiverServer httpServer = (WebSocketReceiverServer) Whitebox.getInternalState(source, "server"); await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer)); WebSocketClient client = new WebSocketClient(); SimpleEchoSocket socket = new SimpleEchoSocket(); try { client.start(); URI echoUri = new URI("ws://localhost:" + webSocketConfigs.getPort() + "?" + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=appId"); ClientUpgradeRequest request = new ClientUpgradeRequest(); client.connect(socket, echoUri, request); // wait for closed socket connection. socket.awaitClose(5, TimeUnit.SECONDS); } catch (Throwable t) { t.printStackTrace(); } finally { try { client.stop(); } catch (Exception e) { e.printStackTrace(); } } runner.waitOnProduce(); Assert.assertEquals(1, records.size()); Assert.assertEquals("value", records.get(0).get("/field1").getValue()); } finally { runner.runDestroy(); } }
Example 11
Source File: HybridServiceTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testHybridService() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestCombinedService.class); WebSocketClient wsClient = new WebSocketClient(); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); messageRegistry.registerType("stuff", TestObject.class); wsClient.start(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null); Session session = wsClient.connect(webSocket, new URI("ws://localhost:" + properties.get("websocket.port") + "/protobuf")).get(5000, TimeUnit.MILLISECONDS); Envelope envelope = new Envelope("getStuff", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); byte[] rawStuff = serDe.serialize(new TestObject("more stuff")); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); envelope = new Envelope("getStuff", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.postForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("even more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("even more stuff", response.value); } finally { try { wsClient.stop(); } finally { context.close(); } } }
Example 12
Source File: WebSocketTransportTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testEmptyWebSocketFrameUsingBinary() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "false"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestWebSocketService.class); WebSocketClient wsClient = new WebSocketClient(); try { //start server context.refresh(); // start client wsClient.start(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); QueuingWebSocketListener listener = new QueuingWebSocketListener(serDe, messageRegistry, null); WebSocketSession session = (WebSocketSession)wsClient.connect(listener, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())) .get(5000, TimeUnit.MILLISECONDS); session.getRemote().sendBytes(ByteBuffer.wrap(new byte[0])); ServiceError error = listener.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals("EMPTY_ENVELOPE", error.code); Assert.assertEquals("STOPPED", session.getState()); } finally { try { wsClient.stop(); } finally { context.close(); } } }
Example 13
Source File: WebSocketTransportTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testEmptyWebSocketFrameUsingText() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "false"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestWebSocketService.class); WebSocketClient wsClient = new WebSocketClient(); try { //start server context.refresh(); // start client wsClient.start(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); QueuingWebSocketListener listener = new QueuingWebSocketListener(serDe, messageRegistry, null); WebSocketSession session = (WebSocketSession)wsClient.connect(listener, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())) .get(5000, TimeUnit.MILLISECONDS); session.getRemote().sendString(""); ServiceError error = listener.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals("EMPTY_ENVELOPE", error.code); Assert.assertEquals("STOPPED", session.getState()); } finally { try { wsClient.stop(); } finally { context.close(); } } }
Example 14
Source File: WebSocketTest.java From roboconf-platform with Apache License 2.0 | 4 votes |
@Test public void run() throws Exception { Assume.assumeTrue( RabbitMqTestUtils.checkRabbitMqIsRunning()); // Prepare to run an agent distribution Option[] options = super.config(); ExamSystem system = PaxExamRuntime.createServerSystem( options ); TestContainer container = PaxExamRuntime.createContainer( system ); Assert.assertEquals( KarafTestContainer.class, container.getClass()); try { // Start the agent's distribution... and wait... :( container.start(); ItUtils.waitForDmRestServices( getCurrentPort()); // Try to connect to our web socket. WebSocketClient client = new WebSocketClient(); TestWebsocket socket = new TestWebsocket(); try { client.start(); URI echoUri = new URI( "ws://localhost:" + getCurrentPort() + "/roboconf-dm-websocket" ); ClientUpgradeRequest request = new ClientUpgradeRequest(); client.connect( socket, echoUri, request ); // Wait more or less (Travis builds with Java 8 may need it). for( int i=0; i<10; i++ ) { Thread.sleep( 2000 ); if( socket.wasConnected ) break; } } finally { client.stop(); } // Did the connection work? Assert.assertTrue( socket.wasConnected ); } finally { container.stop(); } }