Java Code Examples for io.undertow.server.HttpServerExchange#getRelativePath()

The following examples show how to use io.undertow.server.HttpServerExchange#getRelativePath() . 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: RedirectDirHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final String path = exchange.getRelativePath();
    final ServletPathMatch info = paths.getServletHandlerByPath(path);
    // https://issues.jboss.org/browse/WFLY-3439
    // if the request is an upgrade request then we don't want to redirect
    // as there is a good chance the web socket client won't understand the redirect
    // we make an exception for HTTP2 upgrade requests, as this would have already be handled at
    // the connector level if it was going to be handled.
    String upgradeString = exchange.getRequestHeader(HttpHeaderNames.UPGRADE);
    boolean isUpgradeRequest = upgradeString != null && !upgradeString.startsWith(HTTP2_UPGRADE_PREFIX);
    if (info.getType() == ServletPathMatch.Type.REDIRECT && !isUpgradeRequest) {
        // UNDERTOW-89
        // we redirect on GET requests to the root context to add an / to the end
        if (exchange.getRequestMethod().equals(HttpMethodNames.GET) || exchange.getRequestMethod().equals(HttpMethodNames.GET)) {
            exchange.setStatusCode(StatusCodes.FOUND);
        } else {
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
        }
        exchange.setResponseHeader(HttpHeaderNames.LOCATION, RedirectBuilder.redirect(exchange, exchange.getRelativePath() + "/", true));
        return;
    }
    next.handleRequest(exchange);
}
 
Example 2
Source File: ServletSecurityConstraintHandler.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 path = exchange.getRelativePath();
    SecurityPathMatch securityMatch = securityPathMatches.getSecurityInfo(path, exchange.getRequestMethod());
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    List<SingleConstraintMatch> list = servletRequestContext.getRequiredConstrains();
    if (list == null) {
        servletRequestContext.setRequiredConstrains(list = new ArrayList<>());
    }
    list.add(securityMatch.getMergedConstraint());
    TransportGuaranteeType type = servletRequestContext.getTransportGuarenteeType();
    if (type == null || type.ordinal() < securityMatch.getTransportGuaranteeType().ordinal()) {
        servletRequestContext.setTransportGuarenteeType(securityMatch.getTransportGuaranteeType());
    }

    UndertowLogger.SECURITY_LOGGER.debugf("Security constraints for request %s are %s", exchange.getRequestURI(), list);
    next.handleRequest(exchange);
}
 
Example 3
Source File: ManagementHttpServer.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (Methods.POST.equals(exchange.getRequestMethod()))  {
        ResponseCodeHandler.HANDLE_405.handleRequest(exchange);
        return;
    }
    String origReqPath = exchange.getRelativePath();
    String remapped = remapper.remapPath(origReqPath);
    if (remapped == null) {
        ResponseCodeHandler.HANDLE_404.handleRequest(exchange);
        return;
    }
    exchange.setRelativePath(remapped);

    // Note: we only change the relative path, not other exchange data that
    // incorporates it (like getRequestPath(), getRequestURL()) and not the
    // resolved path. If this request gets to DomainApiHandler, it should
    // work off the relative path. Other handlers in between may need the
    // original data.

    next.handleRequest(exchange);
}
 
Example 4
Source File: ServletSecurityConstraintHandler.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 path = exchange.getRelativePath();
    SecurityPathMatch securityMatch = securityPathMatches.getSecurityInfo(path, exchange.getRequestMethod().toString());
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    List<SingleConstraintMatch> list = servletRequestContext.getRequiredConstrains();
    if (list == null) {
        servletRequestContext.setRequiredConstrains(list = new ArrayList<>());
    }
    list.add(securityMatch.getMergedConstraint());
    TransportGuaranteeType type = servletRequestContext.getTransportGuarenteeType();
    if (type == null || type.ordinal() < securityMatch.getTransportGuaranteeType().ordinal()) {
        servletRequestContext.setTransportGuarenteeType(securityMatch.getTransportGuaranteeType());
    }

    UndertowLogger.SECURITY_LOGGER.debugf("Security constraints for request %s are %s", exchange.getRequestURI(), list);
    next.handleRequest(exchange);
}
 
Example 5
Source File: OpenshiftAuthHandler.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange serverExchange) throws Exception {
    // Skip authentication if we are dealing with a CORS preflight request
    // CORS preflight removes any user credentials and doesn't perform an actual invocation.
    // http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
    if (OPTIONS.equals(serverExchange.getRequestMethod())
            && serverExchange.getRequestHeaders().contains(ORIGIN)) {
        containerHandler.handleRequest(serverExchange);
        return;
    }

    // There are a few endpoint that should not be secured. If we secure the status endpoint when we cannot
    // tell if the container is up and it will always be marked as pending
    String path = serverExchange.getRelativePath();
    if (insecureEndpoints != null && insecureEndpoints.matcher(path).find()) {
        containerHandler.handleRequest(serverExchange);
        return;
    }

    // If it is set to be disabled, then just continue
    if (SECURITY_OPTIONS.contains(DISABLED)) {
        containerHandler.handleRequest(serverExchange);
        return;
    }

    // Get the authorization header and determine how it should be handled
    String authorizationHeader = serverExchange.getRequestHeaders().getFirst(AUTHORIZATION);
    if (authorizationHeader == null) {
        endExchange(serverExchange, FORBIDDEN);
    } else if (authorizationHeader.startsWith(BEARER_PREFIX) && SECURITY_OPTIONS.contains(OPENSHIFT_OAUTH)) {
        tokenAuthenticator.handleRequest(serverExchange);
    } else if (authorizationHeader.startsWith(BASIC_PREFIX) && SECURITY_OPTIONS.contains(HTPASSWD)) {
        basicAuthenticator.handleRequest(serverExchange);
    } else {
        endExchange(serverExchange, FORBIDDEN);
    }
}
 
Example 6
Source File: SavedRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange, final byte[] buffer, int length) {
    int maxSize = exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_BUFFERED_REQUEST_SIZE, UndertowOptions.DEFAULT_MAX_BUFFERED_REQUEST_SIZE);
    if (maxSize > 0) {
        if (length > maxSize) {
            UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
            return;//failed to save the request, we just return
        }
        //TODO: we should really be used pooled buffers
        //TODO: we should probably limit the number of saved requests at any given time
        HeaderMap headers = new HeaderMap();
        for (HeaderValues entry : exchange.getRequestHeaders()) {
            if (entry.getHeaderName().equals(Headers.CONTENT_LENGTH) ||
                    entry.getHeaderName().equals(Headers.TRANSFER_ENCODING) ||
                    entry.getHeaderName().equals(Headers.CONNECTION)) {
                continue;
            }
            headers.putAll(entry.getHeaderName(), entry);
        }
        SavedRequest request = new SavedRequest(buffer, length, exchange.getRequestMethod(), exchange.getRelativePath(), exchange.getRequestHeaders());
        final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
        Session underlyingSession;
        if (System.getSecurityManager() == null) {
            underlyingSession = session.getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
        }
        underlyingSession.setAttribute(SESSION_KEY, request);
    }
}
 
Example 7
Source File: PathPrefixPredicate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean resolve(final HttpServerExchange value) {
    final String relativePath = value.getRelativePath();
    PathMatcher.PathMatch<Boolean> result = pathMatcher.match(relativePath);

    boolean matches = Boolean.TRUE.equals(result.getValue());
    if(matches) {
        Map<String, Object> context = value.getAttachment(PREDICATE_CONTEXT);
        if(context == null) {
            value.putAttachment(PREDICATE_CONTEXT, context = new TreeMap<>());
        }
        context.put("remaining", result.getRemaining());
    }
    return matches;
}
 
Example 8
Source File: PathGlobHandler.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final String path = exchange.getRelativePath();
    if ("/__galeb_rule_path_check__".equals(path)) {
        pathGlobHandlerCheck().handleRequest(exchange);
        return;
    }
    final AtomicBoolean hit = new AtomicBoolean(false);
    paths.forEach((key, handler) -> {
        if (!hit.get()) {
            final String pathKey = key.getPath();
            hit.set(Wildcard.match(path, pathKey));
            if (hit.get()) {
                try {
                    if (handler != null) {
                        handler.handleRequest(exchange);
                    } else {
                        logger.error("Handler is null");
                    }
                } catch (Exception e) {
                    ErrorLogger.logError(e, this.getClass());
                }
            }
        }
    });
    if (!hit.get()) {
        defaultHandler.handleRequest(exchange);
    }
}
 
Example 9
Source File: SetAttributeTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final StringBuilder sb = new StringBuilder("URI: " + exchange.getRequestURI()
            + " relative: " + exchange.getRelativePath()
            + " QS:" + exchange.getQueryString());
    for (Map.Entry<String, Deque<String>> param : exchange.getQueryParameters().entrySet()) {
        sb.append(" " + param.getKey() + ": " + param.getValue().getFirst());
    }
    exchange.writeAsync(sb.toString());
}
 
Example 10
Source File: PathPrefixPredicate.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public boolean resolve(final HttpServerExchange value) {
    final String relativePath = value.getRelativePath();
    PathMatcher.PathMatch<Boolean> result = pathMatcher.match(relativePath);

    boolean matches = Boolean.TRUE.equals(result.getValue());
    if(matches) {
        Map<String, Object> context = value.getAttachment(PREDICATE_CONTEXT);
        if(context == null) {
            value.putAttachment(PREDICATE_CONTEXT, context = new TreeMap<>());
        }
        context.put("remaining", result.getRemaining());
    }
    return matches;
}
 
Example 11
Source File: SavedRequest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange, final byte[] buffer, int length) {
    int maxSize = exchange.getUndertowOptions().get(UndertowOptions.MAX_BUFFERED_REQUEST_SIZE, UndertowOptions.DEFAULT_MAX_BUFFERED_REQUEST_SIZE);
    if (maxSize > 0) {
        if (length > maxSize) {
            UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
            return;//failed to save the request, we just return
        }
        //TODO: we should really be used pooled buffers
        //TODO: we should probably limit the number of saved requests at any given time
        HttpHeaders headers = new DefaultHttpHeaders();
        for (String entry : exchange.getRequestHeaderNames()) {
            if (entry.equals(HttpHeaderNames.CONTENT_LENGTH) ||
                    entry.equals(HttpHeaderNames.TRANSFER_ENCODING) ||
                    entry.equals(HttpHeaderNames.CONNECTION)) {
                continue;
            }
            headers.set(entry, exchange.getRequestHeaders(entry));
        }
        SavedRequest request = new SavedRequest(buffer, length, exchange.getRequestMethod(), exchange.getRelativePath(), headers);
        final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
        Session underlyingSession;
        if (System.getSecurityManager() == null) {
            underlyingSession = session.getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
        }
        underlyingSession.setAttribute(SESSION_KEY, request);
    }
}
 
Example 12
Source File: ServletInitialHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final String path = exchange.getRelativePath();
    if (isForbiddenPath(path)) {
        exchange.setStatusCode(StatusCodes.NOT_FOUND);
        return;
    }
    final ServletPathMatch info = paths.getServletHandlerByPath(path);
    if (info.getType() == ServletPathMatch.Type.REWRITE) {
        // this can only happen if the path ends with a /
        // otherwise there would be a redirect instead
        exchange.setRelativePath(info.getRewriteLocation());
        exchange.setRequestPath(exchange.getResolvedPath() + info.getRewriteLocation());
    }
    final HttpServletResponseImpl response = new HttpServletResponseImpl(exchange, servletContext);
    final HttpServletRequestImpl request = new HttpServletRequestImpl(exchange, servletContext);
    final ServletRequestContext servletRequestContext = new ServletRequestContext(servletContext.getDeployment(), request, response, info);
    //set the max request size if applicable
    if (info.getServletChain().getManagedServlet().getMaxRequestSize() > 0) {
        exchange.setMaxEntitySize(info.getServletChain().getManagedServlet().getMaxRequestSize());
    }
    exchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext);

    exchange.startBlocking(new ServletBlockingHttpExchange(exchange));
    servletRequestContext.setServletPathMatch(info);

    Executor executor = info.getServletChain().getExecutor();
    if (executor == null) {
        executor = servletContext.getDeployment().getExecutor();
    }

    if (exchange.isInIoThread() || executor != null) {
        //either the exchange has not been dispatched yet, or we need to use a special executor
        exchange.dispatch(executor, dispatchHandler);
    } else {
        dispatchRequest(exchange, servletRequestContext, info.getServletChain(), DispatcherType.REQUEST);
    }
}
 
Example 13
Source File: HashUriPathHostSelector.java    From galeb with Apache License 2.0 4 votes vote down vote up
private String getKey(final HttpServerExchange exchange) {
    return exchange.getRelativePath();
}
 
Example 14
Source File: RelativePathAttribute.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    return exchange.getRelativePath();
}
 
Example 15
Source File: PathMatchPredicate.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public boolean resolve(final HttpServerExchange value) {
    final String relativePath = value.getRelativePath();
    PathMatcher.PathMatch<Boolean> result = pathMatcher.match(relativePath);
    return Boolean.TRUE.equals(result.getValue());
}
 
Example 16
Source File: RequestPathAttribute.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    return exchange.getRelativePath();
}
 
Example 17
Source File: RequestPathAttribute.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    return exchange.getRelativePath();
}
 
Example 18
Source File: RelativePathAttribute.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    return exchange.getRelativePath();
}
 
Example 19
Source File: ServletInitialHandler.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 {
    final String path = exchange.getRelativePath();
    if(isForbiddenPath(path)) {
        exchange.setStatusCode(StatusCodes.NOT_FOUND);
        return;
    }
    final ServletPathMatch info = paths.getServletHandlerByPath(path);
    //https://issues.jboss.org/browse/WFLY-3439
    //if the request is an upgrade request then we don't want to redirect
    //as there is a good chance the web socket client won't understand the redirect
    //we make an exception for HTTP2 upgrade requests, as this would have already be handled at
    //the connector level if it was going to be handled.
    String upgradeString = exchange.getRequestHeaders().getFirst(Headers.UPGRADE);
    boolean isUpgradeRequest = upgradeString != null && !upgradeString.startsWith(HTTP2_UPGRADE_PREFIX);
    if (info.getType() == ServletPathMatch.Type.REDIRECT && !isUpgradeRequest) {
        //UNDERTOW-89
        //we redirect on GET requests to the root context to add an / to the end
        if(exchange.getRequestMethod().equals(Methods.GET) || exchange.getRequestMethod().equals(Methods.HEAD)) {
            exchange.setStatusCode(StatusCodes.FOUND);
        } else {
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
        }
        exchange.getResponseHeaders().put(Headers.LOCATION, RedirectBuilder.redirect(exchange, exchange.getRelativePath() + "/", true));
        return;
    } else if (info.getType() == ServletPathMatch.Type.REWRITE) {
        //this can only happen if the path ends with a /
        //otherwise there would be a redirect instead
        exchange.setRelativePath(info.getRewriteLocation());
        exchange.setRequestPath(exchange.getResolvedPath() + info.getRewriteLocation());
    }

    final HttpServletResponseImpl response = new HttpServletResponseImpl(exchange, servletContext);
    final HttpServletRequestImpl request = new HttpServletRequestImpl(exchange, servletContext);
    final ServletRequestContext servletRequestContext = new ServletRequestContext(servletContext.getDeployment(), request, response, info);
    //set the max request size if applicable
    if (info.getServletChain().getManagedServlet().getMaxRequestSize() > 0) {
        exchange.setMaxEntitySize(info.getServletChain().getManagedServlet().getMaxRequestSize());
    }
    exchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext);

    exchange.startBlocking(new ServletBlockingHttpExchange(exchange));
    servletRequestContext.setServletPathMatch(info);

    Executor executor = info.getServletChain().getExecutor();
    if (executor == null) {
        executor = servletContext.getDeployment().getExecutor();
    }

    if (exchange.isInIoThread() || executor != null) {
        //either the exchange has not been dispatched yet, or we need to use a special executor
        exchange.dispatch(executor, dispatchHandler);
    } else {
        dispatchRequest(exchange, servletRequestContext, info.getServletChain(), DispatcherType.REQUEST);
    }
}
 
Example 20
Source File: PathMatchPredicate.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public boolean resolve(final HttpServerExchange value) {
    final String relativePath = value.getRelativePath();
    PathMatcher.PathMatch<Boolean> result = pathMatcher.match(relativePath);
    return Boolean.TRUE.equals(result.getValue());
}