use of org.eclipse.jetty.websocket.client.WebSocketClient in project pulsar by yahoo.
the class ProxyPublishConsumeTest method socketTest.
@Test(timeOut = 10000)
public void socketTest() throws Exception {
URI consumeUri = URI.create(CONSUME_URI);
URI produceUri = URI.create(PRODUCE_URI);
WebSocketClient consumeClient = new WebSocketClient();
SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
WebSocketClient produceClient = new WebSocketClient();
SimpleProducerSocket produceSocket = new SimpleProducerSocket();
try {
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);
// let it connect
Assert.assertTrue(consumerFuture.get().isOpen());
Assert.assertTrue(producerFuture.get().isOpen());
while (consumeSocket.getReceivedMessagesCount() < 10) {
Thread.sleep(10);
}
Assert.assertTrue(produceSocket.getBuffer().size() > 0);
Assert.assertEquals(produceSocket.getBuffer(), consumeSocket.getBuffer());
} finally {
ExecutorService executor = newFixedThreadPool(1);
try {
executor.submit(() -> {
try {
consumeClient.stop();
produceClient.stop();
log.info("proxy clients are stopped successfully");
} catch (Exception e) {
log.error(e.getMessage());
}
}).get(2, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("failed to close clients ", e);
}
executor.shutdownNow();
}
}
use of org.eclipse.jetty.websocket.client.WebSocketClient in project pulsar by yahoo.
the class ProxyPublishConsumeTls method socketTest.
@Test
public void socketTest() throws InterruptedException, NoSuchAlgorithmException, KeyManagementException {
URI consumeUri = URI.create(CONSUME_URI);
URI produceUri = URI.create(PRODUCE_URI);
KeyManager[] keyManagers = null;
TrustManager[] trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(keyManagers, trustManagers, new SecureRandom());
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setSslContext(sslCtx);
WebSocketClient consumeClient = new WebSocketClient(sslContextFactory);
SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
WebSocketClient produceClient = new WebSocketClient(sslContextFactory);
SimpleProducerSocket produceSocket = new SimpleProducerSocket();
try {
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);
// let it connect
Thread.sleep(1000);
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());
} catch (Throwable t) {
log.error(t.getMessage());
} finally {
ExecutorService executor = newFixedThreadPool(1);
try {
executor.submit(() -> {
try {
consumeClient.stop();
produceClient.stop();
log.info("proxy clients are stopped successfully");
} catch (Exception e) {
log.error(e.getMessage());
}
}).get(2, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("failed to close clients ", e);
}
executor.shutdownNow();
}
}
use of org.eclipse.jetty.websocket.client.WebSocketClient in project pulsar by yahoo.
the class PerformanceClient method runPerformanceTest.
public void runPerformanceTest(long messages, long limit, int numOfTopic, int sizeOfMessage, String baseUrl, String destination) throws InterruptedException, FileNotFoundException {
ExecutorService executor = Executors.newCachedThreadPool(new DefaultThreadFactory("pulsar-perf-producer-exec"));
HashMap<String, Tuple> producersMap = new HashMap<>();
String produceBaseEndPoint = baseUrl + destination;
for (int i = 0; i < numOfTopic; i++) {
String topic = produceBaseEndPoint + "1" + "/";
URI produceUri = URI.create(topic);
WebSocketClient produceClient = new WebSocketClient(new SslContextFactory(true));
ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
SimpleTestProducerSocket produceSocket = new SimpleTestProducerSocket();
try {
produceClient.start();
produceClient.connect(produceSocket, produceUri, produceRequest);
} catch (IOException e1) {
log.error("Fail in connecting: [{}]", e1.getMessage());
return;
} catch (Exception e1) {
log.error("Fail in starting client[{}]", e1.getMessage());
return;
}
producersMap.put(produceUri.toString(), new Tuple(produceClient, produceRequest, produceSocket));
}
// connection to be established
TimeUnit.SECONDS.sleep(5);
executor.submit(() -> {
try {
RateLimiter rateLimiter = RateLimiter.create(limit);
// Send messages on all topics/producers
long totalSent = 0;
while (true) {
for (String topic : producersMap.keySet()) {
if (messages > 0) {
if (totalSent++ >= messages) {
log.trace("------------------- DONE -----------------------");
Thread.sleep(10000);
System.exit(0);
}
}
rateLimiter.acquire();
if (producersMap.get(topic).getSocket().getSession() == null) {
Thread.sleep(10000);
System.exit(0);
}
producersMap.get(topic).getSocket().sendMsg((String) String.valueOf(totalSent), sizeOfMessage);
messagesSent.increment();
bytesSent.add(1000);
}
}
} catch (Throwable t) {
log.error(t.getMessage());
System.exit(0);
}
});
// Print report stats
long oldTime = System.nanoTime();
Histogram reportHistogram = null;
String statsFileName = "perf-websocket-producer-" + System.currentTimeMillis() + ".hgrm";
log.info("Dumping latency stats to %s \n", statsFileName);
PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false);
HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog);
// Some log header bits
histogramLogWriter.outputLogFormatVersion();
histogramLogWriter.outputLegend();
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
break;
}
long now = System.nanoTime();
double elapsed = (now - oldTime) / 1e9;
double rate = messagesSent.sumThenReset() / elapsed;
double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;
reportHistogram = SimpleTestProducerSocket.recorder.getIntervalHistogram(reportHistogram);
log.info("Throughput produced: {} msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} ms - 95pct: {} ms - 99pct: {} ms - 99.9pct: {} ms - 99.99pct: {} ms", throughputFormat.format(rate), throughputFormat.format(throughput), dec.format(reportHistogram.getMean() / 1000.0), dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0));
histogramLogWriter.outputIntervalHistogram(reportHistogram);
reportHistogram.reset();
oldTime = now;
}
TimeUnit.SECONDS.sleep(100);
executor.shutdown();
}
use of org.eclipse.jetty.websocket.client.WebSocketClient in project chassis by Kixeye.
the class WebSocketTransportTest method testWebSocketServiceWithJson.
@Test
public void testWebSocketServiceWithJson() 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 {
context.refresh();
final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
messageRegistry.registerType("stuff", TestObject.class);
wsClient.start();
QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);
Session session = wsClient.connect(webSocket, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())).get(5000, TimeUnit.MILLISECONDS);
Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), 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);
rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));
envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);
envelope = new Envelope("expectedError", null, null, null);
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);
envelope = new Envelope("unexpectedError", null, null, null);
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
} finally {
try {
wsClient.stop();
} finally {
context.close();
}
}
}
use of org.eclipse.jetty.websocket.client.WebSocketClient in project chassis by Kixeye.
the class WebSocketTransportTest method testWebSocketServiceWithProtobuf.
@Test
public void testWebSocketServiceWithProtobuf() 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 {
context.refresh();
final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class);
final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
messageRegistry.registerType("stuff", TestObject.class);
wsClient.start();
QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);
Session session = wsClient.connect(webSocket, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())).get(5000, TimeUnit.MILLISECONDS);
Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), 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);
rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));
envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);
envelope = new Envelope("expectedError", null, null, null);
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);
envelope = new Envelope("unexpectedError", null, null, null);
session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));
error = webSocket.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
} finally {
try {
wsClient.stop();
} finally {
context.close();
while (context.isActive()) {
Thread.sleep(100);
}
}
}
}
Aggregations