Search in sources :

Example 36 with HttpHandler

use of io.undertow.server.HttpHandler in project undertow by undertow-io.

the class LoadBalancerConnectionPoolingTestCase method before.

@BeforeClass
public static void before() throws Exception {
    ProxyHandler proxyHandler = new ProxyHandler(new LoadBalancingProxyClient().setConnectionsPerThread(1).setSoftMaxConnectionsPerThread(0).setTtl(TTL).setMaxQueueSize(1000).addHost(new URI("http", null, host, port, null, null, null), "s1"), 10000, ResponseCodeHandler.HANDLE_404);
    // Default server uses 8 io threads which is hard to test against
    undertow = Undertow.builder().setIoThreads(1).addHttpListener(port + 1, host).setHandler(proxyHandler).build();
    undertow.start();
    DefaultServer.setRootHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            final ServerConnection con = exchange.getConnection();
            if (!activeConnections.contains(con)) {
                System.out.println("added " + con);
                activeConnections.add(con);
                con.addCloseListener(new ServerConnection.CloseListener() {

                    @Override
                    public void closed(ServerConnection connection) {
                        System.out.println("Closed " + connection);
                        activeConnections.remove(connection);
                    }
                });
            }
        }
    });
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) ServerConnection(io.undertow.server.ServerConnection) URI(java.net.URI) IOException(java.io.IOException) BeforeClass(org.junit.BeforeClass)

Example 37 with HttpHandler

use of io.undertow.server.HttpHandler in project undertow by undertow-io.

the class LoadBalancingProxyHTTP2ViaUpgradeTestCase method setup.

@BeforeClass
public static void setup() throws URISyntaxException {
    int port = DefaultServer.getHostPort("default");
    final HttpHandler handler1 = getRootHandler("s1", "server1");
    server1 = Undertow.builder().addHttpListener(port + 1, DefaultServer.getHostAddress("default")).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, IDLE_TIMEOUT).setSocketOption(Options.REUSE_ADDRESSES, true).setHandler(new Http2UpgradeHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (!(exchange.getConnection() instanceof Http2ServerConnection)) {
                throw new RuntimeException("Not HTTP2");
            }
            exchange.getResponseHeaders().add(new HttpString("X-Custom-Header"), "foo");
            System.out.println("server1 " + exchange.getRequestHeaders());
            handler1.handleRequest(exchange);
        }
    })).build();
    final HttpHandler handler2 = getRootHandler("s2", "server2");
    server2 = Undertow.builder().addHttpListener(port + 2, DefaultServer.getHostAddress("default")).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, IDLE_TIMEOUT).setSocketOption(Options.REUSE_ADDRESSES, true).setHandler(new Http2UpgradeHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (!(exchange.getConnection() instanceof Http2ServerConnection)) {
                throw new RuntimeException("Not HTTP2");
            }
            exchange.getResponseHeaders().add(new HttpString("X-Custom-Header"), "foo");
            System.out.println("server2 " + exchange.getRequestHeaders());
            handler2.handleRequest(exchange);
        }
    })).build();
    server1.start();
    server2.start();
    DefaultServer.setRootHandler(new ProxyHandler(new LoadBalancingProxyClient().setConnectionsPerThread(4).addHost(new URI("h2c", null, DefaultServer.getHostAddress("default"), port + 1, null, null, null), "s1").addHost(new URI("h2c", null, DefaultServer.getHostAddress("default"), port + 2, null, null, null), "s2"), 10000, ResponseCodeHandler.HANDLE_404, false, false, 2));
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) Http2UpgradeHandler(io.undertow.server.protocol.http2.Http2UpgradeHandler) Http2ServerConnection(io.undertow.server.protocol.http2.Http2ServerConnection) URI(java.net.URI) HttpString(io.undertow.util.HttpString) BeforeClass(org.junit.BeforeClass)

Example 38 with HttpHandler

use of io.undertow.server.HttpHandler in project undertow by undertow-io.

the class SimpleBlockingServerTestCase method setup.

@BeforeClass
public static void setup() {
    final BlockingHandler blockingHandler = new BlockingHandler();
    DefaultServer.setRootHandler(blockingHandler);
    blockingHandler.setRootHandler(new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) {
            try {
                if (exchange.getRequestMethod().equals(Methods.POST)) {
                    //for a post we just echo back what was sent
                    //we need to fully buffer it, as otherwise the send buffer fills up, and the client will still be blocked
                    //on writing and will never read
                    byte[] buffer = new byte[1024];
                    final ByteArrayOutputStream b = new ByteArrayOutputStream();
                    int r = 0;
                    final OutputStream outputStream = exchange.getOutputStream();
                    final InputStream inputStream = exchange.getInputStream();
                    while ((r = inputStream.read(buffer)) > 0) {
                        b.write(buffer, 0, r);
                    }
                    outputStream.write(b.toByteArray());
                    outputStream.close();
                } else {
                    if (exchange.getQueryParameters().containsKey("useFragmentedSender")) {
                        //we send it byte at a time
                        exchange.getResponseSender().send("", new IoCallback() {

                            int i = 0;

                            @Override
                            public void onComplete(final HttpServerExchange exchange, final Sender sender) {
                                if (i == message.length()) {
                                    sender.close();
                                    exchange.endExchange();
                                } else {
                                    sender.send("" + message.charAt(i++), this);
                                }
                            }

                            @Override
                            public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
                                exchange.endExchange();
                            }
                        });
                    } else if (exchange.getQueryParameters().containsKey("useSender")) {
                        exchange.getResponseSender().send(message, IoCallback.END_EXCHANGE);
                    } else {
                        final OutputStream outputStream = exchange.getOutputStream();
                        outputStream.write(message.getBytes());
                        outputStream.close();
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) Sender(io.undertow.io.Sender) HttpHandler(io.undertow.server.HttpHandler) BlockingHandler(io.undertow.server.handlers.BlockingHandler) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) IoCallback(io.undertow.io.IoCallback) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) BeforeClass(org.junit.BeforeClass)

Example 39 with HttpHandler

use of io.undertow.server.HttpHandler in project undertow by undertow-io.

the class InMemorySessionTestCase method inMemorySessionTest.

@Test
public void inMemorySessionTest() throws IOException {
    TestHttpClient client = new TestHttpClient();
    client.setCookieStore(new BasicCookieStore());
    try {
        final SessionCookieConfig sessionConfig = new SessionCookieConfig();
        final SessionAttachmentHandler handler = new SessionAttachmentHandler(new InMemorySessionManager(""), sessionConfig);
        handler.setNext(new HttpHandler() {

            @Override
            public void handleRequest(final HttpServerExchange exchange) throws Exception {
                final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
                Session session = manager.getSession(exchange, sessionConfig);
                if (session == null) {
                    session = manager.createSession(exchange, sessionConfig);
                    session.setAttribute(COUNT, 0);
                }
                Integer count = (Integer) session.getAttribute(COUNT);
                exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
                session.setAttribute(COUNT, ++count);
            }
        });
        DefaultServer.setRootHandler(handler);
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        Header[] header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("1", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("2", header[0].getValue());
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) SessionManager(io.undertow.server.session.SessionManager) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) TestHttpClient(io.undertow.testutils.TestHttpClient) HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) Session(io.undertow.server.session.Session) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Example 40 with HttpHandler

use of io.undertow.server.HttpHandler in project undertow by undertow-io.

the class SenderTestCase method setup.

@BeforeClass
public static void setup() {
    HttpHandler lotsOfSendsHandler = new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            boolean blocking = exchange.getQueryParameters().get("blocking").getFirst().equals("true");
            if (blocking) {
                if (exchange.isInIoThread()) {
                    exchange.startBlocking();
                    exchange.dispatch(this);
                    return;
                }
            }
            final Sender sender = exchange.getResponseSender();
            class SendClass implements Runnable, IoCallback {

                int sent = 0;

                @Override
                public void run() {
                    sent++;
                    sender.send("a", this);
                }

                @Override
                public void onComplete(final HttpServerExchange exchange, final Sender sender) {
                    if (sent++ == SENDS) {
                        sender.close();
                        return;
                    }
                    sender.send("a", this);
                }

                @Override
                public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
                    exception.printStackTrace();
                    exchange.endExchange();
                }
            }
            new SendClass().run();
        }
    };
    HttpHandler lotsOfTransferHandler = new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            boolean blocking = exchange.getQueryParameters().get("blocking").getFirst().equals("true");
            if (blocking) {
                if (exchange.isInIoThread()) {
                    exchange.startBlocking();
                    exchange.dispatch(this);
                    return;
                }
            }
            URI uri = SenderTestCase.class.getResource(SenderTestCase.class.getSimpleName() + ".class").toURI();
            Path file = Paths.get(uri);
            final FileChannel channel = FileChannel.open(file, StandardOpenOption.READ);
            exchange.setResponseContentLength(channel.size() * TXS);
            final Sender sender = exchange.getResponseSender();
            class SendClass implements Runnable, IoCallback {

                int sent = 0;

                @Override
                public void run() {
                    sent++;
                    try {
                        channel.position(0);
                    } catch (IOException e) {
                    }
                    sender.transferFrom(channel, this);
                }

                @Override
                public void onComplete(final HttpServerExchange exchange, final Sender sender) {
                    if (sent++ == TXS) {
                        sender.close();
                        return;
                    }
                    try {
                        channel.position(0);
                    } catch (IOException e) {
                    }
                    sender.transferFrom(channel, this);
                }

                @Override
                public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
                    exception.printStackTrace();
                    exchange.endExchange();
                }
            }
            new SendClass().run();
        }
    };
    final HttpHandler fixedLengthSender = new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send(HELLO_WORLD);
        }
    };
    PathHandler handler = new PathHandler().addPrefixPath("/lots", lotsOfSendsHandler).addPrefixPath("/fixed", fixedLengthSender).addPrefixPath("/transfer", lotsOfTransferHandler);
    DefaultServer.setRootHandler(handler);
}
Also used : Path(java.nio.file.Path) HttpHandler(io.undertow.server.HttpHandler) FileChannel(java.nio.channels.FileChannel) IOException(java.io.IOException) URI(java.net.URI) HttpServerExchange(io.undertow.server.HttpServerExchange) Sender(io.undertow.io.Sender) IoCallback(io.undertow.io.IoCallback) BeforeClass(org.junit.BeforeClass)

Aggregations

HttpHandler (io.undertow.server.HttpHandler)126 HttpServerExchange (io.undertow.server.HttpServerExchange)72 IOException (java.io.IOException)54 BeforeClass (org.junit.BeforeClass)35 Test (org.junit.Test)25 TestHttpClient (io.undertow.testutils.TestHttpClient)20 HttpResponse (org.apache.http.HttpResponse)20 HttpGet (org.apache.http.client.methods.HttpGet)19 PathHandler (io.undertow.server.handlers.PathHandler)17 HttpString (io.undertow.util.HttpString)15 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)13 Undertow (io.undertow.Undertow)12 ArrayList (java.util.ArrayList)11 HandlerWrapper (io.undertow.server.HandlerWrapper)9 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)9 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)9 Header (org.apache.http.Header)9 SessionCookieConfig (io.undertow.server.session.SessionCookieConfig)8 AuthenticationMechanism (io.undertow.security.api.AuthenticationMechanism)7 AuthenticationCallHandler (io.undertow.security.handlers.AuthenticationCallHandler)7