Package io.undertow

Examples of io.undertow.Undertow


        }
    }

    public void testAntPropertiesLoadFromURL() throws Exception {
        File tempDir = FileUtil.createTempDirectory("ant-launcher-test", null, null);
        Undertow undertow = null;

        try {
            //prepare the test bundle.. update the recipe with an absolute path to a properties file.
            File deployXml = new File(tempDir, "deploy.xml");

            FileUtil.copyFile(getFileFromTestClasses("ant-properties/deploy.xml.properties-out-of-bundle"), deployXml);

            //copy the other file from the bundle, too, into the correct location
            FileUtil.copyFile(getFileFromTestClasses("ant-properties/deployed.file"),
                new File(tempDir, "deployed.file"));

            //fire up minimal server
            PortScout portScout = new PortScout();
            int port = 0;
            try {
                port = portScout.getNextFreePort();
            } finally {
                portScout.close();
            }

            undertow = Undertow.builder().addHttpListener(port, "localhost").setHandler(new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
                    httpServerExchange.startBlocking();
                    FileInputStream in = new FileInputStream(
                        getFileFromTestClasses("ant-properties/in-bundle.properties"));
                    try {
                        StreamUtil.copy(in, httpServerExchange.getOutputStream(), false);
                    } catch (Exception e) {
                        LOG.error("Failed to handle the HTTP request for loading properties.", e);
                        throw e;
                    } finally {
                        StreamUtil.safeClose(in);
                    }
                }
            }).build();

            undertow.start();

            String deployXmlContents = StreamUtil.slurp(new InputStreamReader(new FileInputStream(deployXml)));

            deployXmlContents = deployXmlContents.replace("%%REPLACE_ME%%", "url=\"http://localhost:" + port + "\"");

            FileUtil.writeFile(new ByteArrayInputStream(deployXmlContents.getBytes()), deployXml);

            //k, now the test itself...
            testNotDeployedFiles(deployXml, false, false);
            checkPropertiesFromExternalFileReplaced();
        } finally {
            FileUtil.purge(tempDir, true);
            if (undertow != null) {
                undertow.stop();
            }
        }
    }
View Full Code Here


        if (null != running.get(port)) {
            throw new ServiceException("Server already running on port " + port);
        }

        final Undertow server = Undertow.builder()
                .addHttpListener(port, host)
                .setHandler(new HttpHandler() {
                    @Override
                    public void handleRequest(final HttpServerExchange exchange) throws Exception {
                        final ResourceDefinition endpoint = getEndpoint(mock, exchange);
                        if (null == endpoint) {
                            LOGGER.info("Sending HTTP {} for request: {}", StatusCodes.NOT_FOUND, exchange.getRequestPath());
                            exchange.setResponseCode(StatusCodes.NOT_FOUND);

                        } else {
                            if (exchange.getQueryParameters().containsKey("blueprint")
                                    && settingsService.isDocumentationEnabled()) {

                                // documentation
                                LOGGER.info("Sending documentation for mock request: {}", exchange.getRequestPath());

                                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
                                exchange.getResponseSender().send(parsingService.parseMarkdownFile(mock.getBlueprintFile()));

                            } else {
                                // match request
                                final RequestDefinition request;
                                try {
                                    request = matchRequest(exchange, endpoint);

                                } catch (ResourceNotFoundException e) {
                                    LOGGER.info("Sending HTTP {} for request: {}", StatusCodes.NOT_FOUND, exchange.getRequestPath());
                                    exchange.setResponseCode(StatusCodes.NOT_FOUND);
                                    return;

                                } catch (MethodNotAllowedException e) {
                                    LOGGER.info("Sending HTTP {} for request: {}", StatusCodes.METHOD_NOT_ALLOWED, exchange.getRequestPath());
                                    exchange.setResponseCode(StatusCodes.METHOD_NOT_ALLOWED);
                                    return;
                                }

                                // match response
                                final ResponseDefinition response = matchResponse(exchange, endpoint, request);

                                final int responseCode = response.getCode();
                                LOGGER.info("Sending HTTP {} for mock request: {}", responseCode,
                                        exchange.getRequestPath());

                                exchange.setResponseCode(responseCode);
                                populateResponseHeaders(response, exchange.getResponseHeaders());

                                // body
                                final String body = response.getBody();
                                exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + (null != body ? body.length() : 0));
                                exchange.getResponseSender().send(body);
                            }
                        }
                    }
                }).build();
        server.start();
        LOGGER.info("Started mock server on host {} and port {} for mock {}", host, port, mock);

        // remember
        running.put(port, server);
View Full Code Here

    /**
     * {@inheritDoc}
     */
    @Override
    public void stop(MockServer server) {
        final Undertow u = running.get(server.getPort());
        if (null != u) {
            LOGGER.info("Stopping server on port {}", server.getPort());

            u.stop();
            running.remove(server.getPort());

        } else {
            LOGGER.warn("No server to stop on port {}", server.getPort());
        }
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) {
        final Undertow server;

        final ModCluster modCluster = ModCluster.builder().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.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) {
View Full Code Here

@UndertowExample("Reverse Proxy")
public class ReverseProxyServer {

    public static void main(final String[] args) {
        try {
            final Undertow server1 = Undertow.builder()
                    .addListener(8081, "localhost")
                    .setHandler(new HttpHandler() {
                        @Override
                        public void handleRequest(HttpServerExchange exchange) throws Exception {
                            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                            exchange.getResponseSender().send("Server1");
                        }
                    })
                    .build();

            server1.start();

            final Undertow server2 = Undertow.builder()
                    .addListener(8082, "localhost")
                    .setHandler(new HttpHandler() {
                        @Override
                        public void handleRequest(HttpServerExchange exchange) throws Exception {
                            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                            exchange.getResponseSender().send("Server2");
                        }
                    })
                    .build();
            server2.start();

            final Undertow server3 = Undertow.builder()
                    .addListener(8083, "localhost")
                    .setHandler(new HttpHandler() {
                        @Override
                        public void handleRequest(HttpServerExchange exchange) throws Exception {
                            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                            exchange.getResponseSender().send("Server3");
                        }
                    })
                    .build();

            server3.start();

            LoadBalancingProxyClient loadBalancer = new LoadBalancingProxyClient()
                    .addHost(new URI("http://localhost:8081"))
                    .addHost(new URI("http://localhost:8082"))
                    .addHost(new URI("http://localhost:8083"))
                    .setConnectionsPerThread(20);

            Undertow reverseProxy = Undertow.builder()
                    .addListener(8080, "localhost")
                    .setIoThreads(4)
                    .setHandler(new ProxyHandler(loadBalancer, 30000, ResponseCodeHandler.HANDLE_404))
                    .build();
            reverseProxy.start();

        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
View Full Code Here

            manager.deploy();

            HttpHandler servletHandler = manager.start();
            PathHandler path = Handlers.path(Handlers.redirect(MYAPP))
                    .addPrefixPath(MYAPP, servletHandler);
            Undertow server = Undertow.builder()
                    .addListener(8080, "localhost")
                    .setHandler(path)
                    .build();
            server.start();
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
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.getSecurityContext();
                        exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
                    }
                }, identityManager))
                .build();
        server.start();
    }
View Full Code Here

    public static void main(final String[] args) {

        System.out.println("To see chat in action is to open two different browsers and point them at http://localhost:8080");

        Undertow server = Undertow.builder()
                .addListener(8080, "localhost")
                .setHandler(path()
                        .addPrefixPath("/myapp", websocket(new WebSocketConnectionCallback() {

                            @Override
                            public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
                                synchronized (sessions) {
                                    sessions.add(channel);
                                    channel.getCloseSetter().set(new ChannelListener<Channel>() {
                                        @Override
                                        public void handleEvent(Channel channel) {
                                            synchronized (sessions) {
                                                sessions.remove(channel);
                                            }
                                        }
                                    });
                                    channel.getReceiveSetter().set(new AbstractReceiveListener() {

                                        @Override
                                        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
                                            final String messageData = message.getData();
                                            synchronized (sessions) {
                                                for (WebSocketChannel session : sessions) {
                                                    WebSockets.sendText(messageData, session, null);
                                                }
                                            }
                                        }
                                    });
                                    channel.resumeReceives();
                                }
                            }
                        }))
                        .addPrefixPath("/", resource(new ClassPathResourceManager(ChatServer.class.getClassLoader(), ChatServer.class.getPackage()))
                                .addWelcomeFiles("index.html")))
                .build();

        server.start();
    }
View Full Code Here

*/
@UndertowExample("Hello World")
public class HelloWorldServer {

    public static void main(final String[] args) {
        Undertow server = Undertow.builder()
                .addListener(8080, "localhost")
                .setHandler(new HttpHandler() {
                    @Override
                    public void handleRequest(final HttpServerExchange exchange) throws Exception {
                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                        exchange.getResponseSender().send("Hello World");
                    }
                }).build();
        server.start();
    }
View Full Code Here

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

    public static void main(final String[] args) {
        Undertow server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(path()
                        .addPrefixPath("/myapp", websocket(new WebSocketConnectionCallback() {

                            @Override
                            public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
                                channel.getReceiveSetter().set(new AbstractReceiveListener() {

                                    @Override
                                    protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
                                        WebSockets.sendText(message.getData(), channel, null);
                                    }
                                });
                                channel.resumeReceives();
                            }
                        }))
                        .addPrefixPath("/", resource(new ClassPathResourceManager(WebSocketServer.class.getClassLoader(), WebSocketServer.class.getPackage())).addWelcomeFiles("index.html")))
                .build();
        server.start();
    }
View Full Code Here

TOP

Related Classes of io.undertow.Undertow

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.