javax.websocket.ClientEndpointConfig Java Examples
The following examples show how to use
javax.websocket.ClientEndpointConfig.
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: GatewayWebsocketHandler.java From knox with Apache License 2.0 | 6 votes |
@Override public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) { try { final URI requestURI = req.getRequestURI(); final String path = requestURI.getPath(); /* URL used to connect to websocket backend */ final String backendURL = getMatchedBackendURL(path, requestURI); LOG.debugLog("Generated backend URL for websocket connection: " + backendURL); /* Upgrade happens here */ final ClientEndpointConfig clientConfig = getClientEndpointConfig(req); clientConfig.getUserProperties().put("org.apache.knox.gateway.websockets.truststore", getTruststore()); return new ProxyWebSocketAdapter(URI.create(backendURL), pool, clientConfig, config); } catch (final Exception e) { LOG.failedCreatingWebSocket(e); throw new RuntimeException(e); } }
Example #2
Source File: StandardWebSocketClient.java From java-technology-stack with MIT License | 6 votes |
private Mono<Void> executeInternal(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) { MonoProcessor<Void> completionMono = MonoProcessor.create(); return Mono.fromCallable( () -> { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + url); } List<String> protocols = handler.getSubProtocols(); DefaultConfigurator configurator = new DefaultConfigurator(requestHeaders); Endpoint endpoint = createEndpoint(url, handler, completionMono, configurator); ClientEndpointConfig config = createEndpointConfig(configurator, protocols); return this.webSocketContainer.connectToServer(endpoint, config, url); }) .subscribeOn(Schedulers.elastic()) // connectToServer is blocking .then(completionMono); }
Example #3
Source File: EndpointConnectionManager.java From java-technology-stack with MIT License | 6 votes |
@Override protected void openConnection() { this.taskExecutor.execute(() -> { try { if (logger.isInfoEnabled()) { logger.info("Connecting to WebSocket at " + getUri()); } Endpoint endpointToUse = this.endpoint; if (endpointToUse == null) { Assert.state(this.endpointProvider != null, "No endpoint set"); endpointToUse = this.endpointProvider.getHandler(); } ClientEndpointConfig endpointConfig = this.configBuilder.build(); this.session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri()); logger.info("Successfully connected to WebSocket"); } catch (Throwable ex) { logger.error("Failed to connect to WebSocket", ex); } }); }
Example #4
Source File: TesterWsClientAutobahn.java From Tomcat8-Source-Read with MIT License | 6 votes |
private static void executeTestCase(WebSocketContainer wsc, int testCase) throws Exception { URI uri = new URI("ws://" + HOST + ":" + PORT + "/runCase?case=" + testCase + "&agent=" + USER_AGENT); TestCaseClient testCaseClient = new TestCaseClient(); Extension permessageDeflate = new WsExtension("permessage-deflate"); // Advertise support for client_max_window_bits // Client only supports some values so there will be some failures here // Note Autobahn returns a 400 response if you provide a value for // client_max_window_bits permessageDeflate.getParameters().add( new WsExtensionParameter("client_max_window_bits", null)); List<Extension> extensions = new ArrayList<>(1); extensions.add(permessageDeflate); Endpoint ep = new PojoEndpointClient(testCaseClient, null); ClientEndpointConfig.Builder builder = ClientEndpointConfig.Builder.create(); ClientEndpointConfig config = builder.extensions(extensions).build(); wsc.connectToServer(ep, config, uri); testCaseClient.waitForClose(); }
Example #5
Source File: DaemonMessagesClientEndpoint.java From pentaho-kettle with Apache License 2.0 | 6 votes |
public DaemonMessagesClientEndpoint( String host, int port, boolean ssl, MessageEventService messageEventService ) throws KettleException { try { setAuthProperties(); String url = String.format( URL_TEMPLATE, ( ssl ? PRFX_WS_SSL : PRFX_WS ), host, port ); URI uri = new URI( url ); this.messageEventService = messageEventService; WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.connectToServer( this, ClientEndpointConfig.Builder.create() .encoders( Collections.singletonList( MessageEncoder.class ) ) .decoders( Collections.singletonList( MessageDecoder.class ) ) .configurator( new SessionConfigurator( uri, keytab, principal ) ) .build(), uri ); } catch ( Exception e ) { throw new KettleException( e ); } }
Example #6
Source File: StandardWebSocketClient.java From spring-analysis-note with MIT License | 6 votes |
private Mono<Void> executeInternal(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) { MonoProcessor<Void> completionMono = MonoProcessor.create(); return Mono.fromCallable( () -> { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + url); } List<String> protocols = handler.getSubProtocols(); DefaultConfigurator configurator = new DefaultConfigurator(requestHeaders); Endpoint endpoint = createEndpoint(url, handler, completionMono, configurator); ClientEndpointConfig config = createEndpointConfig(configurator, protocols); return this.webSocketContainer.connectToServer(endpoint, config, url); }) .subscribeOn(Schedulers.elastic()) // connectToServer is blocking .then(completionMono); }
Example #7
Source File: RunnerWebSocketTest.java From camel-language-server with Apache License 2.0 | 6 votes |
private void testWebSocketServerConnection(String[] arguments, String expectedConnectionURI) throws InterruptedException, DeploymentException, IOException, URISyntaxException { startRunnerWithWebsocketOption(arguments); await("WebSocket Server has not been started.").until(() -> {return Runner.webSocketRunner != null && Runner.webSocketRunner.isStarted(); }); final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build(); ClientManager client = ClientManager.createClient(); client.connectToServer(new Endpoint() { @Override public void onOpen(Session session, EndpointConfig config) { messageLatch.countDown(); } }, cec, new URI(expectedConnectionURI)); assertThat(messageLatch.getCount()).isZero(); }
Example #8
Source File: EndpointConnectionManager.java From spring-analysis-note with MIT License | 6 votes |
@Override protected void openConnection() { this.taskExecutor.execute(() -> { try { if (logger.isInfoEnabled()) { logger.info("Connecting to WebSocket at " + getUri()); } Endpoint endpointToUse = this.endpoint; if (endpointToUse == null) { Assert.state(this.endpointProvider != null, "No endpoint set"); endpointToUse = this.endpointProvider.getHandler(); } ClientEndpointConfig endpointConfig = this.configBuilder.build(); this.session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri()); logger.info("Successfully connected to WebSocket"); } catch (Throwable ex) { logger.error("Failed to connect to WebSocket", ex); } }); }
Example #9
Source File: TestWsWebSocketContainer.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
@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)); }
Example #10
Source File: WsWebSocketContainer.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Override public Session connectToServer(Class<? extends Endpoint> clazz, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException { Endpoint endpoint; try { endpoint = clazz.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.endpointCreateFail", clazz.getName()), e); } return connectToServer(endpoint, clientEndpointConfiguration, path); }
Example #11
Source File: WebsocketClient.java From lams with GNU General Public License v2.0 | 6 votes |
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); } }
Example #12
Source File: LibertySessionWrapper.java From rogue-cloud with Apache License 2.0 | 6 votes |
private void connect(String url) { // Don't try to connect if we have already disposed of the session, or the client instance if (disposed || LibertyClientInstance.getInstance().isDisposed()) { log.interesting("Ignoring connect as instance of wrapper is disposed ["+disposed+","+LibertyClientInstance.getInstance().isDisposed()+"]", parent.getLogContext()); return; } log.interesting("Attempting to connect", parent.getLogContext()); final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build(); // // ClientManager client = ClientManager.createClient(); WebSocketContainer c = ContainerProvider.getWebSocketContainer(); c.setDefaultMaxTextMessageBufferSize(1024 * 1024); c.setDefaultMaxSessionIdleTimeout(2 * TimeUnit.MILLISECONDS.convert(RCSharedConstants.MAX_ROUND_LENGTH_IN_NANOS, TimeUnit.NANOSECONDS)); try { c.connectToServer(this.hce, cec, new URI(url)); // Wait for the endpoint to call us on success or failure. } catch (DeploymentException | IOException | URISyntaxException e) { errorOccurred(null); } }
Example #13
Source File: ServerWebSocketContainer.java From quarkus-http with Apache License 2.0 | 6 votes |
@Override public void afterRequest(final HttpHeaders headers) { ClientEndpointConfig.Configurator configurator = config.getConfigurator(); if (configurator != null) { final Map<String, List<String>> newHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, String> entry : headers) { ArrayList<String> arrayList = new ArrayList<>(headers.getAll(entry.getKey())); newHeaders.put(entry.getKey(), arrayList); } configurator.afterResponse(new HandshakeResponse() { @Override public Map<String, List<String>> getHeaders() { return newHeaders; } }); } headers.remove(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL); super.afterRequest(headers); }
Example #14
Source File: EndpointConnectionManager.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override protected void openConnection() { this.taskExecutor.execute(new Runnable() { @Override public void run() { try { logger.info("Connecting to WebSocket at " + getUri()); Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); ClientEndpointConfig endpointConfig = configBuilder.build(); session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri()); logger.info("Successfully connected"); } catch (Throwable ex) { logger.error("Failed to connect", ex); } } }); }
Example #15
Source File: MockServerContainer.java From java-technology-stack with MIT License | 5 votes |
@Override public Session connectToServer(Endpoint endpointInstance, ClientEndpointConfig cec, URI path) throws DeploymentException, IOException { throw new UnsupportedOperationException( "MockServerContainer does not support connectToServer(Endpoint, ClientEndpointConfig, URI)"); }
Example #16
Source File: WebsocketBasicAuthTestCase.java From quarkus-http with Apache License 2.0 | 5 votes |
@Test public void testWrappedRequest() throws Exception { ProgramaticClientEndpoint endpoint = new ProgramaticClientEndpoint(); ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build(); ContainerProvider.getWebSocketContainer().connectToServer(endpoint, clientEndpointConfig, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/servletContext/wrapper")); Assert.assertEquals("wrapped", endpoint.getResponses().poll(15, TimeUnit.SECONDS)); endpoint.session.close(); endpoint.closeLatch.await(10, TimeUnit.SECONDS); }
Example #17
Source File: StandardWebSocketClientTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void clientEndpointConfig() throws Exception { URI uri = new URI("ws://localhost/abc"); List<String> protocols = Collections.singletonList("abc"); this.headers.setSecWebSocketProtocol(protocols); this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class); verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class)); ClientEndpointConfig endpointConfig = captor.getValue(); assertEquals(protocols, endpointConfig.getPreferredSubprotocols()); }
Example #18
Source File: MockServerContainer.java From java-technology-stack with MIT License | 5 votes |
@Override public Session connectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path) throws DeploymentException, IOException { throw new UnsupportedOperationException( "MockServerContainer does not support connectToServer(Class, ClientEndpointConfig, URI)"); }
Example #19
Source File: TestWsWebSocketContainer.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointNoHost() 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("ws://" + TesterEchoServer.Config.PATH_ASYNC)); }
Example #20
Source File: TestWsWebSocketContainer.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
private void doTestPerMessageDefalteClient(String msg, int count) throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME); List<Extension> extensions = new ArrayList<Extension>(1); extensions.add(perMessageDeflate); ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create().extensions(extensions).build(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, clientConfig, new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(count); BasicText handler = new BasicText(latch, msg); wsSession.addMessageHandler(handler); for (int i = 0; i < count; i++) { wsSession.getBasicRemote().sendText(msg); } boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); ((WsWebSocketContainer) wsContainer).destroy(); }
Example #21
Source File: StandardWebSocketClient.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler, HttpHeaders headers, final URI uri, List<String> protocols, List<WebSocketExtension> extensions, Map<String, Object> attributes) { int port = getPort(uri); InetSocketAddress localAddress = new InetSocketAddress(getLocalHost(), port); InetSocketAddress remoteAddress = new InetSocketAddress(uri.getHost(), port); final StandardWebSocketSession session = new StandardWebSocketSession(headers, attributes, localAddress, remoteAddress); final ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create() .configurator(new StandardWebSocketClientConfigurator(headers)) .preferredSubprotocols(protocols) .extensions(adaptExtensions(extensions)).build(); endpointConfig.getUserProperties().putAll(getUserProperties()); final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session); Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() { @Override public WebSocketSession call() throws Exception { webSocketContainer.connectToServer(endpoint, endpointConfig, uri); return session; } }; if (this.taskExecutor != null) { return this.taskExecutor.submitListenable(connectTask); } else { ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<WebSocketSession>(connectTask); task.run(); return task; } }
Example #22
Source File: StandardWebSocketClientTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void clientEndpointConfig() throws Exception { URI uri = new URI("ws://localhost/abc"); List<String> protocols = Collections.singletonList("abc"); this.headers.setSecWebSocketProtocol(protocols); this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class); verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class)); ClientEndpointConfig endpointConfig = captor.getValue(); assertEquals(protocols, endpointConfig.getPreferredSubprotocols()); }
Example #23
Source File: StandardWebSocketClientTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void clientEndpointConfigWithUserProperties() throws Exception { Map<String,Object> userProperties = Collections.singletonMap("foo", "bar"); URI uri = new URI("ws://localhost/abc"); this.wsClient.setUserProperties(userProperties); this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class); verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class)); ClientEndpointConfig endpointConfig = captor.getValue(); assertEquals(userProperties, endpointConfig.getUserProperties()); }
Example #24
Source File: TestWsWebSocketContainer.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
@Test public void testConnectToServerEndpoint() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); // Set this artificially small to trigger // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054 wsContainer.setDefaultMaxBinaryMessageBufferSize(64); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendText(MESSAGE_STRING_1); boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); Queue<String> messages = handler.getMessages(); Assert.assertEquals(1, messages.size()); Assert.assertEquals(MESSAGE_STRING_1, messages.peek()); ((WsWebSocketContainer) wsContainer).destroy(); }
Example #25
Source File: ServerWebSocketContainer.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override public Session connectToServer(final Endpoint endpointInstance, final ClientEndpointConfig config, final URI path) throws DeploymentException, IOException { if (closed) { throw new ClosedChannelException(); } ClientEndpointConfig cec = config != null ? config : ClientEndpointConfig.Builder.create().build(); SSLContext ssl = null; if (path.getScheme().equals("wss")) { for (WebsocketClientSslProvider provider : clientSslProviders) { ssl = provider.getSsl(eventLoopSupplier.get(), endpointInstance, cec, path); if (ssl != null) { break; } } if (ssl == null) { try { ssl = SSLContext.getDefault(); } catch (NoSuchAlgorithmException e) { //ignore } } } //in theory we should not be able to connect until the deployment is complete, but the definition of when a deployment is complete is a bit nebulous. ClientNegotiation clientNegotiation = new ClientNegotiation(cec.getPreferredSubprotocols(), toExtensionList(cec.getExtensions()), cec); WebsocketConnectionBuilder connectionBuilder = new WebsocketConnectionBuilder(path, eventLoopSupplier.get()) .setSsl(ssl) .setBindAddress(clientBindAddress) .setClientNegotiation(clientNegotiation); return connectToServer(endpointInstance, config, connectionBuilder); }
Example #26
Source File: TeapotSimulator.java From example-restful-project with MIT License | 5 votes |
/** * Creates and starts teapot simulator. * * @param teapot teapot domain object * @param port port number of the server * * @throws URISyntaxException * @throws DeploymentException * @throws IOException */ public TeapotSimulator(Teapot teapot, int port) throws URISyntaxException, DeploymentException, IOException { /* Get websocket container */ final WebSocketContainer container = ContainerProvider .getWebSocketContainer(); /* Configuration of teapot client endpoint */ final ClientEndpointConfig teapotConfig = ClientEndpointConfig.Builder .create() .build(); /* Disable websocket timeout */ container.setDefaultMaxSessionIdleTimeout(0); URI uri = new URI(String.format(REGISTER_URL, port, teapot.getId())); /* Create websocket client for the teapot */ container.connectToServer( new TeapotSimulatorEndpoint(this), teapotConfig, uri); /* Create the file system */ fs = new TeapotFs(); /* Create help.txt file */ fs.cat("help.txt", createHelpFileContent()); /* Create license file */ fs.cat("license", createLicenseFileContent()); /* Create config.json file */ fs.cat("config.json", createConfigFileContent(teapot)); }
Example #27
Source File: TestWsWebSocketContainer.java From tomcatsrc with Apache License 2.0 | 5 votes |
private void doTestPerMessageDefalteClient(String msg, int count) throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME); List<Extension> extensions = new ArrayList<Extension>(1); extensions.add(perMessageDeflate); ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create().extensions(extensions).build(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, clientConfig, new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(count); BasicText handler = new BasicText(latch, msg); wsSession.addMessageHandler(handler); for (int i = 0; i < count; i++) { wsSession.getBasicRemote().sendText(msg); } boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); ((WsWebSocketContainer) wsContainer).destroy(); }
Example #28
Source File: ProxyWebSocketAdapter.java From knox with Apache License 2.0 | 5 votes |
public ProxyWebSocketAdapter(final URI backend, final ExecutorService pool, final ClientEndpointConfig clientConfig, GatewayConfig config) { super(); this.backend = backend; this.pool = pool; this.clientConfig = clientConfig; this.config = config; }
Example #29
Source File: ProgramaticLazyEndpointTest.java From quarkus-http with Apache License 2.0 | 5 votes |
@org.junit.Test public void testStringOnMessage() throws Exception { SSLContext context = DefaultServer.getClientSSLContext(); ProgramaticClientEndpoint endpoint = new ProgramaticClientEndpoint(); ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build(); //clientEndpointConfig.getUserProperties().put(DefaultWebSocketClientSslProvider.SSL_CONTEXT, context); ContainerProvider.getWebSocketContainer().connectToServer(endpoint, clientEndpointConfig, new URI("wss://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostSSLPort("default") + "/foo")); Assert.assertEquals("Hello Stuart", endpoint.getResponses().poll(15, TimeUnit.SECONDS)); endpoint.session.close(); endpoint.closeLatch.await(10, TimeUnit.SECONDS); }
Example #30
Source File: TestWsWebSocketContainer.java From tomcatsrc with Apache License 2.0 | 5 votes |
@Test public void testConnectToServerEndpoint() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); // Set this artificially small to trigger // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054 wsContainer.setDefaultMaxBinaryMessageBufferSize(64); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendText(MESSAGE_STRING_1); boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); Queue<String> messages = handler.getMessages(); Assert.assertEquals(1, messages.size()); Assert.assertEquals(MESSAGE_STRING_1, messages.peek()); ((WsWebSocketContainer) wsContainer).destroy(); }