Search in sources :

Example 21 with XnioWorker

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

the class ModClusterTestSetup method main.

public static void main(final String[] args) throws IOException {
    final Undertow server;
    final XnioWorker worker = Xnio.getInstance().createWorker(OptionMap.EMPTY);
    final ModCluster modCluster = ModCluster.builder(worker).setHealthCheckInterval(TimeUnit.SECONDS.toMillis(3)).setRemoveBrokenNodes(TimeUnit.SECONDS.toMillis(30)).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.builder().setManagementHost(chost).setManagementPort(cport).enableAdvertise().setSecurityKey("secret").getParent().build();
        final MCMPConfig webConfig = MCMPConfig.webBuilder().setManagementHost(chost).setManagementPort(cport).build();
        // Setup specific rewrite rules for the mod_cluster tests.
        final HttpHandler root = Handlers.predicates(PredicatedHandlersParser.parse("regex[pattern='cluster.domain.com', value='%{i,Host}'] and equals[%R, '/'] -> rewrite['/myapp/MyCount']\n" + "regex[pattern='cluster.domain.org', value='%{i,Host}'] and regex['/(.*)'] -> rewrite['/myapp/${1}']\n" + "regex[pattern='cluster.domain.net', value='%{i,Host}'] and regex['/test/(.*)'] -> rewrite['/myapp/${1}']\n" + "regex[pattern='cluster.domain.info', value='%{i,Host}'] and path-template['/{one}/{two}'] -> rewrite['/test/${two}?partnerpath=/${one}&%q']\n", ModClusterTestSetup.class.getClassLoader()), proxy);
        final HttpHandler mcmp = config.create(modCluster, root);
        final HttpHandler web = webConfig.create(modCluster, ResponseCodeHandler.HANDLE_404);
        server = Undertow.builder().addHttpListener(cport, chost).addHttpListener(pport, phost).setHandler(Handlers.path(mcmp).addPrefixPath("/mod_cluster_manager", web)).build();
        server.start();
        // Start advertising the mcmp handler
        modCluster.advertise(config);
        final Runnable r = new Runnable() {

            @Override
            public void run() {
                modCluster.stop();
                server.stop();
            }
        };
        Runtime.getRuntime().addShutdownHook(new Thread(r));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) XnioWorker(org.xnio.XnioWorker) Undertow(io.undertow.Undertow) IOException(java.io.IOException)

Example 22 with XnioWorker

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

the class WebSocketExtensionBasicTestCase method testLongMessageWithoutExtensions.

@Test
@Ignore
public void testLongMessageWithoutExtensions() 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 WebSocketClientNegotiation negotiation = null;
    final WebSocketChannel clientChannel = WebSocketClient.connect(client, DefaultServer.getBufferPool(), OptionMap.EMPTY, new URI("http://localhost:8080"), WebSocketVersion.V13, negotiation).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");
            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();
    int LONG_MSG = 75 * 1024;
    StringBuilder longMsg = new StringBuilder(LONG_MSG);
    for (int i = 0; i < LONG_MSG; i++) {
        longMsg.append(new Integer(i).toString().charAt(0));
    }
    StreamSinkFrameChannel sendChannel = clientChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener(longMsg.toString()).setup(sendChannel);
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals(longMsg.toString(), result.get());
    clientChannel.sendClose();
    stopWorker(client);
}
Also used : XnioWorker(org.xnio.XnioWorker) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) 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) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 23 with XnioWorker

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

the class WebSocketExtensionBasicTestCase method testLongTextMessage.

@Test
public void testLongTextMessage() 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<WebSocketExtension> extensionsList = WebSocketExtension.parse(SEC_WEBSOCKET_EXTENSIONS);
    final WebSocketClientNegotiation negotiation = new WebSocketClientNegotiation(null, extensionsList);
    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.");
            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();
    int LONG_MSG = 125 * 1024;
    StringBuilder longMsg = new StringBuilder(LONG_MSG);
    for (int i = 0; i < LONG_MSG; i++) {
        longMsg.append(Integer.toString(i).charAt(0));
    }
    WebSockets.sendTextBlocking(longMsg.toString(), clientChannel);
    latch.await(300, TimeUnit.SECONDS);
    Assert.assertEquals(longMsg.toString(), result.get());
    clientChannel.sendClose();
    stopWorker(client);
}
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) HashSet(java.util.HashSet) WebSocketExtension(io.undertow.websockets.WebSocketExtension) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 24 with XnioWorker

use of org.xnio.XnioWorker in project indy by Commonjava.

the class HttpProxy method start.

@Override
public void start() throws IndyLifecycleException {
    if (!config.isEnabled()) {
        logger.info("HTTProx proxy is disabled.");
        return;
    }
    String bind;
    if (bootOptions.getBind() == null) {
        bind = "0.0.0.0";
    } else {
        bind = bootOptions.getBind();
    }
    logger.info("Starting HTTProx proxy on: {}:{}", bind, config.getPort());
    XnioWorker worker;
    try {
        worker = Xnio.getInstance().createWorker(OptionMap.EMPTY);
        final InetSocketAddress addr;
        if (config.getPort() < 1) {
            ThreadLocal<InetSocketAddress> using = new ThreadLocal<>();
            ThreadLocal<IOException> errorHolder = new ThreadLocal<>();
            server = PortFinder.findPortFor(16, (foundPort) -> {
                InetSocketAddress a = new InetSocketAddress(bind, config.getPort());
                AcceptingChannel<StreamConnection> result = worker.createStreamConnectionServer(a, acceptHandler, OptionMap.EMPTY);
                result.resumeAccepts();
                using.set(a);
                return result;
            });
            addr = using.get();
            config.setPort(addr.getPort());
        } else {
            addr = new InetSocketAddress(bind, config.getPort());
            server = worker.createStreamConnectionServer(addr, acceptHandler, OptionMap.EMPTY);
            server.resumeAccepts();
        }
        logger.info("HTTProxy listening on: {}", addr);
    } catch (IllegalArgumentException | IOException e) {
        throw new IndyLifecycleException("Failed to start HTTProx general content proxy: %s", e, e.getMessage());
    }
}
Also used : Logger(org.slf4j.Logger) Xnio(org.xnio.Xnio) ShutdownAction(org.commonjava.indy.action.ShutdownAction) XnioWorker(org.xnio.XnioWorker) LoggerFactory(org.slf4j.LoggerFactory) PortFinder(org.commonjava.propulsor.boot.PortFinder) IOException(java.io.IOException) IndyLifecycleException(org.commonjava.indy.action.IndyLifecycleException) AcceptingChannel(org.xnio.channels.AcceptingChannel) InetSocketAddress(java.net.InetSocketAddress) OptionMap(org.xnio.OptionMap) Inject(javax.inject.Inject) StreamConnection(org.xnio.StreamConnection) HttproxConfig(org.commonjava.indy.httprox.conf.HttproxConfig) StartupAction(org.commonjava.indy.action.StartupAction) BootOptions(org.commonjava.propulsor.boot.BootOptions) ProxyAcceptHandler(org.commonjava.indy.httprox.handler.ProxyAcceptHandler) ApplicationScoped(javax.enterprise.context.ApplicationScoped) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) IndyLifecycleException(org.commonjava.indy.action.IndyLifecycleException) AcceptingChannel(org.xnio.channels.AcceptingChannel)

Example 25 with XnioWorker

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

the class H2CUpgradeContinuationTestCase method beforeClass.

/**
 * Initializes the server with the H2C handler and adds the echo handler to
 * manage the requests.
 * @throws IOException Some error
 */
@BeforeClass
public static void beforeClass() throws IOException {
    // server and client pool is using 1024 for the buffer size
    smallPool = new DebuggingSlicePool(new DefaultByteBufferPool(true, 1024, 1000, 10, 100));
    final PathHandler path = new PathHandler().addExactPath(ECHO_PATH, new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            sendEchoResponse(exchange);
        }
    });
    server = Undertow.builder().setByteBufferPool(smallPool).addHttpListener(DefaultServer.getHostPort("default") + 1, DefaultServer.getHostAddress("default"), new Http2UpgradeHandler(path)).setSocketOption(Options.REUSE_ADDRESSES, true).build();
    server.start();
    // Create xnio worker
    final Xnio xnio = Xnio.getInstance();
    final XnioWorker xnioWorker = xnio.createWorker(null, OptionMap.builder().set(Options.WORKER_IO_THREADS, 8).set(Options.TCP_NODELAY, true).set(Options.KEEP_ALIVE, true).getMap());
    worker = xnioWorker;
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) Http2UpgradeHandler(io.undertow.server.protocol.http2.Http2UpgradeHandler) Xnio(org.xnio.Xnio) XnioWorker(org.xnio.XnioWorker) DebuggingSlicePool(io.undertow.testutils.DebuggingSlicePool) PathHandler(io.undertow.server.handlers.PathHandler) IOException(java.io.IOException) BeforeClass(org.junit.BeforeClass)

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