Java Code Examples for io.undertow.server.HttpHandler#handleRequest()

The following examples show how to use io.undertow.server.HttpHandler#handleRequest() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiPartParserDefinition.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void parse(final HttpHandler handler) throws Exception {
    if (exchange.getAttachment(FORM_DATA) != null) {
        handler.handleRequest(exchange);
        return;
    }
    this.handler = handler;
    //we need to delegate to a thread pool
    //as we parse with blocking operations

    NonBlockingParseTask task;
    if (executor == null) {
        task = new NonBlockingParseTask(exchange.getWorker());
    } else {
        task = new NonBlockingParseTask(executor);
    }
    exchange.dispatch(executor, task);
}
 
Example 2
Source File: NameVirtualHostHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final String hostHeader = exchange.getRequestHeaders().getFirst(Headers.HOST);
    if (hostHeader != null) {
        String host;
        if (hostHeader.contains(":")) { //header can be in host:port format
            host = hostHeader.substring(0, hostHeader.lastIndexOf(":"));
        } else {
            host = hostHeader;
        }
        //most hosts will be lowercase, so we do the host
        HttpHandler handler = hosts.get(host);
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
        //do a cache insensitive match
        handler = hosts.get(host.toLowerCase(Locale.ENGLISH));
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
    }
    defaultHandler.handleRequest(exchange);
}
 
Example 3
Source File: NameVirtualHostHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final String hostHeader = exchange.getRequestHeader(HttpHeaderNames.HOST);
    if (hostHeader != null) {
        String host;
        if (hostHeader.contains(":")) { //header can be in host:port format
            host = hostHeader.substring(0, hostHeader.lastIndexOf(":"));
        } else {
            host = hostHeader;
        }
        //most hosts will be lowercase, so we do the host
        HttpHandler handler = hosts.get(host);
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
        //do a cache insensitive match
        handler = hosts.get(host.toLowerCase(Locale.ENGLISH));
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
    }
    defaultHandler.handleRequest(exchange);
}
 
Example 4
Source File: CustomHandlers.java    From StubbornJava with MIT License 6 votes vote down vote up
public static HttpHandler loadBalancerHttpToHttps(HttpHandler next) {
    return (HttpServerExchange exchange) -> {
        HttpUrl currentUrl = Exchange.urls().currentUrl(exchange);
        String protocolForward = Exchange.headers().getHeader(exchange, "X-Forwarded-Proto").orElse(null);
        if (null != protocolForward && protocolForward.equalsIgnoreCase("http")) {
            log.debug("non https switching to https {}", currentUrl.host());
            HttpUrl newUrl = currentUrl.newBuilder()
               .scheme("https")
               .port(443)
               .build();
            exchange.setStatusCode(301);
            exchange.getResponseHeaders().put(Headers.LOCATION, newUrl.toString());
            exchange.endExchange();
            return;
        }

        next.handleRequest(exchange);
    };
}
 
Example 5
Source File: MultiPartParserDefinition.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void parse(final HttpHandler handler) throws Exception {
    if (exchange.getAttachment(FORM_DATA) != null) {
        handler.handleRequest(exchange);
        return;
    }
    this.handler = handler;
    //we need to delegate to a thread pool
    //as we parse with blocking operations

    StreamSourceChannel requestChannel = exchange.getRequestChannel();
    if (requestChannel == null) {
        throw new IOException(UndertowMessages.MESSAGES.requestChannelAlreadyProvided());
    }
    if (executor == null) {
        exchange.dispatch(new NonBlockingParseTask(exchange.getConnection().getWorker(), requestChannel));
    } else {
        exchange.dispatch(executor, new NonBlockingParseTask(executor, requestChannel));
    }
}
 
Example 6
Source File: RewriteCorrectingHandlerWrappers.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public HttpHandler wrap(final HttpHandler handler) {
    return new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            String old = exchange.getAttachment(OLD_RELATIVE_PATH);
            if (!old.equals(exchange.getRelativePath())) {
                ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                ServletPathMatch info = src.getDeployment().getServletPaths()
                        .getServletHandlerByPath(exchange.getRelativePath());
                src.setCurrentServlet(info.getServletChain());
                src.setServletPathMatch(info);
            }
            handler.handleRequest(exchange);
        }
    };
}
 
Example 7
Source File: PredicatesHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public HandlerWrapper build(Map<String, Object> config) {
    return new HandlerWrapper() {
        @Override
        public HttpHandler wrap(final HttpHandler handler) {
            return new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    exchange.putAttachment(DONE, true);
                    handler.handleRequest(exchange);
                }
            };
        }
    };
}
 
Example 8
Source File: RequestLimit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void handleRequest(final HttpServerExchange exchange, final HttpHandler next) throws Exception {
    int oldVal, newVal;
    do {
        oldVal = requests;
        if (oldVal >= max) {
            exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() {
                @Override
                public void run() {
                    //we have to try again in the sync block
                    //we need to have already dispatched for thread safety reasons
                    synchronized (RequestLimit.this) {
                        int oldVal, newVal;
                        do {
                            oldVal = requests;
                            if (oldVal >= max) {
                                if (!queue.offer(new SuspendedRequest(exchange, next))) {
                                    Connectors.executeRootHandler(failureHandler, exchange);
                                }
                                return;
                            }
                            newVal = oldVal + 1;
                        } while (!requestsUpdater.compareAndSet(RequestLimit.this, oldVal, newVal));
                        exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
                        exchange.dispatch(next);
                    }
                }
            });
            return;
        }
        newVal = oldVal + 1;
    } while (!requestsUpdater.compareAndSet(this, oldVal, newVal));
    exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
    next.handleRequest(exchange);
}
 
Example 9
Source File: ServletChain.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ServletChain(final HttpHandler originalHandler, final ManagedServlet managedServlet, final String servletPath, boolean defaultServletMapping, MappingMatch mappingMatch, String pattern, Map<DispatcherType, List<ManagedFilter>> filters, boolean wrapHandler) {
    if (wrapHandler) {
        this.handler = new HttpHandler() {

            private volatile boolean initDone = false;

            @Override
            public void handleRequest(HttpServerExchange exchange) throws Exception {
                if(!initDone) {
                    synchronized (this) {
                        if(!initDone) {
                            ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                            forceInit(src.getDispatcherType());
                            initDone = true;
                        }
                    }
                }
                originalHandler.handleRequest(exchange);
            }
        };
    } else {
        this.handler = originalHandler;
    }
    this.managedServlet = managedServlet;
    this.servletPath = servletPath;
    this.defaultServletMapping = defaultServletMapping;
    this.mappingMatch = mappingMatch;
    this.pattern = pattern;
    this.executor = managedServlet.getServletInfo().getExecutor();
    this.filters = filters;
}
 
Example 10
Source File: PredicatesHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public HandlerWrapper build(Map<String, Object> config) {
    return new HandlerWrapper() {
        @Override
        public HttpHandler wrap(final HttpHandler handler) {
            return new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    exchange.putAttachment(DONE, true);
                    handler.handleRequest(exchange);
                }
            };
        }
    };
}
 
Example 11
Source File: TestWrapper.java    From proteus with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler wrap(HttpHandler handler)
{
    return exchange -> {

        log.debug("Test wrapper");

        exchange.putAttachment(DEBUG_TEST_KEY,wrapperValue);

        handler.handleRequest(exchange);
    };
}
 
Example 12
Source File: TestClassWrapper.java    From proteus with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler wrap(HttpHandler handler)
{
    return exchange -> {

        handler.handleRequest(exchange);
    };
}
 
Example 13
Source File: XFrameOptionsHandlers.java    From StubbornJava with MIT License 5 votes vote down vote up
public static HttpHandler allowFromDynamicOrigin(HttpHandler next,
                                    Function<HttpServerExchange, String> originExtractor) {
    // Since this is dynamic skip using the SetHeaderHandler
    return exchange -> {
        exchange.getResponseHeaders().put(X_FRAME_OPTIONS, originExtractor.apply(exchange));
        next.handleRequest(exchange);
    };
}
 
Example 14
Source File: RewriteCorrectingHandlerWrappers.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler wrap(final HttpHandler handler) {
    return new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.putAttachment(OLD_RELATIVE_PATH, exchange.getRelativePath());
            handler.handleRequest(exchange);
        }
    };
}
 
Example 15
Source File: RequestLimit.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void handleRequest(final HttpServerExchange exchange, final HttpHandler next) throws Exception {
    int oldVal, newVal;
    do {
        oldVal = requests;
        if (oldVal >= max) {
            exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() {
                @Override
                public void run() {
                    //we have to try again in the sync block
                    //we need to have already dispatched for thread safety reasons
                    synchronized (RequestLimit.this) {
                        int oldVal, newVal;
                        do {
                            oldVal = requests;
                            if (oldVal >= max) {
                                if (!queue.offer(new SuspendedRequest(exchange, next))) {
                                    Connectors.executeRootHandler(failureHandler, exchange);
                                }
                                return;
                            }
                            newVal = oldVal + 1;
                        } while (!requestsUpdater.compareAndSet(RequestLimit.this, oldVal, newVal));
                        exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
                        exchange.dispatch(next);
                    }
                }
            });
            return;
        }
        newVal = oldVal + 1;
    } while (!requestsUpdater.compareAndSet(this, oldVal, newVal));
    exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
    next.handleRequest(exchange);
}
 
Example 16
Source File: PageRoutes.java    From StubbornJava with MIT License 5 votes vote down vote up
public static HttpHandler redirector(HttpHandler next) {
    return (HttpServerExchange exchange) -> {
        HttpUrl currentUrl = Exchange.urls().currentUrl(exchange);
        String protocolForward = Exchange.headers().getHeader(exchange, "X-Forwarded-Proto").orElse(null);
        String host = currentUrl.host();
        boolean redirect = false;

        Builder newUrlBuilder = currentUrl.newBuilder();

        if (host.equals("stubbornjava.com")) {
            host = "www." + host;
            newUrlBuilder.host(host);
            redirect = true;
            logger.debug("Host {} does not start with www redirecting to {}", currentUrl.host(), host);
        }

        if (null != protocolForward && protocolForward.equalsIgnoreCase("http")) {
            logger.debug("non https switching to https", currentUrl.host(), host);
            newUrlBuilder.scheme("https")
                         .port(443);
            redirect = true;
        }

        if (redirect) {
            HttpUrl newUrl = newUrlBuilder.build();
            exchange.setStatusCode(301);
            exchange.getResponseHeaders().put(Headers.LOCATION, newUrl.toString());
            exchange.endExchange();
            return;
        }
        next.handleRequest(exchange);
    };
}
 
Example 17
Source File: ServletChain.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private ServletChain(final HttpHandler originalHandler, final ManagedServlet managedServlet, final String servletPath, boolean defaultServletMapping, MappingMatch mappingMatch, String pattern, Map<DispatcherType, List<ManagedFilter>> filters, boolean wrapHandler) {
    if (wrapHandler) {
        this.handler = new HttpHandler() {

            private volatile boolean initDone = false;

            @Override
            public void handleRequest(HttpServerExchange exchange) throws Exception {
                if(!initDone) {
                    synchronized (this) {
                        if(!initDone) {
                            ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                            forceInit(src.getDispatcherType());
                            initDone = true;
                        }
                    }
                }
                originalHandler.handleRequest(exchange);
            }
        };
    } else {
        this.handler = originalHandler;
    }
    this.managedServlet = managedServlet;
    this.servletPath = servletPath;
    this.defaultServletMapping = defaultServletMapping;
    this.mappingMatch = mappingMatch;
    this.pattern = pattern;
    this.executor = managedServlet.getServletInfo().getExecutor();
    this.filters = filters;
}
 
Example 18
Source File: PredicateHandler.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    HttpHandler next = predicate.resolve(exchange) ? trueHandler : falseHandler;
    next.handleRequest(exchange);
}
 
Example 19
Source File: PredicateHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    HttpHandler next = predicate.resolve(exchange) ? trueHandler : falseHandler;
    next.handleRequest(exchange);
}
 
Example 20
Source File: HeaderApiKeyWrapper.java    From proteus with Apache License 2.0 3 votes vote down vote up
@Override
public HttpHandler wrap(HttpHandler handler)
{
    return exchange -> {

        if(API_KEY == null)
        {
            handler.handleRequest(exchange);
            return;
        }

        Optional<String> keyValue = Optional.ofNullable(exchange.getRequestHeaders().getFirst(API_KEY_HEADER));

        if(!keyValue.isPresent() || !keyValue.get().equals(API_KEY))
        {

            logger.error("Missing security credentials");
            exchange.putAttachment(THROWABLE, new ServerException("Unauthorized access", Response.Status.UNAUTHORIZED));
            throw new ServerException("Unauthorized access", Response.Status.UNAUTHORIZED);

        }

        handler.handleRequest(exchange);



    };
}