Package io.undertow

Examples of io.undertow.Undertow$ListenerConfig


            System.out.println("The HTTP2 spec requires certain cyphers that are not present in older JVM's");
            System.out.println("See section 9.2.2 of the HTTP2 specification for details");
            System.exit(1);
        }
        String bindAddress = System.getProperty("bind.address", "localhost");
        Undertow server = Undertow.builder()
                .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
                .setServerOption(UndertowOptions.ENABLE_SPDY, true)
                .addHttpListener(8080, bindAddress)
                .addHttpsListener(8443, bindAddress, createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore")))
                .setHandler(Handlers.header(predicate(secure(), resource(new FileResourceManager(new File(System.getProperty("example.directory", System.getProperty("user.home"))), 100))
                        .setDirectoryListingEnabled(true), new HttpHandler() {
                    @Override
                    public void handleRequest(HttpServerExchange exchange) throws Exception {
                        exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (exchange.getHostPort() + 363) + exchange.getRelativePath());
                        exchange.setResponseCode(StatusCodes.TEMPORARY_REDIRECT);
                    }
                }), "x-undertow-transport", ExchangeAttributes.transportProtocol())).build();
        server.start();
    }
View Full Code Here


    @Test
    public void testLongTextMessage() throws Exception {

        final Pool<ByteBuffer> buffer = new ByteBufferSlicePool(BufferAllocator.BYTE_BUFFER_ALLOCATOR, 8192, 8192 * 8192);

        Undertow server;
        XnioWorker client;

        Xnio xnio = Xnio.getInstance(WebSocketExtensionBasicTest.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);

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(path().addPrefixPath("/", debug))
                .build();
        server.start();

        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, buffer, OptionMap.EMPTY, new URI("http://localhost:8080"), 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 {
                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(new Integer(i).toString().charAt(0));
        }

        StreamSinkFrameChannel sendChannel = clientChannel.send(WebSocketFrameType.TEXT, LONG_MSG);
        new StringWriteChannelListener(longMsg.toString()).setup(sendChannel);

        latch.await(10, TimeUnit.SECONDS);
        Assert.assertEquals(longMsg.toString(), result.get());
        clientChannel.sendClose();

        client.shutdown();
        server.stop();
    }
View Full Code Here

    @Ignore
    public void testLongMessageWithoutExtensions() throws Exception {

        final Pool<ByteBuffer> buffer = new ByteBufferSlicePool(BufferAllocator.BYTE_BUFFER_ALLOCATOR, 8192, 8192 * 8192);

        Undertow server;
        XnioWorker client;

        Xnio xnio = Xnio.getInstance(WebSocketExtensionBasicTest.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);

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(path().addPrefixPath("/", debug))
                .build();
        server.start();

        final WebSocketClientNegotiation negotiation = null;

        final WebSocketChannel clientChannel = WebSocketClient.connect(client, buffer, 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 {
                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, LONG_MSG);
        new StringWriteChannelListener(longMsg.toString()).setup(sendChannel);

        latch.await(10, TimeUnit.SECONDS);

        Assert.assertEquals(longMsg.toString(), result.get());
        clientChannel.sendClose();

        client.shutdown();
        server.stop();
    }
View Full Code Here

    @Test
    public void testExtensionsHeaders() throws Exception {

        final Pool<ByteBuffer> buffer = new ByteBufferSlicePool(BufferAllocator.BYTE_BUFFER_ALLOCATOR, 1024, 1024 * 1024);

        Undertow server;
        XnioWorker client;

        Xnio xnio = Xnio.getInstance(WebSocketExtensionBasicTest.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);

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(path().addPrefixPath("/", debug))
                .build();
        server.start();

        final String SEC_WEBSOCKET_EXTENSIONS = "permessage-deflate; client_no_context_takeover; client_max_window_bits";
        final String SEC_WEBSOCKET_EXTENSIONS_EXPECTED = "[permessage-deflate; client_no_context_takeover]"// List format
        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, buffer, OptionMap.EMPTY, new URI("http://localhost:8080"), 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 {
                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, "Hello, World!".length());
        new StringWriteChannelListener("Hello, World!").setup(sendChannel);

        latch.await(10, TimeUnit.SECONDS);
        Assert.assertEquals("Hello, World!", result.get());
        clientChannel.sendClose();

        client.shutdown();
        server.stop();

        Assert.assertEquals(SEC_WEBSOCKET_EXTENSIONS_EXPECTED, debug.getResponseExtensions().toString());
    }
View Full Code Here

        // set as next handler your root handler
        sessionAttachmentHandler.setNext(pathHandler);

        System.out
                .println("Open the url and fill the form to add attributes into the session");
        Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
                .setHandler(sessionAttachmentHandler).build();
        server.start();
    }
View Full Code Here

    /* the address and port to receive normal requests */
    static String phost = System.getProperty("io.undertow.examples.proxy.ADDRESS", "localhost");
    static final int pport = Integer.parseInt(System.getProperty("io.undertow.examples.proxy.PORT", "8000"));

    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.getProxyHandler();
            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) {
View Full Code Here

                .setNext(new PathHandler()
                        .addPrefixPath("/path", new ResourceHandler()
                                // 1 byte = force transfer
                                .setResourceManager(new FileResourceManager(rootPath, 1))
                                .setDirectoryListingEnabled(true)));
        Undertow undertow = Undertow.builder()
                .addHttpListener(8888, "localhost")
                .setHandler(root)
                .build();
        undertow.start();
    }
View Full Code Here

        users.put("userOne", "passwordOne".toCharArray());
        users.put("userTwo", "passwordTwo".toCharArray());

        final IdentityManager identityManager = new MapIdentityManager(users);

        Undertow server = Undertow.builder()
                .addListener(8080, "localhost")
                .setHandler(addSecurity(new HttpHandler() {
                    @Override
                    public void handleRequest(final HttpServerExchange exchange) throws Exception {
                        final SecurityContext context = exchange.getAttachment(SecurityContext.ATTACHMENT_KEY);
                        exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
                    }
                }, identityManager))
                .build();
        server.start();
    }
View Full Code Here

                                    .addMapping("/myservlet"));

            DeploymentManager manager = defaultContainer().addDeployment(servletBuilder);
            manager.deploy();

            Undertow server = Undertow.builder()
                    .addListener(8080, "localhost")
                    .setHandler(manager.start())
                    .build();
            server.start();
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
View Full Code Here

*/
@UndertowExample("Web Sockets")
public class WebSocketServer {

    public static void main(final String[] args) {
        Undertow server = Undertow.builder()
                .addListener(8080, "localhost")
                .setHandler(path()
                        .addPath("/myapp", websocket(new WebSocketSessionHandler() {
                            @Override
                            public void onSession(final WebSocketSession session, WebSocketHttpExchange exchange) {
                                session.setFrameHandler(new AbstractAssembledFrameHandler() {
                                    @Override
                                    public void onTextFrame(final WebSocketSession session, final WebSocketFrameHeader header, final CharSequence payload) {
                                        session.sendText(payload, null);
                                    }
                                });
                            }
                        }))
                        .addPath("index.html", resource(new ClassPathResourceManager(WebSocketServer.class.getClassLoader(), WebSocketServer.class.getPackage())))
                        .addPath("/", redirect("http://localhost:8080/index.html")))
                .build();
        server.start();
    }
View Full Code Here

TOP

Related Classes of io.undertow.Undertow$ListenerConfig

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.