Search in sources :

Example 61 with HttpServerExchange

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

the class ConnectHandler method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.getRequestMethod().equals(Methods.CONNECT)) {
        if (!allowed.resolve(exchange)) {
            // not sure if this is the best response
            exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
            return;
        }
        String[] parts = exchange.getRequestPath().split(":");
        if (parts.length != 2) {
            // not sure if this is the best response
            exchange.setStatusCode(StatusCodes.BAD_REQUEST);
            return;
        }
        final String host = parts[0];
        final Integer port = Integer.parseInt(parts[1]);
        exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() {

            @Override
            public void run() {
                exchange.getConnection().getIoThread().openStreamConnection(new InetSocketAddress(host, port), new ChannelListener<StreamConnection>() {

                    @Override
                    public void handleEvent(final StreamConnection clientChannel) {
                        exchange.acceptConnectRequest(new HttpUpgradeListener() {

                            @Override
                            public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
                                final ClosingExceptionHandler handler = new ClosingExceptionHandler(streamConnection, clientChannel);
                                Transfer.initiateTransfer(clientChannel.getSourceChannel(), streamConnection.getSinkChannel(), ChannelListeners.closingChannelListener(), ChannelListeners.writeShutdownChannelListener(ChannelListeners.<StreamSinkChannel>flushingChannelListener(ChannelListeners.closingChannelListener(), ChannelListeners.closingChannelExceptionHandler()), ChannelListeners.closingChannelExceptionHandler()), handler, handler, exchange.getConnection().getByteBufferPool());
                                Transfer.initiateTransfer(streamConnection.getSourceChannel(), clientChannel.getSinkChannel(), ChannelListeners.closingChannelListener(), ChannelListeners.writeShutdownChannelListener(ChannelListeners.<StreamSinkChannel>flushingChannelListener(ChannelListeners.closingChannelListener(), ChannelListeners.closingChannelExceptionHandler()), ChannelListeners.closingChannelExceptionHandler()), handler, handler, exchange.getConnection().getByteBufferPool());
                            }
                        });
                        exchange.setStatusCode(200);
                        exchange.endExchange();
                    }
                }, OptionMap.create(Options.TCP_NODELAY, true)).addNotifier(new IoFuture.Notifier<StreamConnection, Object>() {

                    @Override
                    public void notify(IoFuture<? extends StreamConnection> ioFuture, Object attachment) {
                        if (ioFuture.getStatus() == IoFuture.Status.FAILED) {
                            exchange.setStatusCode(503);
                            exchange.endExchange();
                        }
                    }
                }, null);
            }
        });
    } else {
        next.handleRequest(exchange);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) IoFuture(org.xnio.IoFuture) StreamConnection(org.xnio.StreamConnection) HttpServerExchange(io.undertow.server.HttpServerExchange) HttpUpgradeListener(io.undertow.server.HttpUpgradeListener)

Example 62 with HttpServerExchange

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

the class RequestDispatcherImpl method setupIncludeImpl.

private void setupIncludeImpl(final ServletRequest request, final ServletResponse response) throws ServletException, IOException {
    final ServletRequestContext servletRequestContext = SecurityActions.currentServletRequestContext();
    if (servletRequestContext == null) {
        UndertowLogger.REQUEST_LOGGER.debugf("No servlet request context for %s, dispatching mock request", request);
        mock(request, response);
        return;
    }
    final HttpServletRequestImpl requestImpl = servletRequestContext.getOriginalRequest();
    final HttpServletResponseImpl responseImpl = servletRequestContext.getOriginalResponse();
    ServletContextImpl oldServletContext = null;
    HttpSessionImpl oldSession = null;
    if (servletRequestContext.getCurrentServletContext() != this.servletContext) {
        // cross context request, we need to run the thread setup actions
        oldServletContext = servletRequestContext.getCurrentServletContext();
        oldSession = servletRequestContext.getSession();
        servletRequestContext.setSession(null);
        servletRequestContext.setCurrentServletContext(this.servletContext);
        try {
            servletRequestContext.getCurrentServletContext().invokeAction(servletRequestContext.getExchange(), new ThreadSetupHandler.Action<Void, Object>() {

                @Override
                public Void call(HttpServerExchange exchange, Object context) throws Exception {
                    includeImpl(request, response, servletRequestContext, requestImpl, responseImpl);
                    return null;
                }
            });
        } finally {
            // update time in new context and run the requestDone for the session
            servletRequestContext.getCurrentServletContext().updateSessionAccessTime(servletRequestContext.getExchange());
            servletRequestContext.setSession(oldSession);
            servletRequestContext.setCurrentServletContext(oldServletContext);
        }
    } else {
        includeImpl(request, response, servletRequestContext, requestImpl, responseImpl);
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException)

Example 63 with HttpServerExchange

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

the class AsyncContextImpl method dispatch.

@Override
public void dispatch(final ServletContext context, final String path) {
    if (dispatched) {
        throw UndertowServletMessages.MESSAGES.asyncRequestAlreadyDispatched();
    }
    HttpServletRequestImpl requestImpl = servletRequestContext.getOriginalRequest();
    HttpServletResponseImpl responseImpl = servletRequestContext.getOriginalResponse();
    final HttpServerExchange exchange = requestImpl.getExchange();
    exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).setDispatcherType(DispatcherType.ASYNC);
    requestImpl.setAttribute(ASYNC_REQUEST_URI, requestImpl.getOriginalRequestURI());
    requestImpl.setAttribute(ASYNC_CONTEXT_PATH, requestImpl.getOriginalContextPath());
    requestImpl.setAttribute(ASYNC_SERVLET_PATH, requestImpl.getOriginalServletPath());
    requestImpl.setAttribute(ASYNC_QUERY_STRING, requestImpl.getOriginalQueryString());
    String newQueryString = "";
    int qsPos = path.indexOf("?");
    String newServletPath = path;
    if (qsPos != -1) {
        newQueryString = newServletPath.substring(qsPos + 1);
        newServletPath = newServletPath.substring(0, qsPos);
    }
    String newRequestUri = context.getContextPath() + newServletPath;
    // todo: a more efficient impl
    Map<String, Deque<String>> newQueryParameters = new HashMap<>();
    for (String part : newQueryString.split("&")) {
        String name = part;
        String value = "";
        int equals = part.indexOf('=');
        if (equals != -1) {
            name = part.substring(0, equals);
            value = part.substring(equals + 1);
        }
        Deque<String> queue = newQueryParameters.get(name);
        if (queue == null) {
            newQueryParameters.put(name, queue = new ArrayDeque<>(1));
        }
        queue.add(value);
    }
    requestImpl.setQueryParameters(newQueryParameters);
    requestImpl.getExchange().setRelativePath(newServletPath);
    requestImpl.getExchange().setQueryString(newQueryString);
    requestImpl.getExchange().setRequestPath(newRequestUri);
    requestImpl.getExchange().setRequestURI(newRequestUri);
    requestImpl.setServletContext((ServletContextImpl) context);
    responseImpl.setServletContext((ServletContextImpl) context);
    Deployment deployment = requestImpl.getServletContext().getDeployment();
    ServletPathMatch info = deployment.getServletPaths().getServletHandlerByPath(newServletPath);
    requestImpl.getExchange().getAttachment(ServletRequestContext.ATTACHMENT_KEY).setServletPathMatch(info);
    dispatchAsyncRequest(deployment.getServletDispatcher(), info, exchange);
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HashMap(java.util.HashMap) Deployment(io.undertow.servlet.api.Deployment) ServletPathMatch(io.undertow.servlet.handlers.ServletPathMatch) Deque(java.util.Deque) ArrayDeque(java.util.ArrayDeque) ArrayDeque(java.util.ArrayDeque)

Example 64 with HttpServerExchange

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

the class AsyncContextImpl method dispatchAsyncRequest.

private void dispatchAsyncRequest(final ServletDispatcher servletDispatcher, final ServletPathMatch pathInfo, final HttpServerExchange exchange) {
    doDispatch(new Runnable() {

        @Override
        public void run() {
            Connectors.executeRootHandler(new HttpHandler() {

                @Override
                public void handleRequest(final HttpServerExchange exchange) throws Exception {
                    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                    src.setServletRequest(servletRequest);
                    src.setServletResponse(servletResponse);
                    servletDispatcher.dispatchToPath(exchange, pathInfo, DispatcherType.ASYNC);
                }
            }, exchange);
        }
    });
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Example 65 with HttpServerExchange

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

the class ServletRequestContextThreadSetupAction method create.

@Override
public <T, C> Action<T, C> create(final Action<T, C> action) {
    return new Action<T, C>() {

        @Override
        public T call(HttpServerExchange exchange, C context) throws Exception {
            if (exchange == null) {
                return action.call(null, context);
            } else {
                ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                final ServletRequestContext old = ServletRequestContext.current();
                SecurityActions.setCurrentRequestContext(servletRequestContext);
                try {
                    return action.call(exchange, context);
                } finally {
                    ServletRequestContext.setCurrentRequestContext(old);
                }
            }
        }
    };
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Aggregations

HttpServerExchange (io.undertow.server.HttpServerExchange)277 HttpHandler (io.undertow.server.HttpHandler)127 Test (org.junit.Test)109 IOException (java.io.IOException)90 UnitTest (io.undertow.testutils.category.UnitTest)45 BeforeClass (org.junit.BeforeClass)44 TestHttpClient (io.undertow.testutils.TestHttpClient)42 HttpGet (org.apache.http.client.methods.HttpGet)40 HttpResponse (org.apache.http.HttpResponse)37 HttpString (io.undertow.util.HttpString)36 Header (org.apache.http.Header)24 Undertow (io.undertow.Undertow)19 ByteBuffer (java.nio.ByteBuffer)19 SessionConfig (io.undertow.server.session.SessionConfig)16 Map (java.util.Map)16 Sender (io.undertow.io.Sender)15 ExchangeCompletionListener (io.undertow.server.ExchangeCompletionListener)14 HeaderMap (io.undertow.util.HeaderMap)13 URI (java.net.URI)13 HeaderValues (io.undertow.util.HeaderValues)12