Java Code Examples for org.eclipse.jetty.websocket.client.WebSocketClient#start()

The following examples show how to use org.eclipse.jetty.websocket.client.WebSocketClient#start() . 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 vote down vote up
@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: JettyWebSocketClient.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
@Override
public void startClient(final ConfigurationContext context) throws Exception{

    final SSLContextService sslService = context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);
    SslContextFactory sslContextFactory = null;
    if (sslService != null) {
        sslContextFactory = createSslFactory(sslService, false, false);
    }
    client = new WebSocketClient(sslContextFactory);

    configurePolicy(context, client.getPolicy());

    client.start();

    webSocketUri = new URI(context.getProperty(WS_URI).getValue());
    connectionTimeoutMillis = context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS);
}
 
Example 3
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test(timeOut = 10000)
public void emptySubcriptionConsumerTest() throws Exception {

    // Empty subcription name
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/consumer/persistent/my-property/my-ns/my-topic2/?subscriptionType=Exclusive";
    URI consumeUri = URI.create(consumerUri);

    WebSocketClient consumeClient1 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket1 = new SimpleConsumerSocket();

    try {
        consumeClient1.start();
        ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest();
        Future<Session> consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1);
        consumerFuture1.get();
        fail("should fail: empty subscription");
    } catch (Exception e) {
        // Expected
        assertTrue(e.getCause() instanceof UpgradeException);
        assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                HttpServletResponse.SC_BAD_REQUEST);
    } finally {
        stopWebSocketClient(consumeClient1);
    }
}
 
Example 4
Source File: SwingClient.java    From codenjoy with GNU General Public License v3.0 6 votes vote down vote up
private void connect() {
    try {
        // TODO to use board url parsing like WebSocketRunner.runClient
        String server = String.format("ws://%s/codenjoy-contest/ws", SERVER_AND_PORT);
        URI uri = new URI(String.format("%s?user=%s&code=%s", server, USER_ID, CODE));

        if (session != null) {
            session.close();
        }

        cc = new WebSocketClient();
        cc.start();
        session = cc.connect(new ClientSocket(), uri).get(5000, TimeUnit.MILLISECONDS);
    } catch (Exception ex) {
        textArea.append(ex.toString());
    }
}
 
Example 5
Source File: RosBridge.java    From java_rosbridge with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Connects to the Rosbridge host at the provided URI.
 * @param rosBridgeURI the URI to the ROS Bridge websocket server. Note that ROS Bridge by default uses port 9090. An example URI is: ws://localhost:9090
 * @param waitForConnection if true, then this method will block until the connection is established. If false, then return immediately.
 */
public void connect(String rosBridgeURI, boolean waitForConnection){
	WebSocketClient client = new WebSocketClient();
	try {
		client.start();
		URI echoUri = new URI(rosBridgeURI);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(this, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);
		if(waitForConnection){
			this.waitForConnection();
		}

	} catch (Throwable t) {
		t.printStackTrace();
	}

}
 
Example 6
Source File: WebSocketRunnerMock.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@SneakyThrows
private void start(String server, String userName, String code)  {
    wsClient = new WebSocketClient();
    wsClient.start();

    URI uri = new URI(server + "?user=" + userName + "&code=" + code);
    System.out.println("Connecting to: " + uri);
    session = wsClient.connect(new ClientSocket(), uri).get(5000, TimeUnit.MILLISECONDS);
}
 
Example 7
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void conflictingConsumerTest() throws Exception {
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/consumer/persistent/my-property/my-ns/my-topic3/sub1?subscriptionType=Exclusive";
    URI consumeUri = URI.create(consumerUri);

    WebSocketClient consumeClient1 = new WebSocketClient();
    WebSocketClient consumeClient2 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket1 = new SimpleConsumerSocket();
    SimpleConsumerSocket consumeSocket2 = new SimpleConsumerSocket();

    try {
        consumeClient1.start();
        ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest();
        Future<Session> consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1);
        consumerFuture1.get();

        try {
            consumeClient2.start();
            ClientUpgradeRequest consumeRequest2 = new ClientUpgradeRequest();
            Future<Session> consumerFuture2 = consumeClient2.connect(consumeSocket2, consumeUri, consumeRequest2);
            consumerFuture2.get();
            fail("should fail: conflicting subscription name");
        } catch (Exception e) {
            // Expected
            assertTrue(e.getCause() instanceof UpgradeException);
            assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                    HttpServletResponse.SC_CONFLICT);
        } finally {
            stopWebSocketClient(consumeClient2);
        }
    } finally {
        stopWebSocketClient(consumeClient1);
    }
}
 
Example 8
Source File: MaxWsConnectionsTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {

  List<Session> clients = new ArrayList<>();

  while (true) {

    URI wsUri = new URI("ws", null, "localhost", Integer.parseInt(getPort()), "/jsonrpc", null,
        null);

    WebSocketClient jettyClient = new WebSocketClient(new SslContextFactory(true));
    jettyClient.start();
    Session session = jettyClient
        .connect(new WebSocketClientSocket(), wsUri, new ClientUpgradeRequest()).get();

    clients.add(session);

    log.debug("WebSocket client {} connected", clients.size());

    Thread.sleep(100);

    if (!session.isOpen()) {
      if (clients.size() < MAX_WS_CONNECTIONS) {
        fail("WebSocket num " + clients.size() + " disconnected. MAX_WS_CONNECTION="
            + MAX_WS_CONNECTIONS);
      } else {
        log.debug("WebSocket client {} disconnected from server", clients.size());
        break;
      }
    } else {

      if (clients.size() > MAX_WS_CONNECTIONS) {
        fail("Server should close automatically WebSocket connection above " + MAX_WS_CONNECTIONS
            + " but it has " + clients.size() + " open connections");
      }
    }
  }

}
 
Example 9
Source File: EventClientTest.java    From dawnsci with Eclipse Public License 1.0 5 votes vote down vote up
@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 10
Source File: WebSocketAbstractSampler.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
public WebSocketConnection getConnectionWS (String connectionId, SampleResult sampleResult) throws Exception{
  	
  	
  	
  	URI uri = getUri();
  
  	String closeConnectionPattern = getCloseConnectionPattern();
  	int connectionTimeout;
  	
  	try {
  		connectionTimeout = Integer.parseInt(getConnectionTimeout());
      } catch (NumberFormatException ex) {
          log.warn("Request timeout is not a number; using the default connection timeout of " + DEFAULT_CONNECTION_TIMEOUT + "ms");
          connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
      }

  	SslContextFactory sslContexFactory = new SslContextFactory();
      sslContexFactory.setTrustAll(true);
      WebSocketClient webSocketClient = new WebSocketClient(sslContexFactory);
      WebSocketConnection webSocketConnection = factory.getWebSocketHandler(webSocketClient, closeConnectionPattern, getContentEncoding());
      
webSocketClient.start();
      
      ClientUpgradeRequest request = new ClientUpgradeRequest();
      setConnectionHeaders(request, getHeaderManager(), null);
      setConnectionCookie(webSocketClient, uri, getCookieManager());
      webSocketClient.connect(webSocketConnection, uri, request);
      
      for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()){
      	sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + entry.getKey() + ": ");
      	for (String s : entry.getValue()){
      		sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + entry.getValue() + " ");
      	}
      	sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + "\n");
      }
      
      sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + "\n\nCookies: \n\n");
      
      for (HttpCookie h : webSocketClient.getCookieStore().getCookies()){
      	sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + h);
      }

webSocketConnection.awaitOpen(connectionTimeout, TimeUnit.MILLISECONDS);

      
      if (!webSocketConnection.isConnected()){
  		return null;
      }
      
      connectionList.put(connectionId, webSocketConnection);
      
      return webSocketConnection;
  }
 
Example 11
Source File: TestWebSocketServerPushSource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@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 12
Source File: ExampleServerR5IT.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 4 votes vote down vote up
@Test
public void testWebsocketSubscription() throws Exception {

    /*
     * Create topic
     */
    SubscriptionTopic topic = new SubscriptionTopic();
    topic.getResourceTrigger().getQueryCriteria().setCurrent("Observation?status=final");

    /*
     * Create subscription
     */
    Subscription subscription = new Subscription();
    subscription.getTopic().setResource(topic);
    subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
    subscription.setStatus(Enumerations.SubscriptionState.REQUESTED);
    subscription.getChannelType()
            .setSystem("http://terminology.hl7.org/CodeSystem/subscription-channel-type")
            .setCode("websocket");
    subscription.setContentType("application/json");

    MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
    IIdType mySubscriptionId = methodOutcome.getId();

    // Wait for the subscription to be activated
    waitForSize(1, () -> ourClient.search().forResource(Subscription.class).where(Subscription.STATUS.exactly().code("active")).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute().getEntry().size());

    /*
     * Attach websocket
     */

    WebSocketClient myWebSocketClient = new WebSocketClient();
    SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);

    myWebSocketClient.start();
    URI echoUri = new URI("ws://localhost:" + ourPort + "/hapi-fhir-jpaserver/websocket");
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    ourLog.info("Connecting to : {}", echoUri);
    Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
    Session session = connection.get(2, TimeUnit.SECONDS);

    ourLog.info("Connected to WS: {}", session.isOpen());

    /*
     * Create a matching resource
     */
    Observation obs = new Observation();
    obs.setStatus(Enumerations.ObservationStatus.FINAL);
    ourClient.create().resource(obs).execute();

    // Give some time for the subscription to deliver
    Thread.sleep(2000);

    /*
     * Ensure that we receive a ping on the websocket
     */
    waitForSize(1, () -> mySocketImplementation.myPingCount);

    /*
     * Clean up
     */
    ourClient.delete().resourceById(mySubscriptionId).execute();
}
 
Example 13
Source File: V1_ProxyAuthenticationTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@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 14
Source File: JettyWebSocketClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@OnEnabled
@Override
public void startClient(final ConfigurationContext context) throws Exception{

    final SSLContextService sslService = context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);
    SslContextFactory sslContextFactory = null;
    if (sslService != null) {
        sslContextFactory = createSslFactory(sslService, false, false, null);
    }
    client = new WebSocketClient(sslContextFactory);

    configurePolicy(context, client.getPolicy());
    final String userName = context.getProperty(USER_NAME).evaluateAttributeExpressions().getValue();
    final String userPassword = context.getProperty(USER_PASSWORD).evaluateAttributeExpressions().getValue();
    if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(userPassword)) {
        final String charsetName = context.getProperty(AUTH_CHARSET).evaluateAttributeExpressions().getValue();
        if (StringUtils.isEmpty(charsetName)) {
            throw new IllegalArgumentException(AUTH_CHARSET.getDisplayName() + " was not specified.");
        }
        final Charset charset = Charset.forName(charsetName);
        final String base64String = Base64.encodeBase64String((userName + ":" + userPassword).getBytes(charset));
        authorizationHeader = "Basic " + base64String;
    } else {
        authorizationHeader = null;
    }

    client.start();
    activeSessions.clear();

    webSocketUri = new URI(context.getProperty(WS_URI).evaluateAttributeExpressions().getValue());
    connectionTimeoutMillis = context.getProperty(CONNECTION_TIMEOUT).evaluateAttributeExpressions().asTimePeriod(TimeUnit.MILLISECONDS);

    final Long sessionMaintenanceInterval = context.getProperty(SESSION_MAINTENANCE_INTERVAL).evaluateAttributeExpressions().asTimePeriod(TimeUnit.MILLISECONDS);

    sessionMaintenanceScheduler = Executors.newSingleThreadScheduledExecutor();
    sessionMaintenanceScheduler.scheduleAtFixedRate(() -> {
        try {
            maintainSessions();
        } catch (final Exception e) {
            getLogger().warn("Failed to maintain sessions due to {}", new Object[]{e}, e);
        }
    }, sessionMaintenanceInterval, sessionMaintenanceInterval, TimeUnit.MILLISECONDS);
}
 
Example 15
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Test(timeOut = 10000)
public void socketTest() throws Exception {
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/consumer/persistent/my-property/my-ns/my-topic1/my-sub1?subscriptionType=Failover";
    String readerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/reader/persistent/my-property/my-ns/my-topic1";
    String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/producer/persistent/my-property/my-ns/my-topic1/";

    URI consumeUri = URI.create(consumerUri);
    URI readUri = URI.create(readerUri);
    URI produceUri = URI.create(producerUri);

    WebSocketClient consumeClient1 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket1 = new SimpleConsumerSocket();
    WebSocketClient consumeClient2 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket2 = new SimpleConsumerSocket();
    WebSocketClient readClient = new WebSocketClient();
    SimpleConsumerSocket readSocket = new SimpleConsumerSocket();
    WebSocketClient produceClient = new WebSocketClient();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();

    try {
        consumeClient1.start();
        consumeClient2.start();
        ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest();
        ClientUpgradeRequest consumeRequest2 = new ClientUpgradeRequest();
        Future<Session> consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1);
        Future<Session> consumerFuture2 = consumeClient2.connect(consumeSocket2, consumeUri, consumeRequest2);
        log.info("Connecting to : {}", consumeUri);

        readClient.start();
        ClientUpgradeRequest readRequest = new ClientUpgradeRequest();
        Future<Session> readerFuture = readClient.connect(readSocket, readUri, readRequest);
        log.info("Connecting to : {}", readUri);

        // let it connect
        assertTrue(consumerFuture1.get().isOpen());
        assertTrue(consumerFuture2.get().isOpen());
        assertTrue(readerFuture.get().isOpen());

        // Also make sure subscriptions and reader are already created
        Thread.sleep(500);

        ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
        produceClient.start();
        Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest);
        assertTrue(producerFuture.get().isOpen());

        int retry = 0;
        int maxRetry = 400;
        while ((consumeSocket1.getReceivedMessagesCount() < 10 && consumeSocket2.getReceivedMessagesCount() < 10)
                || readSocket.getReceivedMessagesCount() < 10) {
            Thread.sleep(10);
            if (retry++ > maxRetry) {
                final String msg = String.format("Consumer still has not received the message after %s ms",
                        (maxRetry * 10));
                log.warn(msg);
                throw new IllegalStateException(msg);
            }
        }

        // if the subscription type is exclusive (default), either of the consumer sessions has already been closed
        assertTrue(consumerFuture1.get().isOpen());
        assertTrue(consumerFuture2.get().isOpen());
        assertTrue(produceSocket.getBuffer().size() > 0);

        if (consumeSocket1.getBuffer().size() > consumeSocket2.getBuffer().size()) {
            assertEquals(produceSocket.getBuffer(), consumeSocket1.getBuffer());
        } else {
            assertEquals(produceSocket.getBuffer(), consumeSocket2.getBuffer());
        }
        assertEquals(produceSocket.getBuffer(), readSocket.getBuffer());
    } finally {
        stopWebSocketClient(consumeClient1, consumeClient2, readClient, produceClient);
    }
}
 
Example 16
Source File: WebSocketTransportTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@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 17
Source File: WebSocketClientToKmsConnectionTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
@Test
public void reconnectTest() throws Exception {

  for (int i = 0; i < 2; i++) {

    String kmsUrl = kms.getWsUri();

    log.debug("Connecting to KMS in " + kmsUrl);

    WebSocketClient client = new WebSocketClient();
    WebSocketHandler socket = new WebSocketHandler();

    client.start();
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    Session wsSession = client.connect(socket, new URI(kmsUrl), request).get();

    wsSession.getRemote().sendString("xxxx");

    kms.stopKms();

    Thread.sleep(3000);

    kms.start();

  }
}
 
Example 18
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
/**
 * It verifies proxy topic-stats and proxy-metrics api
 *
 * @throws Exception
 */
@Test(timeOut = 10000)
public void testProxyStats() throws Exception {
    final String topic = "my-property/my-ns/my-topic6";
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/consumer/persistent/" + topic
            + "/my-sub?subscriptionType=Failover";
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/producer/persistent/" + topic + "/";
    final String readerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/reader/persistent/" + topic;
    System.out.println(consumerUri + ", " + producerUri);
    URI consumeUri = URI.create(consumerUri);
    URI produceUri = URI.create(producerUri);
    URI readUri = URI.create(readerUri);

    WebSocketClient consumeClient1 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket1 = new SimpleConsumerSocket();
    WebSocketClient produceClient = new WebSocketClient();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();
    WebSocketClient readClient = new WebSocketClient();
    SimpleConsumerSocket readSocket = new SimpleConsumerSocket();

    try {
        consumeClient1.start();
        ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest();
        Future<Session> consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1);
        log.info("Connecting to : {}", consumeUri);

        readClient.start();
        ClientUpgradeRequest readRequest = new ClientUpgradeRequest();
        Future<Session> readerFuture = readClient.connect(readSocket, readUri, readRequest);
        log.info("Connecting to : {}", readUri);

        assertTrue(consumerFuture1.get().isOpen());
        assertTrue(readerFuture.get().isOpen());

        Thread.sleep(500);

        ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
        produceClient.start();
        Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest);
        // let it connect

        assertTrue(producerFuture.get().isOpen());

        // sleep so, proxy can deliver few messages to consumers for stats
        int retry = 0;
        int maxRetry = 400;
        while (consumeSocket1.getReceivedMessagesCount() < 2) {
            Thread.sleep(10);
            if (retry++ > maxRetry) {
                final String msg = String.format("Consumer still has not received the message after %s ms", (maxRetry * 10));
                log.warn(msg);
                break;
            }
        }

        Client client = ClientBuilder.newClient(new ClientConfig().register(LoggingFeature.class));
        final String baseUrl = pulsar.getSafeWebServiceAddress()
                .replace(Integer.toString(pulsar.getConfiguration().getWebServicePort().get()),
                        (Integer.toString(proxyServer.getListenPortHTTP().get())))
                + "/admin/v2/proxy-stats/";

        // verify proxy metrics
        verifyProxyMetrics(client, baseUrl);

        // verify proxy stats
        verifyProxyStats(client, baseUrl, topic);

        // verify topic stat
        verifyTopicStat(client, baseUrl + "persistent/", topic);

    } finally {
        stopWebSocketClient(consumeClient1, produceClient, readClient);
    }
}
 
Example 19
Source File: HybridServiceTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@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 20
Source File: WebSocketClientToKmsConnectionTest.java    From kurento-java with Apache License 2.0 3 votes vote down vote up
@Test
public void errorSendingClosedKmsTest() throws Exception {

  String kmsUrl = kms.getWsUri();

  log.debug("Connecting to KMS in " + kmsUrl);

  WebSocketClient client = new WebSocketClient();
  WebSocketHandler socket = new WebSocketHandler();

  client.start();
  ClientUpgradeRequest request = new ClientUpgradeRequest();
  Session wsSession = client.connect(socket, new URI(kmsUrl), request).get();

  wsSession.getRemote().sendString("xxxx");

  kms.stopKms();

  Thread.sleep(3000);

  try {

    wsSession.getRemote().sendString("xxxx");
    fail("Trying to send to a closed WebSocket should raise an exception");
  } catch (Exception e) {

  }
}