Search in sources :

Example 6 with XnioWorker

use of org.xnio.XnioWorker in project undertow by undertow-io.

the class Bootstrap method handleDeployment.

@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
    WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) deploymentInfo.getServletContextAttributes().get(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
    if (info == null) {
        return;
    }
    Supplier<XnioWorker> worker = info.getWorker();
    ByteBufferPool buffers = info.getBuffers();
    if (buffers == null) {
        ServerWebSocketContainer defaultContainer = UndertowContainerProvider.getDefaultContainer();
        if (defaultContainer == null) {
            throw JsrWebSocketLogger.ROOT_LOGGER.bufferPoolWasNullAndNoDefault();
        }
        JsrWebSocketLogger.ROOT_LOGGER.bufferPoolWasNull();
        buffers = defaultContainer.getBufferPool();
    }
    final List<ThreadSetupHandler> setup = new ArrayList<>();
    setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader()));
    setup.addAll(deploymentInfo.getThreadSetupActions());
    InetSocketAddress bind = null;
    if (info.getClientBindAddress() != null) {
        bind = new InetSocketAddress(info.getClientBindAddress(), 0);
    }
    List<Extension> extensions = new ArrayList<>();
    for (ExtensionHandshake e : info.getExtensions()) {
        extensions.add(new ExtensionImpl(e.getName(), Collections.emptyList()));
    }
    ServerWebSocketContainer container = new ServerWebSocketContainer(deploymentInfo.getClassIntrospecter(), servletContext.getClassLoader(), worker, buffers, setup, info.isDispatchToWorkerThread(), bind, info.getReconnectHandler(), extensions);
    try {
        for (Class<?> annotation : info.getAnnotatedEndpoints()) {
            container.addEndpoint(annotation);
        }
        for (ServerEndpointConfig programatic : info.getProgramaticEndpoints()) {
            container.addEndpoint(programatic);
        }
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
    servletContext.setAttribute(ServerContainer.class.getName(), container);
    info.containerReady(container);
    SecurityActions.addContainer(deploymentInfo.getClassLoader(), container);
    deploymentInfo.addListener(Servlets.listener(WebSocketListener.class));
    deploymentInfo.addDeploymentCompleteListener(new ServletContextListener() {

        @Override
        public void contextInitialized(ServletContextEvent sce) {
            container.validateDeployment();
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
}
Also used : ByteBufferPool(io.undertow.connector.ByteBufferPool) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServletContextListener(javax.servlet.ServletContextListener) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) ServletExtension(io.undertow.servlet.ServletExtension) Extension(javax.websocket.Extension) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) ContextClassLoaderSetupAction(io.undertow.servlet.core.ContextClassLoaderSetupAction) ExtensionHandshake(io.undertow.websockets.extensions.ExtensionHandshake) DeploymentException(javax.websocket.DeploymentException) ServletContextEvent(javax.servlet.ServletContextEvent) ServerContainer(javax.websocket.server.ServerContainer)

Example 7 with XnioWorker

use of org.xnio.XnioWorker in project undertow by undertow-io.

the class WebSocketExtensionBasicTestCase method testExtensionsHeaders.

/**
 * Simulate an extensions request.
 *
 * <pre>{@code
 *
 *    GET / HTTP/1.1
 *    User-Agent: AutobahnTestSuite/0.7.0-0.9.0
 *    Host: localhost:7777
 *    Upgrade: WebSocket
 *    Connection: Upgrade
 *    Pragma: no-cache
 *    Cache-Control: no-cache
 *    Sec-WebSocket-Key: pRAuwtkO0SUKzufqA2g+ig==
 *    Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover; client_max_window_bits
 *    Sec-WebSocket-Version: 13
 *
 * }
 * </pre>
 */
@Test
public void testExtensionsHeaders() throws Exception {
    XnioWorker client;
    Xnio xnio = Xnio.getInstance(WebSocketExtensionBasicTestCase.class.getClassLoader());
    client = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, 2).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
    WebSocketProtocolHandshakeHandler handler = webSocketDebugHandler().addExtension(new PerMessageDeflateHandshake());
    DebugExtensionsHeaderHandler debug = new DebugExtensionsHeaderHandler(handler);
    DefaultServer.setRootHandler(path().addPrefixPath("/", debug));
    final String SEC_WEBSOCKET_EXTENSIONS = "permessage-deflate; client_no_context_takeover; client_max_window_bits";
    // List format
    final String SEC_WEBSOCKET_EXTENSIONS_EXPECTED = "[permessage-deflate; client_no_context_takeover]";
    List<WebSocketExtension> extensions = WebSocketExtension.parse(SEC_WEBSOCKET_EXTENSIONS);
    final WebSocketClientNegotiation negotiation = new WebSocketClientNegotiation(null, extensions);
    Set<ExtensionHandshake> extensionHandshakes = new HashSet<>();
    extensionHandshakes.add(new PerMessageDeflateHandshake(true));
    final WebSocketChannel clientChannel = WebSocketClient.connect(client, null, DefaultServer.getBufferPool(), OptionMap.EMPTY, new URI(DefaultServer.getDefaultServerURL()), WebSocketVersion.V13, negotiation, extensionHandshakes).get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();
    clientChannel.getReceiveSetter().set(new AbstractReceiveListener() {

        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
            String data = message.getData();
            WebSocketLogger.ROOT_LOGGER.info("onFullTextMessage - Client - Received: " + data.getBytes().length + " bytes . Data: " + data);
            result.set(data);
            latch.countDown();
        }

        @Override
        protected void onFullCloseMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException {
            message.getData().close();
            WebSocketLogger.ROOT_LOGGER.info("onFullCloseMessage");
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            WebSocketLogger.ROOT_LOGGER.info("onError");
            super.onError(channel, error);
            error.printStackTrace();
            latch.countDown();
        }
    });
    clientChannel.resumeReceives();
    StreamSinkFrameChannel sendChannel = clientChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener("Hello, World!").setup(sendChannel);
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals("Hello, World!", result.get());
    clientChannel.sendClose();
    client.shutdown();
    stopWorker(client);
    Assert.assertEquals(SEC_WEBSOCKET_EXTENSIONS_EXPECTED, debug.getResponseExtensions().toString());
}
Also used : XnioWorker(org.xnio.XnioWorker) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) Xnio(org.xnio.Xnio) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) BufferedBinaryMessage(io.undertow.websockets.core.BufferedBinaryMessage) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) HashSet(java.util.HashSet) WebSocketExtension(io.undertow.websockets.WebSocketExtension) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) Test(org.junit.Test)

Example 8 with XnioWorker

use of org.xnio.XnioWorker in project undertow by undertow-io.

the class ModClusterProxyServer method main.

public static void main(final String[] args) throws IOException {
    final XnioWorker worker = Xnio.getInstance().createWorker(OptionMap.EMPTY);
    final Undertow server;
    final ModCluster modCluster = ModCluster.builder(worker).build();
    try {
        if (chost == null) {
            // We are going to guess it.
            chost = java.net.InetAddress.getLocalHost().getHostName();
            System.out.println("Using: " + chost + ":" + cport);
        }
        modCluster.start();
        // Create the proxy and mgmt handler
        final HttpHandler proxy = modCluster.createProxyHandler();
        final MCMPConfig config = MCMPConfig.webBuilder().setManagementHost(chost).setManagementPort(cport).enableAdvertise().getParent().build();
        final HttpHandler mcmp = config.create(modCluster, proxy);
        server = Undertow.builder().addHttpListener(cport, chost).addHttpListener(pport, phost).setHandler(mcmp).build();
        server.start();
        // Start advertising the mcmp handler
        modCluster.advertise(config);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) ModCluster(io.undertow.server.handlers.proxy.mod_cluster.ModCluster) XnioWorker(org.xnio.XnioWorker) MCMPConfig(io.undertow.server.handlers.proxy.mod_cluster.MCMPConfig) Undertow(io.undertow.Undertow) IOException(java.io.IOException)

Example 9 with XnioWorker

use of org.xnio.XnioWorker in project undertow by undertow-io.

the class StopServerWithExternalWorkerUtils method stopServerAndWorker.

/**
 * Stops the server and the external worker associated with it. Blocks until
 * the worker has fully stopped.
 *
 * @param server the Undertow server
 */
public static void stopServerAndWorker(Undertow server) {
    final XnioWorker worker = server.getWorker();
    server.stop();
    stopWorker(worker);
}
Also used : XnioWorker(org.xnio.XnioWorker)

Example 10 with XnioWorker

use of org.xnio.XnioWorker in project undertow by undertow-io.

the class StopServerWithExternalWorkerUtils method stopServer.

/**
 * Stops only the server, keeping its external worker up and unchanged. After the server
 * is stopped, waits for a full worker runnable cycle to complete, plus a sleep time, to
 * prevent the time window in which the closing server is still bound to the associated
 * address.
 * This operation blocks until the worker finishes executing an empty Runnable task.
 *
 * @param server the Undertow server
 */
public static void stopServer(Undertow server) {
    final XnioWorker worker = server.getWorker();
    server.stop();
    waitWorkerRunnableCycle(worker);
}
Also used : XnioWorker(org.xnio.XnioWorker)

Aggregations

XnioWorker (org.xnio.XnioWorker)27 IOException (java.io.IOException)15 Xnio (org.xnio.Xnio)13 HttpHandler (io.undertow.server.HttpHandler)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 HttpServerExchange (io.undertow.server.HttpServerExchange)5 PathHandler (io.undertow.server.handlers.PathHandler)5 BeforeClass (org.junit.BeforeClass)5 OptionMap (org.xnio.OptionMap)5 DefaultByteBufferPool (io.undertow.server.DefaultByteBufferPool)4 InetSocketAddress (java.net.InetSocketAddress)4 URI (java.net.URI)4 Undertow (io.undertow.Undertow)3 ByteBufferPool (io.undertow.connector.ByteBufferPool)3 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)3 ServletContainer (io.undertow.servlet.api.ServletContainer)3 Test (org.junit.Test)3 ChannelListener (org.xnio.ChannelListener)3 Predicate (io.undertow.predicate.Predicate)2 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)2