Search in sources :

Example 11 with HttpString

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

the class HTTP2ViaUpgradeTestCase method setup.

@BeforeClass
public static void setup() throws URISyntaxException {
    final SessionCookieConfig sessionConfig = new SessionCookieConfig();
    int port = DefaultServer.getHostPort("default");
    server = Undertow.builder().addHttpListener(port + 1, DefaultServer.getHostAddress("default")).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setSocketOption(Options.REUSE_ADDRESSES, true).setHandler(Handlers.header(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");
            exchange.getResponseSender().send(message);
        }
    }, "h2c", "h2c-17"), Headers.SEC_WEB_SOCKET_ACCEPT_STRING, //work around Netty bug, it assumes that every upgrade request that does not have this header is an old style websocket upgrade
    "fake")).build();
    server.start();
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) URISyntaxException(java.net.URISyntaxException) HttpString(io.undertow.util.HttpString) BeforeClass(org.junit.BeforeClass)

Example 12 with HttpString

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

the class URLRewritingSessionTestCase method setup.

@BeforeClass
public static void setup() {
    final PathParameterSessionConfig sessionConfig = new PathParameterSessionConfig();
    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);
            } else {
                Assert.assertEquals("/notamatchingpath;jsessionid=" + session.getId(), exchange.getRequestURI());
            }
            Integer count = (Integer) session.getAttribute(COUNT);
            exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
            session.setAttribute(COUNT, ++count);
            for (Map.Entry<String, Deque<String>> qp : exchange.getQueryParameters().entrySet()) {
                exchange.getResponseHeaders().add(new HttpString(qp.getKey()), qp.getValue().getFirst());
            }
            if (exchange.getQueryString().isEmpty()) {
                exchange.getResponseSender().send(sessionConfig.rewriteUrl(DefaultServer.getDefaultServerURL() + "/notamatchingpath", session.getId()));
            } else {
                exchange.getResponseSender().send(sessionConfig.rewriteUrl(DefaultServer.getDefaultServerURL() + "/notamatchingpath?" + exchange.getQueryString(), session.getId()));
            }
        }
    });
    DefaultServer.setRootHandler(handler);
}
Also used : HttpHandler(io.undertow.server.HttpHandler) PathParameterSessionConfig(io.undertow.server.session.PathParameterSessionConfig) SessionManager(io.undertow.server.session.SessionManager) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) HttpString(io.undertow.util.HttpString) IOException(java.io.IOException) HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) Session(io.undertow.server.session.Session) HttpString(io.undertow.util.HttpString) BeforeClass(org.junit.BeforeClass)

Example 13 with HttpString

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

the class MCMPHandler method handleRequest.

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final HttpString method = exchange.getRequestMethod();
    if (!handlesMethod(method)) {
        next.handleRequest(exchange);
        return;
    }
    /*
         * Proxy the request that needs to be proxied and process others
         */
    // TODO maybe this should be handled outside here?
    final InetSocketAddress addr = exchange.getConnection().getLocalAddress(InetSocketAddress.class);
    if (!addr.isUnresolved() && addr.getPort() != config.getManagementSocketAddress().getPort() || !Arrays.equals(addr.getAddress().getAddress(), config.getManagementSocketAddress().getAddress().getAddress())) {
        next.handleRequest(exchange);
        return;
    }
    if (exchange.isInIoThread()) {
        //for now just do all the management stuff in a worker, as it uses blocking IO
        exchange.dispatch(this);
        return;
    }
    try {
        handleRequest(method, exchange);
    } catch (Exception e) {
        UndertowLogger.ROOT_LOGGER.failedToProcessManagementReq(e);
        exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
        exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
        final Sender sender = exchange.getResponseSender();
        sender.send("failed to process management request");
    }
}
Also used : Sender(io.undertow.io.Sender) InetSocketAddress(java.net.InetSocketAddress) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) HttpString(io.undertow.util.HttpString)

Example 14 with HttpString

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

the class SavedRequest method tryRestoreRequest.

public static void tryRestoreRequest(final HttpServerExchange exchange, HttpSession session) {
    if (session instanceof HttpSessionImpl) {
        Session underlyingSession;
        if (System.getSecurityManager() == null) {
            underlyingSession = ((HttpSessionImpl) session).getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
        }
        SavedRequest request = (SavedRequest) underlyingSession.getAttribute(SESSION_KEY);
        if (request != null) {
            if (request.requestPath.equals(exchange.getRelativePath()) && exchange.isRequestComplete()) {
                UndertowLogger.REQUEST_LOGGER.debugf("restoring request body for request to %s", request.requestPath);
                exchange.setRequestMethod(request.method);
                Connectors.ungetRequestBytes(exchange, new ImmediatePooledByteBuffer(ByteBuffer.wrap(request.data, 0, request.dataLength)));
                underlyingSession.removeAttribute(SESSION_KEY);
                //clear the existing header map of everything except the connection header
                //TODO: are there other headers we should preserve?
                Iterator<HeaderValues> headerIterator = exchange.getRequestHeaders().iterator();
                while (headerIterator.hasNext()) {
                    HeaderValues header = headerIterator.next();
                    if (!header.getHeaderName().equals(Headers.CONNECTION)) {
                        headerIterator.remove();
                    }
                }
                for (Map.Entry<HttpString, List<String>> header : request.headerMap.entrySet()) {
                    exchange.getRequestHeaders().putAll(header.getKey(), header.getValue());
                }
            }
        }
    }
}
Also used : HttpSessionImpl(io.undertow.servlet.spec.HttpSessionImpl) HeaderValues(io.undertow.util.HeaderValues) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) HeaderMap(io.undertow.util.HeaderMap) Map(java.util.Map) HttpSession(javax.servlet.http.HttpSession) Session(io.undertow.server.session.Session) ImmediatePooledByteBuffer(io.undertow.util.ImmediatePooledByteBuffer) HttpString(io.undertow.util.HttpString)

Example 15 with HttpString

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

the class HttpClientConnection method initiateRequest.

private void initiateRequest(HttpClientExchange httpClientExchange) {
    this.requestCount++;
    currentRequest = httpClientExchange;
    pendingResponse = new HttpResponseBuilder();
    ClientRequest request = httpClientExchange.getRequest();
    String connectionString = request.getRequestHeaders().getFirst(CONNECTION);
    if (connectionString != null) {
        HttpString connectionHttpString = new HttpString(connectionString);
        if (connectionHttpString.equals(CLOSE)) {
            state |= CLOSE_REQ;
        } else if (connectionHttpString.equals(UPGRADE)) {
            state |= UPGRADE_REQUESTED;
        }
    } else if (request.getProtocol() != Protocols.HTTP_1_1) {
        state |= CLOSE_REQ;
    }
    if (request.getRequestHeaders().contains(UPGRADE)) {
        state |= UPGRADE_REQUESTED;
    }
    if (request.getMethod().equals(Methods.CONNECT)) {
        //we treat CONNECT like upgrade requests
        state |= UPGRADE_REQUESTED;
    }
    //setup the client request conduits
    final ConduitStreamSourceChannel sourceChannel = connection.getSourceChannel();
    sourceChannel.setReadListener(clientReadListener);
    sourceChannel.resumeReads();
    ConduitStreamSinkChannel sinkChannel = connection.getSinkChannel();
    StreamSinkConduit conduit = originalSinkConduit;
    conduit = new HttpRequestConduit(conduit, bufferPool, request);
    String fixedLengthString = request.getRequestHeaders().getFirst(CONTENT_LENGTH);
    String transferEncodingString = request.getRequestHeaders().getLast(TRANSFER_ENCODING);
    boolean hasContent = true;
    if (fixedLengthString != null) {
        try {
            long length = Long.parseLong(fixedLengthString);
            conduit = new ClientFixedLengthStreamSinkConduit(conduit, length, false, false, currentRequest);
            hasContent = length != 0;
        } catch (NumberFormatException e) {
            handleError(new IOException(e));
            return;
        }
    } else if (transferEncodingString != null) {
        if (!transferEncodingString.toLowerCase(Locale.ENGLISH).contains(Headers.CHUNKED.toString())) {
            handleError(UndertowClientMessages.MESSAGES.unknownTransferEncoding(transferEncodingString));
            return;
        }
        conduit = new ChunkedStreamSinkConduit(conduit, httpClientExchange.getConnection().getBufferPool(), false, false, httpClientExchange.getRequest().getRequestHeaders(), requestFinishListener, httpClientExchange);
    } else {
        conduit = new ClientFixedLengthStreamSinkConduit(conduit, 0, false, false, currentRequest);
        hasContent = false;
    }
    sinkChannel.setConduit(conduit);
    httpClientExchange.invokeReadReadyCallback();
    if (!hasContent) {
        //otherwise it is up to the user
        try {
            sinkChannel.shutdownWrites();
            if (!sinkChannel.flush()) {
                sinkChannel.setWriteListener(ChannelListeners.flushingChannelListener(null, new ChannelExceptionHandler<ConduitStreamSinkChannel>() {

                    @Override
                    public void handleException(ConduitStreamSinkChannel channel, IOException exception) {
                        handleError(exception);
                    }
                }));
                sinkChannel.resumeWrites();
            }
        } catch (IOException e) {
            handleError(e);
        }
    }
}
Also used : ChunkedStreamSinkConduit(io.undertow.conduits.ChunkedStreamSinkConduit) HttpString(io.undertow.util.HttpString) IOException(java.io.IOException) StreamSinkConduit(org.xnio.conduits.StreamSinkConduit) BytesSentStreamSinkConduit(io.undertow.conduits.BytesSentStreamSinkConduit) ChunkedStreamSinkConduit(io.undertow.conduits.ChunkedStreamSinkConduit) ChannelExceptionHandler(org.xnio.ChannelExceptionHandler) ConduitStreamSourceChannel(org.xnio.conduits.ConduitStreamSourceChannel) ClientRequest(io.undertow.client.ClientRequest) ConduitStreamSinkChannel(org.xnio.conduits.ConduitStreamSinkChannel) 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