Search in sources :

Example 21 with HttpString

use of io.undertow.util.HttpString 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 22 with HttpString

use of io.undertow.util.HttpString 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 23 with HttpString

use of io.undertow.util.HttpString 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 24 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class HttpReadListener method handleEventWithNoRunningRequest.

public void handleEventWithNoRunningRequest(final ConduitStreamSourceChannel channel) {
    PooledByteBuffer existing = connection.getExtraBytes();
    if ((existing == null && connection.getOriginalSourceConduit().isReadShutdown()) || connection.getOriginalSinkConduit().isWriteShutdown()) {
        IoUtils.safeClose(connection);
        channel.suspendReads();
        return;
    }
    final PooledByteBuffer pooled = existing == null ? connection.getByteBufferPool().allocate() : existing;
    final ByteBuffer buffer = pooled.getBuffer();
    boolean free = true;
    try {
        int res;
        boolean bytesRead = false;
        do {
            if (existing == null) {
                buffer.clear();
                try {
                    res = channel.read(buffer);
                } catch (IOException e) {
                    UndertowLogger.REQUEST_IO_LOGGER.debug("Error reading request", e);
                    IoUtils.safeClose(connection);
                    return;
                }
            } else {
                res = buffer.remaining();
            }
            if (res <= 0) {
                if (bytesRead && parseTimeoutUpdater != null) {
                    parseTimeoutUpdater.failedParse();
                }
                handleFailedRead(channel, res);
                return;
            } else {
                bytesRead = true;
            }
            if (existing != null) {
                existing = null;
                connection.setExtraBytes(null);
            } else {
                buffer.flip();
            }
            int begin = buffer.remaining();
            if (httpServerExchange == null) {
                httpServerExchange = new HttpServerExchange(connection, maxEntitySize);
            }
            parser.handle(buffer, state, httpServerExchange);
            if (buffer.hasRemaining()) {
                free = false;
                connection.setExtraBytes(pooled);
            }
            int total = read + (begin - buffer.remaining());
            read = total;
            if (read > maxRequestSize) {
                UndertowLogger.REQUEST_LOGGER.requestHeaderWasTooLarge(connection.getPeerAddress(), maxRequestSize);
                sendBadRequestAndClose(connection.getChannel(), null);
                return;
            }
        } while (!state.isComplete());
        if (parseTimeoutUpdater != null) {
            parseTimeoutUpdater.requestStarted();
        }
        final HttpServerExchange httpServerExchange = this.httpServerExchange;
        httpServerExchange.setRequestScheme(connection.getSslSession() != null ? "https" : "http");
        this.httpServerExchange = null;
        requestStateUpdater.set(this, 1);
        if (httpServerExchange.getProtocol() == Protocols.HTTP_2_0) {
            free = handleHttp2PriorKnowledge(pooled, httpServerExchange);
            return;
        }
        if (!allowUnknownProtocols) {
            HttpString protocol = httpServerExchange.getProtocol();
            if (protocol != Protocols.HTTP_1_1 && protocol != Protocols.HTTP_1_0 && protocol != Protocols.HTTP_0_9) {
                UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing connection from %s due to unknown protocol %s", connection.getChannel().getPeerAddress(), protocol);
                sendBadRequestAndClose(connection.getChannel(), new IOException());
                return;
            }
        }
        HttpTransferEncoding.setupRequest(httpServerExchange);
        if (recordRequestStartTime) {
            Connectors.setRequestStartTime(httpServerExchange);
        }
        connection.setCurrentExchange(httpServerExchange);
        if (connectorStatistics != null) {
            connectorStatistics.setup(httpServerExchange);
        }
        if (connection.getSslSession() != null) {
            //TODO: figure out a better solution for this
            //in order to improve performance we do not generally suspend reads, instead we a CAS to detect when
            //data arrives while a request is running and suspend lazily, as suspend/resume is relatively expensive
            //however this approach does not work for SSL, as the underlying channel is not thread safe
            //so we just suspend every time (the overhead is likely much less than the general SSL overhead anyway)
            channel.suspendReads();
        }
        if (requireHostHeader && !httpServerExchange.getRequestHeaders().contains(Headers.HOST)) {
            if (httpServerExchange.getProtocol().equals(Protocols.HTTP_1_1)) {
                sendBadRequestAndClose(connection.getChannel(), UndertowMessages.MESSAGES.noHostInHttp11Request());
                return;
            }
        }
        Connectors.executeRootHandler(connection.getRootHandler(), httpServerExchange);
    } catch (Exception e) {
        sendBadRequestAndClose(connection.getChannel(), e);
        return;
    } finally {
        if (free)
            pooled.close();
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) IOException(java.io.IOException) HttpString(io.undertow.util.HttpString)

Example 25 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class HttpRequestParser method httpStrings.

/**
     * This is a bit of hack to enable the parser to get access to the HttpString's that are sorted
     * in the static fields of the relevant classes. This means that in most cases a HttpString comparison
     * will take the fast path == route, as they will be the same object
     *
     * @return
     */
@SuppressWarnings("unused")
protected static Map<String, HttpString> httpStrings() {
    final Map<String, HttpString> results = new HashMap<>();
    final Class[] classs = { Headers.class, Methods.class, Protocols.class };
    for (Class<?> c : classs) {
        for (Field field : c.getDeclaredFields()) {
            if (field.getType().equals(HttpString.class)) {
                HttpString result = null;
                try {
                    result = (HttpString) field.get(null);
                    results.put(result.toString(), result);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    return results;
}
Also used : Field(java.lang.reflect.Field) HashMap(java.util.HashMap) HttpString(io.undertow.util.HttpString) HttpString(io.undertow.util.HttpString)

Aggregations

HttpString (io.undertow.util.HttpString)59 IOException (java.io.IOException)18 HttpServerExchange (io.undertow.server.HttpServerExchange)16 HeaderMap (io.undertow.util.HeaderMap)15 HttpHandler (io.undertow.server.HttpHandler)9 ByteBuffer (java.nio.ByteBuffer)9 Map (java.util.Map)8 HashMap (java.util.HashMap)7 PooledByteBuffer (io.undertow.connector.PooledByteBuffer)6 HeaderValues (io.undertow.util.HeaderValues)6 ClientRequest (io.undertow.client.ClientRequest)5 Session (io.undertow.server.session.Session)5 URISyntaxException (java.net.URISyntaxException)5 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)4 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)4 SessionManager (io.undertow.server.session.SessionManager)4 List (java.util.List)4 TypeConverter (org.apache.camel.TypeConverter)4