Search in sources :

Example 41 with Endpoint

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

the class JsrWebSocketServer07Test method testCloseFrame.

@org.junit.Test
public void testCloseFrame() throws Exception {
    final int code = 1000;
    final String reasonText = "TEST";
    final AtomicReference<CloseReason> reason = new AtomicReference<>();
    ByteBuffer payload = ByteBuffer.allocate(reasonText.length() + 2);
    payload.putShort((short) code);
    payload.put(reasonText.getBytes(StandardCharsets.UTF_8));
    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.getWorkerSupplier(), DefaultServer.getBufferPool(), Collections.emptyList(), 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, reasonText), new FrameChecker(CloseWebSocketFrame.class, payload.array(), latch));
    // FIXME UNDERTOW-1862 assertEquals(DONE, latch.getIoFuture().await());
    latch.getIoFuture().await();
    clientLatch.await();
    assertEquals(code, reason.get().getCloseCode().getCode());
    assertEquals(reasonText, reason.get().getReasonPhrase());
    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)

Example 42 with Endpoint

use of javax.websocket.Endpoint 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.getWorkerSupplier(), DefaultServer.getBufferPool(), Collections.emptyList(), 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));
    assertEquals(DONE, latch.getIoFuture().await(10, TimeUnit.SECONDS));
    clientLatch.await();
    assertEquals(code, reason.get().getCloseCode().getCode());
    assertEquals("", reason.get().getReasonPhrase());
    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)

Example 43 with Endpoint

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

the class JsrWebSocketServer07Test method testTextByCompletion.

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

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

                @Override
                public void onMessage(String message) {
                    session.getAsyncRemote().sendText(message, result -> {
                        sendResult.set(result);
                        if (result.getException() != null) {
                            latch2.setException(new IOException(result.getException()));
                        } else {
                            latch2.setResult(null);
                        }
                    });
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorkerSupplier(), DefaultServer.getBufferPool(), Collections.emptyList(), 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 TextWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, payload, latch));
    // FIXME UNDERTOW-1862 assertEquals(DONE, latch.getIoFuture().await());
    latch.getIoFuture().await();
    assertEquals(DONE, latch2.getIoFuture().await());
    SendResult result = sendResult.get();
    Assert.assertNotNull(result);
    assertNull(result.getException());
    client.destroy();
}
Also used : ServletException(javax.servlet.ServletException) TestClassIntrospector(io.undertow.servlet.test.util.TestClassIntrospector) FrameChecker(io.undertow.websockets.utils.FrameChecker) ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) Endpoint(javax.websocket.Endpoint) Future(java.util.concurrent.Future) MessageHandler(javax.websocket.MessageHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) URI(java.net.URI) NetworkUtils(io.undertow.util.NetworkUtils) SendResult(javax.websocket.SendResult) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) Session(javax.websocket.Session) ContainerProvider(javax.websocket.ContainerProvider) DefaultServer(io.undertow.testutils.DefaultServer) FilterInfo(io.undertow.servlet.api.FilterInfo) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) Writer(java.io.Writer) AjpIgnore(io.undertow.testutils.AjpIgnore) UndertowSession(io.undertow.websockets.jsr.UndertowSession) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) CloseReason(javax.websocket.CloseReason) HttpOneOnly(io.undertow.testutils.HttpOneOnly) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) SendHandler(javax.websocket.SendHandler) WebSocketVersion(io.netty.handler.codec.http.websocketx.WebSocketVersion) PathHandler(io.undertow.server.handlers.PathHandler) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) OutputStream(java.io.OutputStream) EndpointConfig(javax.websocket.EndpointConfig) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) JsrWebSocketFilter(io.undertow.websockets.jsr.JsrWebSocketFilter) ServletContainer(io.undertow.servlet.api.ServletContainer) DeploymentManager(io.undertow.servlet.api.DeploymentManager) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) TimeUnit(java.util.concurrent.TimeUnit) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) DONE(org.xnio.IoFuture.Status.DONE) Assert.assertNull(org.junit.Assert.assertNull) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) FutureResult(org.xnio.FutureResult) DispatcherType(javax.servlet.DispatcherType) Assert(org.junit.Assert) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) MessageHandler(javax.websocket.MessageHandler) URI(java.net.URI) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) FutureResult(org.xnio.FutureResult) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) SendResult(javax.websocket.SendResult) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) FrameChecker(io.undertow.websockets.utils.FrameChecker) ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession)

Example 44 with Endpoint

use of javax.websocket.Endpoint 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.getWorkerSupplier(), DefaultServer.getBufferPool(), Collections.emptyList(), 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));
    // FIXME UNDERTOW-1862 assertEquals(DONE, latch.getIoFuture().await());
    latch.getIoFuture().get();
    Future<Void> result = sendResult.get();
    /* FIXME result.wait(4000);
        assertTrue(result.isDone());*/
    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) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession)

Example 45 with Endpoint

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

the class EndpointSessionHandler method onConnect.

@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    ConfiguredServerEndpoint config = HandshakeUtil.getConfig(channel);
    try {
        if (container.isClosed()) {
            // if the underlying container is closed we just reject
            channel.sendClose();
            channel.resumeReceives();
            return;
        }
        InstanceFactory<?> endpointFactory = config.getEndpointFactory();
        ServerEndpointConfig.Configurator configurator = config.getEndpointConfiguration().getConfigurator();
        final InstanceHandle<?> instance;
        DefaultContainerConfigurator.setCurrentInstanceFactory(endpointFactory);
        final Object instanceFromConfigurator = configurator.getEndpointInstance(config.getEndpointConfiguration().getEndpointClass());
        final InstanceHandle<?> factoryInstance = DefaultContainerConfigurator.clearCurrentInstanceFactory();
        if (factoryInstance == null) {
            instance = new ImmediateInstanceHandle<>(instanceFromConfigurator);
        } else if (factoryInstance.getInstance() == instanceFromConfigurator) {
            instance = factoryInstance;
        } else {
            // the default instance has been wrapped
            instance = new InstanceHandle<Object>() {

                @Override
                public Object getInstance() {
                    return instanceFromConfigurator;
                }

                @Override
                public void release() {
                    factoryInstance.release();
                }
            };
        }
        ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        Principal principal = exchange.getAttachment(HandshakeUtil.PRINCIPAL);
        if (principal == null) {
            if (src.getServletRequest() instanceof HttpServletRequest) {
                principal = ((HttpServletRequest) src.getServletRequest()).getUserPrincipal();
            } else {
                principal = src.getOriginalRequest().getUserPrincipal();
            }
        }
        final InstanceHandle<Endpoint> endpointInstance;
        if (config.getAnnotatedEndpointFactory() != null) {
            final AnnotatedEndpoint annotated = config.getAnnotatedEndpointFactory().createInstance(instance);
            endpointInstance = new InstanceHandle<Endpoint>() {

                @Override
                public Endpoint getInstance() {
                    return annotated;
                }

                @Override
                public void release() {
                    instance.release();
                }
            };
        } else {
            endpointInstance = (InstanceHandle<Endpoint>) instance;
        }
        UndertowSession session = new UndertowSession(channel, URI.create(exchange.getRequestURI()), exchange.getAttachment(HandshakeUtil.PATH_PARAMS), exchange.getRequestParameters(), this, principal, endpointInstance, config.getEndpointConfiguration(), exchange.getQueryString(), config.getEncodingFactory().createEncoding(config.getEndpointConfiguration()), config, channel.getSubProtocol(), Collections.<Extension>emptyList(), null);
        config.addOpenSession(session);
        session.setMaxBinaryMessageBufferSize(getContainer().getDefaultMaxBinaryMessageBufferSize());
        session.setMaxTextMessageBufferSize(getContainer().getDefaultMaxTextMessageBufferSize());
        session.setMaxIdleTimeout(getContainer().getDefaultMaxSessionIdleTimeout());
        session.getAsyncRemote().setSendTimeout(getContainer().getDefaultAsyncSendTimeout());
        try {
            endpointInstance.getInstance().onOpen(session, config.getEndpointConfiguration());
        } catch (Exception e) {
            endpointInstance.getInstance().onError(session, e);
            IoUtils.safeClose(session);
        }
        channel.resumeReceives();
    } catch (Exception e) {
        JsrWebSocketLogger.REQUEST_LOGGER.endpointCreationFailed(e);
        IoUtils.safeClose(channel);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) HttpServletRequest(javax.servlet.http.HttpServletRequest) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) Endpoint(javax.websocket.Endpoint) InstanceHandle(io.undertow.servlet.api.InstanceHandle) ImmediateInstanceHandle(io.undertow.servlet.util.ImmediateInstanceHandle) Principal(java.security.Principal)

Aggregations

Endpoint (javax.websocket.Endpoint)46 Session (javax.websocket.Session)29 URI (java.net.URI)24 EndpointConfig (javax.websocket.EndpointConfig)24 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)20 AtomicReference (java.util.concurrent.atomic.AtomicReference)18 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 FutureResult (org.xnio.FutureResult)14 IOException (java.io.IOException)13 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)12 MessageHandler (javax.websocket.MessageHandler)12 ByteBuffer (java.nio.ByteBuffer)11 ServerEndpoint (javax.websocket.server.ServerEndpoint)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 ClientEndpoint (javax.websocket.ClientEndpoint)10