Search in sources :

Example 11 with EndpointConfig

use of javax.websocket.EndpointConfig in project undertow by undertow-io.

the class TestMessagesReceivedInOrder method testMessagesReceivedInOrder.

@Test
public void testMessagesReceivedInOrder() throws Exception {
    stacks.clear();
    EchoSocket.receivedEchos = new FutureResult<>();
    final ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    final CountDownLatch done = new CountDownLatch(1);
    final AtomicReference<String> error = new AtomicReference<>();
    ContainerProvider.getWebSocketContainer().connectToServer(new Endpoint() {

        @Override
        public void onOpen(final Session session, EndpointConfig endpointConfig) {
            try {
                RemoteEndpoint.Basic rem = session.getBasicRemote();
                List<String> messages = new ArrayList<>();
                for (int i = 0; i < MESSAGES; i++) {
                    byte[] data = new byte[2048];
                    (new Random()).nextBytes(data);
                    String crc = md5(data);
                    rem.sendBinary(ByteBuffer.wrap(data));
                    messages.add(crc);
                }
                List<String> received = EchoSocket.receivedEchos.getIoFuture().get();
                StringBuilder sb = new StringBuilder();
                boolean fail = false;
                for (int i = 0; i < messages.size(); i++) {
                    if (received.size() <= i) {
                        fail = true;
                        sb.append(i + ": should be " + messages.get(i) + " but is empty.");
                    } else {
                        if (!messages.get(i).equals(received.get(i))) {
                            fail = true;
                            sb.append(i + ": should be " + messages.get(i) + " but is " + received.get(i) + " (but found at " + received.indexOf(messages.get(i)) + ").");
                        }
                    }
                }
                if (fail) {
                    error.set(sb.toString());
                }
                done.countDown();
            } catch (Throwable t) {
                System.out.println(t);
            }
        }
    }, clientEndpointConfig, new URI(DefaultServer.getDefaultServerURL() + "/webSocket"));
    done.await(30, TimeUnit.SECONDS);
    if (error.get() != null) {
        Assert.fail(error.get());
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) Endpoint(javax.websocket.Endpoint) RemoteEndpoint(javax.websocket.RemoteEndpoint) ServerEndpoint(javax.websocket.server.ServerEndpoint) Random(java.util.Random) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) Test(org.junit.Test)

Example 12 with EndpointConfig

use of javax.websocket.EndpointConfig in project undertow by undertow-io.

the class JsrWebSocketServer07Test method testPingPong.

@org.junit.Test
public void testPingPong() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();
    class TestEndPoint extends Endpoint {

        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorker(), DefaultServer.getBufferPool(), Collections.EMPTY_LIST, false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new PingWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(PongWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    Assert.assertNull(cause.get());
    client.destroy();
}
Also used : ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) URI(java.net.URI) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) FutureResult(org.xnio.FutureResult) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) FrameChecker(io.undertow.websockets.utils.FrameChecker) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession) Test(org.junit.Test)

Example 13 with EndpointConfig

use of javax.websocket.EndpointConfig in project pinot by linkedin.

the class MeetupRsvpStream method run.

public void run() {
    try {
        final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
        final KafkaJSONMessageDecoder decoder = new KafkaJSONMessageDecoder();
        decoder.init(null, schema, null);
        client = ClientManager.createClient();
        client.connectToServer(new Endpoint() {

            @Override
            public void onOpen(Session session, EndpointConfig config) {
                try {
                    session.addMessageHandler(new MessageHandler.Whole<String>() {

                        @Override
                        public void onMessage(String message) {
                            try {
                                JSONObject messageJSON = new JSONObject(message);
                                JSONObject extracted = new JSONObject();
                                if (messageJSON.has("venue")) {
                                    JSONObject venue = messageJSON.getJSONObject("venue");
                                    extracted.put("venue_name", venue.getString("venue_name"));
                                }
                                if (messageJSON.has("event")) {
                                    JSONObject event = messageJSON.getJSONObject("event");
                                    extracted.put("event_name", event.getString("event_name"));
                                    extracted.put("event_id", event.getString("event_id"));
                                    extracted.put("event_time", event.getLong("time"));
                                }
                                if (messageJSON.has("group")) {
                                    JSONObject group = messageJSON.getJSONObject("group");
                                    extracted.put("group_city", group.getString("group_city"));
                                    extracted.put("group_country", group.getString("group_country"));
                                    extracted.put("group_id", group.getLong("group_id"));
                                    extracted.put("group_name", group.getString("group_name"));
                                }
                                extracted.put("mtime", messageJSON.getLong("mtime"));
                                extracted.put("rsvp_count", 1);
                                if (keepPublishing) {
                                    KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>("meetupRSVPEvents", extracted.toString().getBytes("UTF-8"));
                                    producer.send(data);
                                }
                            } catch (Exception e) {
                            //LOGGER.error("error processing raw event ", e);
                            }
                        }
                    });
                    session.getBasicRemote().sendText("");
                } catch (IOException e) {
                //LOGGER.error("found an event where data did not have all the fields, don't care about for quickstart");
                }
            }
        }, cec, new URI("ws://stream.meetup.com/2/rsvps"));
    } catch (Exception e) {
    //e.printStackTrace();
    }
}
Also used : KafkaJSONMessageDecoder(com.linkedin.pinot.core.realtime.impl.kafka.KafkaJSONMessageDecoder) IOException(java.io.IOException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Endpoint(javax.websocket.Endpoint) JSONObject(org.json.JSONObject) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) KeyedMessage(kafka.producer.KeyedMessage) EndpointConfig(javax.websocket.EndpointConfig) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) Session(javax.websocket.Session)

Example 14 with EndpointConfig

use of javax.websocket.EndpointConfig in project undertow by undertow-io.

the class JsrWebSocketServer07Test method testBinaryWithByteBufferByFuture.

@org.junit.Test
public void testBinaryWithByteBufferByFuture() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Future<Void>> sendResult = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();
    class TestEndPoint extends Endpoint {

        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
            session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {

                @Override
                public void onMessage(ByteBuffer message) {
                    ByteBuffer buf = ByteBuffer.allocate(message.remaining());
                    buf.put(message);
                    buf.flip();
                    sendResult.set(session.getAsyncRemote().sendBinary(buf));
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorker(), DefaultServer.getBufferPool(), Collections.EMPTY_LIST, false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    Future<Void> result = sendResult.get();
    client.destroy();
}
Also used : MessageHandler(javax.websocket.MessageHandler) ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) FutureResult(org.xnio.FutureResult) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) FrameChecker(io.undertow.websockets.utils.FrameChecker) Future(java.util.concurrent.Future) IoFuture(org.xnio.IoFuture) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession) Test(org.junit.Test)

Example 15 with EndpointConfig

use of javax.websocket.EndpointConfig in project undertow by undertow-io.

the class JsrWebSocketServer07Test method testCloseFrameWithoutReasonBody.

/**
     * Section 5.5.1 of RFC 6455 says the reason body is optional
     */
@org.junit.Test
public void testCloseFrameWithoutReasonBody() throws Exception {
    final int code = 1000;
    final AtomicReference<CloseReason> reason = new AtomicReference<>();
    ByteBuffer payload = ByteBuffer.allocate(2);
    payload.putShort((short) code);
    payload.flip();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();
    final CountDownLatch clientLatch = new CountDownLatch(1);
    final AtomicInteger closeCount = new AtomicInteger();
    class TestEndPoint extends Endpoint {

        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
        }

        @Override
        public void onClose(Session session, CloseReason closeReason) {
            closeCount.incrementAndGet();
            reason.set(closeReason);
            clientLatch.countDown();
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorker(), DefaultServer.getBufferPool(), Collections.EMPTY_LIST, false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new CloseWebSocketFrame(code, null), new FrameChecker(CloseWebSocketFrame.class, payload.array(), latch));
    if (latch.getIoFuture().await(10, TimeUnit.SECONDS) != IoFuture.Status.DONE) {
        Assert.fail();
    }
    latch.getIoFuture().get();
    clientLatch.await();
    Assert.assertEquals(code, reason.get().getCloseCode().getCode());
    Assert.assertEquals("", reason.get().getReasonPhrase());
    Assert.assertEquals(1, closeCount.get());
    client.destroy();
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) FutureResult(org.xnio.FutureResult) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) CloseReason(javax.websocket.CloseReason) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FrameChecker(io.undertow.websockets.utils.FrameChecker) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession) Test(org.junit.Test)

Aggregations

Endpoint (javax.websocket.Endpoint)20 EndpointConfig (javax.websocket.EndpointConfig)20 Session (javax.websocket.Session)20 Test (org.junit.Test)19 URI (java.net.URI)18 AtomicReference (java.util.concurrent.atomic.AtomicReference)15 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)14 UndertowSession (io.undertow.websockets.jsr.UndertowSession)14 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)14 FrameChecker (io.undertow.websockets.utils.FrameChecker)14 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)14 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)14 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)14 FutureResult (org.xnio.FutureResult)14 MessageHandler (javax.websocket.MessageHandler)11 IOException (java.io.IOException)7 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)6 ByteBuffer (java.nio.ByteBuffer)6 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)5 CountDownLatch (java.util.concurrent.CountDownLatch)5