Search in sources :

Example 31 with HttpHandler

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

the class AsyncReceiverImpl method receivePartialBytes.

@Override
public void receivePartialBytes(final PartialBytesCallback callback, final ErrorCallback errorCallback) {
    if (done) {
        throw UndertowMessages.MESSAGES.requestBodyAlreadyRead();
    }
    final ErrorCallback error = errorCallback == null ? END_EXCHANGE : errorCallback;
    if (callback == null) {
        throw UndertowMessages.MESSAGES.argumentCannotBeNull("callback");
    }
    if (exchange.isRequestComplete()) {
        callback.handle(exchange, EMPTY_BYTE_ARRAY, true);
        return;
    }
    String contentLengthString = exchange.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH);
    long contentLength;
    if (contentLengthString != null) {
        contentLength = Long.parseLong(contentLengthString);
        if (contentLength > Integer.MAX_VALUE) {
            error.error(exchange, new RequestToLargeException());
            return;
        }
    } else {
        contentLength = -1;
    }
    if (maxBufferSize > 0) {
        if (contentLength > maxBufferSize) {
            error.error(exchange, new RequestToLargeException());
            return;
        }
    }
    PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
    final ByteBuffer buffer = pooled.getBuffer();
    channel.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {

        @Override
        public void handleEvent(final StreamSourceChannel channel) {
            if (done || paused) {
                return;
            }
            PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
            final ByteBuffer buffer = pooled.getBuffer();
            try {
                int res;
                do {
                    if (paused) {
                        return;
                    }
                    try {
                        buffer.clear();
                        res = channel.read(buffer);
                        if (res == -1) {
                            done = true;
                            Connectors.executeRootHandler(new HttpHandler() {

                                @Override
                                public void handleRequest(HttpServerExchange exchange) throws Exception {
                                    callback.handle(exchange, EMPTY_BYTE_ARRAY, true);
                                }
                            }, exchange);
                            return;
                        } else if (res == 0) {
                            return;
                        } else {
                            buffer.flip();
                            final byte[] data = new byte[buffer.remaining()];
                            buffer.get(data);
                            Connectors.executeRootHandler(new HttpHandler() {

                                @Override
                                public void handleRequest(HttpServerExchange exchange) throws Exception {
                                    callback.handle(exchange, data, false);
                                    if (!paused) {
                                        channel.resumeReads();
                                    }
                                }
                            }, exchange);
                        }
                    } catch (final IOException e) {
                        Connectors.executeRootHandler(new HttpHandler() {

                            @Override
                            public void handleRequest(HttpServerExchange exchange) throws Exception {
                                error.error(exchange, e);
                            }
                        }, exchange);
                        return;
                    }
                } while (true);
            } finally {
                pooled.close();
            }
        }
    });
    try {
        int res;
        do {
            try {
                buffer.clear();
                res = channel.read(buffer);
                if (res == -1) {
                    done = true;
                    callback.handle(exchange, EMPTY_BYTE_ARRAY, true);
                    return;
                } else if (res == 0) {
                    channel.resumeReads();
                    return;
                } else {
                    buffer.flip();
                    byte[] data = new byte[buffer.remaining()];
                    buffer.get(data);
                    callback.handle(exchange, data, false);
                    if (paused) {
                        return;
                    }
                }
            } catch (IOException e) {
                error.error(exchange, e);
                return;
            }
        } while (true);
    } finally {
        pooled.close();
    }
}
Also used : StreamSourceChannel(org.xnio.channels.StreamSourceChannel) HttpHandler(io.undertow.server.HttpHandler) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) IOException(java.io.IOException) HttpServerExchange(io.undertow.server.HttpServerExchange) PooledByteBuffer(io.undertow.connector.PooledByteBuffer)

Example 32 with HttpHandler

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

the class AsyncReceiverImpl method receiveFullBytes.

@Override
public void receiveFullBytes(final FullBytesCallback callback, final ErrorCallback errorCallback) {
    if (done) {
        throw UndertowMessages.MESSAGES.requestBodyAlreadyRead();
    }
    final ErrorCallback error = errorCallback == null ? END_EXCHANGE : errorCallback;
    if (callback == null) {
        throw UndertowMessages.MESSAGES.argumentCannotBeNull("callback");
    }
    if (exchange.isRequestComplete()) {
        callback.handle(exchange, EMPTY_BYTE_ARRAY);
        return;
    }
    String contentLengthString = exchange.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH);
    long contentLength;
    final ByteArrayOutputStream sb;
    if (contentLengthString != null) {
        contentLength = Long.parseLong(contentLengthString);
        if (contentLength > Integer.MAX_VALUE) {
            error.error(exchange, new RequestToLargeException());
            return;
        }
        sb = new ByteArrayOutputStream((int) contentLength);
    } else {
        contentLength = -1;
        sb = new ByteArrayOutputStream();
    }
    if (maxBufferSize > 0) {
        if (contentLength > maxBufferSize) {
            error.error(exchange, new RequestToLargeException());
            return;
        }
    }
    PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
    final ByteBuffer buffer = pooled.getBuffer();
    try {
        int res;
        do {
            try {
                buffer.clear();
                res = channel.read(buffer);
                if (res == -1) {
                    done = true;
                    callback.handle(exchange, sb.toByteArray());
                    return;
                } else if (res == 0) {
                    channel.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {

                        @Override
                        public void handleEvent(StreamSourceChannel channel) {
                            if (done) {
                                return;
                            }
                            PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
                            final ByteBuffer buffer = pooled.getBuffer();
                            try {
                                int res;
                                do {
                                    try {
                                        buffer.clear();
                                        res = channel.read(buffer);
                                        if (res == -1) {
                                            done = true;
                                            Connectors.executeRootHandler(new HttpHandler() {

                                                @Override
                                                public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                    callback.handle(exchange, sb.toByteArray());
                                                }
                                            }, exchange);
                                            return;
                                        } else if (res == 0) {
                                            return;
                                        } else {
                                            buffer.flip();
                                            while (buffer.hasRemaining()) {
                                                sb.write(buffer.get());
                                            }
                                            if (maxBufferSize > 0 && sb.size() > maxBufferSize) {
                                                Connectors.executeRootHandler(new HttpHandler() {

                                                    @Override
                                                    public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                        error.error(exchange, new RequestToLargeException());
                                                    }
                                                }, exchange);
                                                return;
                                            }
                                        }
                                    } catch (final Exception e) {
                                        Connectors.executeRootHandler(new HttpHandler() {

                                            @Override
                                            public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                error.error(exchange, new IOException(e));
                                            }
                                        }, exchange);
                                        return;
                                    }
                                } while (true);
                            } finally {
                                pooled.close();
                            }
                        }
                    });
                    channel.resumeReads();
                    return;
                } else {
                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        sb.write(buffer.get());
                    }
                    if (maxBufferSize > 0 && sb.size() > maxBufferSize) {
                        error.error(exchange, new RequestToLargeException());
                        return;
                    }
                }
            } catch (IOException e) {
                error.error(exchange, e);
                return;
            }
        } while (true);
    } finally {
        pooled.close();
    }
}
Also used : StreamSourceChannel(org.xnio.channels.StreamSourceChannel) HttpHandler(io.undertow.server.HttpHandler) ChannelListener(org.xnio.ChannelListener) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) IOException(java.io.IOException) HttpServerExchange(io.undertow.server.HttpServerExchange) PooledByteBuffer(io.undertow.connector.PooledByteBuffer)

Example 33 with HttpHandler

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

the class FormDataParserTestCase method handlerChains.

@Parameterized.Parameters
public static Collection<Object[]> handlerChains() {
    List<Object[]> ret = new ArrayList<>();
    final FormParserFactory parserFactory = FormParserFactory.builder().build();
    HttpHandler fd = new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final FormDataParser parser = parserFactory.createParser(exchange);
            parser.parse(new HttpHandler() {

                @Override
                public void handleRequest(final HttpServerExchange exchange) throws Exception {
                    FormData data = exchange.getAttachment(FormDataParser.FORM_DATA);
                    Iterator<String> it = data.iterator();
                    while (it.hasNext()) {
                        String fd = it.next();
                        for (FormData.FormValue val : data.get(fd)) {
                            exchange.getResponseHeaders().add(new HttpString(fd), val.getValue());
                        }
                    }
                }
            });
        }
    };
    ret.add(new Object[] { fd });
    final BlockingHandler blocking = new BlockingHandler();
    blocking.setRootHandler(new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final FormDataParser parser = parserFactory.createParser(exchange);
            try {
                FormData data = parser.parseBlocking();
                Iterator<String> it = data.iterator();
                while (it.hasNext()) {
                    String fd = it.next();
                    for (FormData.FormValue val : data.get(fd)) {
                        exchange.getResponseHeaders().add(new HttpString(fd), val.getValue());
                    }
                }
            } catch (IOException e) {
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            }
        }
    });
    ret.add(new Object[] { blocking });
    return ret;
}
Also used : HttpHandler(io.undertow.server.HttpHandler) ArrayList(java.util.ArrayList) HttpString(io.undertow.util.HttpString) IOException(java.io.IOException) IOException(java.io.IOException) HttpServerExchange(io.undertow.server.HttpServerExchange) BlockingHandler(io.undertow.server.handlers.BlockingHandler) Iterator(java.util.Iterator) HttpString(io.undertow.util.HttpString)

Example 34 with HttpHandler

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

the class PathTestCase method testBasicPathHanding.

@Test
public void testBasicPathHanding() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {
        final PathHandler handler = new PathHandler();
        handler.addPrefixPath("a", new RemainingPathHandler("/a"));
        handler.addPrefixPath("/aa", new RemainingPathHandler("/aa"));
        handler.addExactPath("/aa", new HttpHandler() {

            @Override
            public void handleRequest(HttpServerExchange exchange) throws Exception {
                exchange.getResponseSender().send("Exact /aa match:" + exchange.getRelativePath() + ":" + exchange.getResolvedPath());
            }
        });
        handler.addPrefixPath("/aa/anotherSubPath", new RemainingPathHandler("/aa/anotherSubPath"));
        final PathHandler sub = new PathHandler();
        handler.addPrefixPath("/path", sub);
        sub.addPrefixPath("/subpath", new RemainingPathHandler("/subpath"));
        sub.addPrefixPath("/", new RemainingPathHandler("/path"));
        DefaultServer.setRootHandler(handler);
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.NOT_FOUND, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.NOT_FOUND, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        runPathTest(client, "/path", "/path", "");
        runPathTest(client, "/path/a", "/path", "/a");
        runPathTest(client, "/path/subpath", "/subpath", "");
        runPathTest(client, "/path/subpath/", "/subpath", "/");
        runPathTest(client, "/path/subpath/foo", "/subpath", "/foo");
        runPathTest(client, "/a", "/a", "");
        runPathTest(client, "/aa/anotherSubPath", "/aa/anotherSubPath", "");
        runPathTest(client, "/aa/anotherSubPath/bob", "/aa/anotherSubPath", "/bob");
        runPathTest(client, "/aa/b?a=b", "/aa", "/b", Collections.singletonMap("a", "b"));
        runPathTest(client, "/path/:bar/baz", "/path", "/:bar/baz");
        //now test the exact path match
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/aa");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("Exact /aa match::/aa", HttpClientUtils.readResponse(result));
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) HttpGet(org.apache.http.client.methods.HttpGet) PathHandler(io.undertow.server.handlers.PathHandler) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) TestHttpClient(io.undertow.testutils.TestHttpClient) Test(org.junit.Test)

Example 35 with HttpHandler

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

the class AbstractLoadBalancingProxyTestCase method getRootHandler.

protected static HttpHandler getRootHandler(String s1, String server1) {
    final SessionCookieConfig sessionConfig = new SessionCookieConfig();
    return jvmRoute("JSESSIONID", s1, path().addPrefixPath("/session", new SessionAttachmentHandler(new SessionTestHandler(sessionConfig), new InMemorySessionManager(""), sessionConfig)).addPrefixPath("/name", new StringSendHandler(server1)).addPrefixPath("/url", new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send(exchange.getRequestURI());
        }
    }).addPrefixPath("/path", new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send(exchange.getRequestURI());
        }
    }).addPrefixPath("/fail", new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (firstFail) {
                firstFail = false;
                IoUtils.safeClose(exchange.getConnection());
            }
            exchange.getResponseSender().send(exchange.getRequestURI() + ":" + firstFail);
        }
    }).addPrefixPath("/timeout", new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (exchange.getConnection().getAttachment(EXISTING) == null) {
                exchange.getConnection().putAttachment(EXISTING, true);
                exchange.getResponseSender().send("false");
            } else {
                exchange.getResponseSender().send("true");
            }
        }
    }));
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) HttpHandler(io.undertow.server.HttpHandler) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) IOException(java.io.IOException) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager)

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