Search in sources :

Example 36 with CloseReason

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

the class WebsocketStressTestCase method websocketFragmentationStressTestCase.

@Test
public void websocketFragmentationStressTestCase() throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final CountDownLatch done = new CountDownLatch(1);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; ++i) {
        sb.append("message ");
        sb.append(i);
    }
    String toSend = sb.toString();
    final Session session = defaultContainer.connectToServer(new Endpoint() {

        @Override
        public void onOpen(Session session, EndpointConfig config) {
            session.addMessageHandler(new MessageHandler.Partial<byte[]>() {

                @Override
                public void onMessage(byte[] bytes, boolean b) {
                    try {
                        out.write(bytes);
                    } catch (IOException e) {
                        e.printStackTrace();
                        done.countDown();
                    }
                    if (b) {
                        done.countDown();
                    }
                }
            });
        }

        @Override
        public void onClose(Session session, CloseReason closeReason) {
            done.countDown();
        }

        @Override
        public void onError(Session session, Throwable thr) {
            thr.printStackTrace();
            done.countDown();
        }
    }, null, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/stress"));
    OutputStream stream = session.getBasicRemote().getSendStream();
    for (int i = 0; i < toSend.length(); ++i) {
        stream.write(toSend.charAt(i));
        stream.flush();
    }
    stream.close();
    assertTrue(done.await(40, TimeUnit.SECONDS));
    assertEquals(toSend, new String(out.toByteArray()));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) Endpoint(javax.websocket.Endpoint) Endpoint(javax.websocket.Endpoint) CloseReason(javax.websocket.CloseReason) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) Test(org.junit.Test)

Example 37 with CloseReason

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

the class ServerWebSocketContainer method pause.

/**
 * Pauses the container
 * @param listener
 */
public synchronized void pause(PauseListener listener) {
    closed = true;
    if (configuredServerEndpoints.isEmpty()) {
        listener.paused();
        return;
    }
    if (listener != null) {
        pauseListeners.add(listener);
    }
    for (ConfiguredServerEndpoint endpoint : configuredServerEndpoints) {
        for (final Session session : endpoint.getOpenSessions()) {
            ((UndertowSession) session).getExecutor().execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, ""));
                    } catch (Exception e) {
                        JsrWebSocketLogger.ROOT_LOGGER.couldNotCloseOnUndeploy(e);
                    }
                }
            });
        }
    }
    Runnable done = new Runnable() {

        int count = configuredServerEndpoints.size();

        @Override
        public synchronized void run() {
            List<PauseListener> copy = null;
            synchronized (ServerWebSocketContainer.this) {
                count--;
                if (count == 0) {
                    copy = new ArrayList<>(pauseListeners);
                    pauseListeners.clear();
                }
            }
            if (copy != null) {
                for (PauseListener p : copy) {
                    p.paused();
                }
            }
        }
    };
    for (ConfiguredServerEndpoint endpoint : configuredServerEndpoints) {
        endpoint.notifyClosed(done);
    }
}
Also used : CloseReason(javax.websocket.CloseReason) ServletException(javax.servlet.ServletException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DeploymentException(javax.websocket.DeploymentException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) UpgradeFailedException(org.xnio.http.UpgradeFailedException) Session(javax.websocket.Session)

Example 38 with CloseReason

use of javax.websocket.CloseReason 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 39 with CloseReason

use of javax.websocket.CloseReason 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 40 with CloseReason

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

the class FrameHandler method onFullCloseMessage.

@Override
protected void onFullCloseMessage(final WebSocketChannel channel, final BufferedBinaryMessage message) {
    if (session.isSessionClosed()) {
        // we have already handled this when we sent the close frame
        message.getData().free();
        return;
    }
    final Pooled<ByteBuffer[]> pooled = message.getData();
    final ByteBuffer singleBuffer = toBuffer(pooled.getResource());
    final ByteBuffer toSend = singleBuffer.duplicate();
    // send the close immediatly
    WebSockets.sendClose(toSend, channel, null);
    session.getContainer().invokeEndpointMethod(executor, new Runnable() {

        @Override
        public void run() {
            try {
                if (singleBuffer.remaining() > 1) {
                    final CloseReason.CloseCode code = CloseReason.CloseCodes.getCloseCode(singleBuffer.getShort());
                    final String reasonPhrase = singleBuffer.remaining() > 1 ? new UTF8Output(singleBuffer).extract() : null;
                    session.closeInternal(new CloseReason(code, reasonPhrase));
                } else {
                    session.closeInternal(new CloseReason(CloseReason.CloseCodes.NO_STATUS_CODE, null));
                }
            } catch (IOException e) {
                invokeOnError(e);
            } finally {
                pooled.close();
            }
        }
    });
}
Also used : CloseReason(javax.websocket.CloseReason) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) UTF8Output(io.undertow.websockets.core.UTF8Output)

Aggregations

CloseReason (javax.websocket.CloseReason)47 IOException (java.io.IOException)26 Session (javax.websocket.Session)21 URI (java.net.URI)9 Test (org.junit.Test)8 Endpoint (javax.websocket.Endpoint)7 EndpointConfig (javax.websocket.EndpointConfig)7 ByteBuffer (java.nio.ByteBuffer)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 WebSocketContainer (javax.websocket.WebSocketContainer)4 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)3 UndertowSession (io.undertow.websockets.jsr.UndertowSession)3 Iterator (java.util.Iterator)3 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)3 UserPass (com.disney.groovity.tags.Credentials.UserPass)2 ScriptHelper (com.disney.groovity.util.ScriptHelper)2 AuthorizationRequest (com.disney.http.auth.AuthorizationRequest)2 DigestAuthorization (com.disney.http.auth.DigestAuthorization)2