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

The following examples show how to use org.eclipse.jetty.websocket.client.WebSocketClient#connect() . 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: BoseSoundTouchHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private synchronized void openConnection() {
    closeConnection();
    try {
        client = new WebSocketClient();
        // we need longer timeouts for web socket.
        client.setMaxIdleTimeout(360 * 1000);
        // Port seems to be hard coded, therefore no user input or discovery is necessary
        String wsUrl = "ws://" + getIPAddress() + ":8080/";
        logger.debug("{}: Connecting to: {}", getDeviceName(), wsUrl);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setSubProtocols("gabbo");
        client.setStopTimeout(1000);
        client.start();
        client.connect(this, new URI(wsUrl), request);
    } catch (Exception e) {
        onWebSocketError(e);
    }
}
 
Example 2
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 3
Source File: LoggregatorClient.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
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 4
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 5
Source File: WsClient.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
    client = new WebSocketClient();
    client.start();
    URI echoUri = new URI(destUri);
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    socket = new SimpleWebSocket(sessionListener);
    client.connect(socket, echoUri, request);
    socket.awaitOpen(10, TimeUnit.SECONDS);
}
 
Example 6
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 7
Source File: V1_ProxyAuthenticationTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void socketTest() throws Exception {
    final String topic = "prop/use/my-ns/my-topic1";
    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);

    consumeClient = new WebSocketClient();
    SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
    produceClient = new WebSocketClient();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();

    consumeClient.start();
    ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest();
    Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest);
    log.info("Connecting to : {}", consumeUri);

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

    consumeSocket.awaitClose(1, TimeUnit.SECONDS);
    produceSocket.awaitClose(1, TimeUnit.SECONDS);
    Assert.assertTrue(produceSocket.getBuffer().size() > 0);
    Assert.assertEquals(produceSocket.getBuffer(), consumeSocket.getBuffer());
}
 
Example 8
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void consumeMessagesInPartitionedTopicTest() throws Exception {
    final String namespace = "my-property/my-ns";
    final String topic = namespace + "/" + "my-topic7";
    admin.topics().createPartitionedTopic("persistent://" + topic, 3);

    final String subscription = "my-sub";
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/consumer/persistent/" + topic + "/" + subscription;
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/producer/persistent/" + topic;

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

    WebSocketClient consumeClient = new WebSocketClient();
    WebSocketClient produceClient = new WebSocketClient();

    SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();

    try {
        produceClient.start();
        ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
        Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest);
        producerFuture.get();
        produceSocket.sendMessage(100);
    } finally {
        stopWebSocketClient(produceClient);
    }

    Thread.sleep(500);

    try {
        consumeClient.start();
        ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest();
        Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest);
        consumerFuture.get();
    } finally {
        stopWebSocketClient(consumeClient);
    }
}
 
Example 9
Source File: ProxyAuthenticationTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void checkSocket() throws Exception {
    final String topic = "my-property/my-ns/my-topic1";
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/consumer/persistent/" + topic + "/my-sub";
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/producer/persistent/" + topic;
    URI consumeUri = URI.create(consumerUri);
    URI produceUri = URI.create(producerUri);

    consumeClient = new WebSocketClient();
    SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
    produceClient = new WebSocketClient();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();

    consumeClient.start();
    ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest();
    Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest);
    log.info("Connecting to : {}", consumeUri);

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

    consumeSocket.awaitClose(1, TimeUnit.SECONDS);
    produceSocket.awaitClose(1, TimeUnit.SECONDS);
    Assert.assertTrue(produceSocket.getBuffer().size() > 0);
    Assert.assertEquals(produceSocket.getBuffer(), consumeSocket.getBuffer());
}
 
Example 10
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void conflictingProducerTest() throws Exception {
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/producer/persistent/my-property/my-ns/my-topic4?producerName=my-producer";
    URI produceUri = URI.create(producerUri);

    WebSocketClient produceClient1 = new WebSocketClient();
    WebSocketClient produceClient2 = new WebSocketClient();
    SimpleProducerSocket produceSocket1 = new SimpleProducerSocket();
    SimpleProducerSocket produceSocket2 = new SimpleProducerSocket();

    try {
        produceClient1.start();
        ClientUpgradeRequest produceRequest1 = new ClientUpgradeRequest();
        Future<Session> producerFuture1 = produceClient1.connect(produceSocket1, produceUri, produceRequest1);
        producerFuture1.get();

        try {
            produceClient2.start();
            ClientUpgradeRequest produceRequest2 = new ClientUpgradeRequest();
            Future<Session> producerFuture2 = produceClient2.connect(produceSocket2, produceUri, produceRequest2);
            producerFuture2.get();
            fail("should fail: conflicting producer name");
        } catch (Exception e) {
            // Expected
            assertTrue(e.getCause() instanceof UpgradeException);
            assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                    HttpServletResponse.SC_CONFLICT);
        } finally {
            stopWebSocketClient(produceClient2);
        }
    } finally {
        stopWebSocketClient(produceClient1);
    }
}
 
Example 11
Source File: RosBridge.java    From java_rosbridge with GNU Lesser General Public License v3.0 5 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
 */
public void connect(String rosBridgeURI){
	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);

	} catch (Throwable t) {
		t.printStackTrace();
	}
}
 
Example 12
Source File: WebSocketTest.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
@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();
	}
}
 
Example 13
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 14
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 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: 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 = "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 17
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 18
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 19
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 20
Source File: ExampleServerR4IT.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 4 votes vote down vote up
@Test
public void testWebsocketSubscription() throws Exception {
    /*
     * Create subscription
     */
    Subscription subscription = new Subscription();
    subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
    subscription.setStatus(Subscription.SubscriptionStatus.REQUESTED);
    subscription.setCriteria("Observation?status=final");

    Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
    channel.setType(Subscription.SubscriptionChannelType.WEBSOCKET);
    channel.setPayload("application/json");
    subscription.setChannel(channel);

    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(Observation.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();
}