/** * Default constructor that creates an instance of * {@link org.eclipse.jetty.websocket.client.WebSocketClient}. */ public JettyWebSocketClient() { this.client = new org.eclipse.jetty.websocket.client.WebSocketClient(); }
@Override public boolean isRunning() { return this.client.isStarted(); }
@Override public boolean isRunning() { return this.jettyClient.isRunning(); }
public Session connect(AgentWebSocketClientController controller) throws Exception { if (webSocketClient == null || !webSocketClient.isRunning()) { if (webSocketClient != null) { webSocketClient.stop(); } webSocketClient = builder.build(); webSocketClient.start(); } LOG.info("Connecting to websocket endpoint: {}", urlService.getAgentRemoteWebSocketUrl()); ClientUpgradeRequest request = new ClientUpgradeRequest(); request.addExtensions("fragment;maxLength=" + getMessageBufferSize()); return webSocketClient.connect(controller, new URI(urlService.getAgentRemoteWebSocketUrl()), request).get(); }
@SuppressWarnings("FutureReturnValueIgnored") @Test public void checkPlainConnect() throws Exception { LOG.info("*** checkPlainConnect ***"); String destUri = "ws://localhost:" + BrokerConstants.WEBSOCKET_PORT + "/mqtt"; MQTTWebSocket socket = new MQTTWebSocket(); client.start(); URI echoUri = new URI(destUri); ClientUpgradeRequest request = new ClientUpgradeRequest(); client.connect(socket, echoUri, request); LOG.info("Connecting to : {}", echoUri); boolean connected = socket.awaitConnected(4, TimeUnit.SECONDS); LOG.info("Connected was : {}", connected); assertTrue(connected); } }
@Override public ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler wsHandler, HttpHeaders headers, final URI uri, List<String> protocols, List<WebSocketExtension> extensions, Map<String, Object> attributes) { final ClientUpgradeRequest request = new ClientUpgradeRequest(); request.setSubProtocols(protocols); for (WebSocketExtension e : extensions) { request.addExtensions(new WebSocketToJettyExtensionConfigAdapter(e)); } headers.forEach(request::setHeader); Principal user = getUser(); final JettyWebSocketSession wsSession = new JettyWebSocketSession(attributes, user); final JettyWebSocketHandlerAdapter listener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession); Callable<WebSocketSession> connectTask = () -> { Future<Session> future = this.client.connect(listener, uri, request); future.get(); return wsSession; }; if (this.taskExecutor != null) { return this.taskExecutor.submitListenable(connectTask); } else { ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<>(connectTask); task.run(); return task; } }
private Mono<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) { MonoProcessor<Void> completionMono = MonoProcessor.create(); return Mono.fromCallable( () -> { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + url); } Object jettyHandler = createHandler(url, handler, completionMono); ClientUpgradeRequest request = new ClientUpgradeRequest(); request.setSubProtocols(handler.getSubProtocols()); UpgradeListener upgradeListener = new DefaultUpgradeListener(headers); return this.jettyClient.connect(jettyHandler, url, request, upgradeListener); }) .then(completionMono); }
@Override public void stop() { if (!this.externallyManaged) { try { this.jettyClient.stop(); } catch (Exception ex) { throw new IllegalStateException("Error stopping Jetty WebSocketClient", ex); } } }
@Override public void start() { if (!this.externallyManaged) { try { this.jettyClient.start(); } catch (Exception ex) { throw new IllegalStateException("Failed to start Jetty WebSocketClient", ex); } } }
@Override public WebSocketClient build() throws Exception { SslContextFactory sslContextFactory = sslVerificationMode == SslVerificationMode.NONE ? new TrustAllSSLContextFactory() : new SslContextFactory(); sslContextFactory.setNeedClientAuth(true); sslContextFactory.setKeyStore(agentKeystore()); sslContextFactory.setKeyStorePassword(keystorePassword()); sslContextFactory.setKeyManagerPassword(keystorePassword()); if (rootCertFile != null) { sslContextFactory.setTrustStore(agentTruststore()); sslContextFactory.setTrustStorePassword(keystorePassword()); } if (sslVerificationMode == SslVerificationMode.NO_VERIFY_HOST) { sslContextFactory.setEndpointIdentificationAlgorithm(null); } WebSocketClient client = new WebSocketClient(sslContextFactory); client.setMaxIdleTimeout(systemEnvironment.getWebsocketMaxIdleTime()); return client; }
private int getMessageBufferSize() { return webSocketClient.getPolicy().getMaxBinaryMessageBufferSize(); } }
@Test public void shouldNotThrowAnyExceptionWhenDataReceivedBeforeClose() throws Throwable { // Given WebSocketClient client = mock( WebSocketClient.class ); WebSocketConnection conn = new WebSocketConnection( client ); when( client.isStopped() ).thenReturn( true ); byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // When conn.onWebSocketBinary( data, 0, 10 ); conn.recv( 10 ); // Then // no exception }
/** * Default constructor that creates and manages an instance of a Jetty * {@link org.eclipse.jetty.websocket.client.WebSocketClient WebSocketClient}. * The instance can be obtained with {@link #getJettyClient()} for further * configuration. * * <p><strong>Note: </strong> When this constructor is used {@link Lifecycle} * methods of this class are delegated to the Jetty {@code WebSocketClient}. */ public JettyWebSocketClient() { this.jettyClient = new org.eclipse.jetty.websocket.client.WebSocketClient(); this.externallyManaged = false; }
@Override public void stop() { try { this.client.stop(); } catch (Exception ex) { logger.error("Failed to stop Jetty WebSocketClient", ex); } }
@Override public void start() { try { this.client.start(); } catch (Exception ex) { throw new IllegalStateException("Failed to start Jetty WebSocketClient", ex); } }
@Test public void shouldThrowIOExceptionWhenNotEnoughDataReceivedBeforeClose() throws Throwable { // Given WebSocketClient client = mock( WebSocketClient.class ); WebSocketConnection conn = new WebSocketConnection( client ); when( client.isStopped() ).thenReturn( true, true ); byte[] data = {0, 1, 2, 3}; // When && Then conn.onWebSocketBinary( data, 0, 4 ); expectedException.expect( IOException.class ); expectedException.expectMessage( "Connection closed while waiting for data from the server." ); conn.recv( 10 ); } }
private static Supplier<WebSocketClient> createTestClientSupplier() { return () -> { SslContextFactory sslContextFactory = new SslContextFactory( /* trustall= */ true ); /* remove extra filters added by jetty on cipher suites */ sslContextFactory.setExcludeCipherSuites(); return new WebSocketClient( sslContextFactory ); }; } }
@Override public void disconnect() throws IOException { if ( client != null ) { try { client.stop(); } catch ( Exception e ) { throw new IOException( e ); } } }
@Before public void setUp() throws Exception { startServer(); client = new WebSocketClient(); }
@After public void tearDown() throws Exception { client.stop(); m_server.stopServer(); IntegrationUtils.clearTestStorage(); }