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

The following examples show how to use io.undertow.server.HttpServerExchange#setRequestPath() . 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: RequestPathAttribute.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    int pos = newValue.indexOf('?');
    exchange.setResolvedPath("");
    if (pos == -1) {
        exchange.setRelativePath(newValue);
        exchange.setRequestURI(newValue);
        exchange.setRequestPath(newValue);
    } else {
        final String path = newValue.substring(0, pos);
        exchange.setRequestPath(path);
        exchange.setRelativePath(path);
        exchange.setRequestURI(newValue);

        final String newQueryString = newValue.substring(pos);
        exchange.setQueryString(newQueryString);
        exchange.getQueryParameters().putAll(QueryParameterUtils.parseQueryString(newQueryString.substring(1), QueryParameterUtils.getQueryParamEncoding(exchange)));
    }
}
 
Example 2
Source File: RequestURLAttribute.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    int pos = newValue.indexOf('?');
    if (pos == -1) {
        exchange.setRelativePath(newValue);
        exchange.setRequestURI(newValue);
        exchange.setRequestPath(newValue);
        exchange.setResolvedPath("");
    } else {
        final String path = newValue.substring(0, pos);
        exchange.setRelativePath(path);
        exchange.setRequestURI(path);
        exchange.setRequestPath(path);
        exchange.setResolvedPath("");
        final String newQueryString = newValue.substring(pos);
        exchange.setQueryString(newQueryString);
        exchange.getQueryParameters().putAll(QueryParameterUtils.parseQueryString(newQueryString.substring(1), QueryParameterUtils.getQueryParamEncoding(exchange)));
    }

}
 
Example 3
Source File: URLDecodingHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    boolean decodeDone = exchange.getUndertowOptions().get(UndertowOptions.DECODE_URL, true);
    if (!decodeDone) {
        final StringBuilder sb = new StringBuilder();
        final boolean decodeSlash = exchange.getUndertowOptions().get(UndertowOptions.ALLOW_ENCODED_SLASH, false);
        exchange.setRequestPath(URLUtils.decode(exchange.getRequestPath(), charset, decodeSlash, false, sb));
        exchange.setRelativePath(URLUtils.decode(exchange.getRelativePath(), charset, decodeSlash, false, sb));
        exchange.setResolvedPath(URLUtils.decode(exchange.getResolvedPath(), charset, decodeSlash, false, sb));
        if (!exchange.getQueryString().isEmpty()) {
            final TreeMap<String, Deque<String>> newParams = new TreeMap<>();
            for (Map.Entry<String, Deque<String>> param : exchange.getQueryParameters().entrySet()) {
                final Deque<String> newVales = new ArrayDeque<>(param.getValue().size());
                for (String val : param.getValue()) {
                    newVales.add(URLUtils.decode(val, charset, true, true, sb));
                }
                newParams.put(URLUtils.decode(param.getKey(), charset, true, true, sb), newVales);
            }
            exchange.getQueryParameters().clear();
            exchange.getQueryParameters().putAll(newParams);
        }
    }
    next.handleRequest(exchange);
}
 
Example 4
Source File: RequestPathAttribute.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    int pos = newValue.indexOf('?');
    exchange.setResolvedPath("");
    if (pos == -1) {
        exchange.setRelativePath(newValue);
        exchange.setRequestURI(newValue);
        exchange.setRequestPath(newValue);
    } else {
        final String path = newValue.substring(0, pos);
        exchange.setRequestPath(path);
        exchange.setRelativePath(path);
        exchange.setRequestURI(newValue);

        final String newQueryString = newValue.substring(pos);
        exchange.setQueryString(newQueryString);
        exchange.getQueryParameters().putAll(QueryParameterUtils.parseQueryString(newQueryString.substring(1), QueryParameterUtils.getQueryParamEncoding(exchange)));
    }
}
 
Example 5
Source File: RequestURLAttribute.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    int pos = newValue.indexOf('?');
    if (pos == -1) {
        exchange.setRelativePath(newValue);
        exchange.setRequestURI(newValue);
        exchange.setRequestPath(newValue);
        exchange.setResolvedPath("");
    } else {
        final String path = newValue.substring(0, pos);
        exchange.setRelativePath(path);
        exchange.setRequestURI(path);
        exchange.setRequestPath(path);
        exchange.setResolvedPath("");
        final String newQueryString = newValue.substring(pos);
        exchange.setQueryString(newQueryString);
        exchange.getQueryParameters().putAll(QueryParameterUtils.parseQueryString(newQueryString.substring(1), QueryParameterUtils.getQueryParamEncoding(exchange)));
    }

}
 
Example 6
Source File: URLDecodingHandler.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 {
    boolean decodeDone = exchange.getConnection().getUndertowOptions().get(UndertowOptions.DECODE_URL, true);
    if (!decodeDone) {
        final StringBuilder sb = new StringBuilder();
        final boolean decodeSlash = exchange.getConnection().getUndertowOptions().get(UndertowOptions.ALLOW_ENCODED_SLASH, false);
        exchange.setRequestPath(URLUtils.decode(exchange.getRequestPath(), charset, decodeSlash, false, sb));
        exchange.setRelativePath(URLUtils.decode(exchange.getRelativePath(), charset, decodeSlash, false, sb));
        exchange.setResolvedPath(URLUtils.decode(exchange.getResolvedPath(), charset, decodeSlash, false, sb));
        if (!exchange.getQueryString().isEmpty()) {
            final TreeMap<String, Deque<String>> newParams = new TreeMap<>();
            for (Map.Entry<String, Deque<String>> param : exchange.getQueryParameters().entrySet()) {
                final Deque<String> newVales = new ArrayDeque<>(param.getValue().size());
                for (String val : param.getValue()) {
                    newVales.add(URLUtils.decode(val, charset, true, true, sb));
                }
                newParams.put(URLUtils.decode(param.getKey(), charset, true, true, sb), newVales);
            }
            exchange.getQueryParameters().clear();
            exchange.getQueryParameters().putAll(newParams);
        }
    }
    next.handleRequest(exchange);
}
 
Example 7
Source File: HttpRequestParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void beginPathParameters(ParseState state, HttpServerExchange exchange, StringBuilder stringBuilder, int parseState, int canonicalPathStart, boolean urlDecodeRequired) {
    final String path = stringBuilder.toString();
    if(parseState == SECOND_SLASH) {
        exchange.setRequestPath("/");
        exchange.setRelativePath("/");
        exchange.setRequestURI(path);
    } else if (parseState < HOST_DONE) {
        String decodedPath = decode(path, urlDecodeRequired, state, allowEncodedSlash, false);
        exchange.setRequestPath(decodedPath);
        exchange.setRelativePath(decodedPath);
        exchange.setRequestURI(path);
    } else {
        String thePath = path.substring(canonicalPathStart);
        exchange.setRequestPath(thePath);
        exchange.setRelativePath(thePath);
        exchange.setRequestURI(path, true);
    }
    state.state = ParseState.PATH_PARAMETERS;
    state.stringBuilder.setLength(0);
    state.parseState = 0;
    state.pos = 0;
    state.urlDecodeRequired = false;
}
 
Example 8
Source File: HttpRequestParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void beginQueryParameters(ByteBuffer buffer, ParseState state, HttpServerExchange exchange, StringBuilder stringBuilder, int parseState, int canonicalPathStart, boolean urlDecodeRequired) throws BadRequestException {
    final String path = stringBuilder.toString();
    if (parseState == SECOND_SLASH) {
        exchange.setRequestPath("/");
        exchange.setRelativePath("/");
        exchange.setRequestURI(path);
    } else if (parseState < HOST_DONE) {
        String decodedPath = decode(path, urlDecodeRequired, state, allowEncodedSlash, false);
        exchange.setRequestPath(decodedPath);
        exchange.setRelativePath(decodedPath);
        exchange.setRequestURI(path, false);
    } else {
        handleFullUrl(state, exchange, canonicalPathStart, urlDecodeRequired, path);
    }
    state.state = ParseState.QUERY_PARAMETERS;
    state.stringBuilder.setLength(0);
    state.parseState = 0;
    state.pos = 0;
    state.urlDecodeRequired = false;
    handleQueryParameters(buffer, state, exchange);
}
 
Example 9
Source File: RoutingHandlerInterceptorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private HttpServerExchange buildExchange() {
    HeaderMap requestHeaders = new HeaderMap();
    HeaderMap responseHeaders = new HeaderMap();
    HttpServerExchange exchange = new HttpServerExchange(serverConnection, requestHeaders, responseHeaders, 0);
    exchange.setRequestURI(uri);
    exchange.setRequestPath(uri);
    exchange.setDestinationAddress(new InetSocketAddress("localhost", 8080));
    exchange.setRequestScheme("http");
    exchange.setRequestMethod(Methods.GET);
    return exchange;
}
 
Example 10
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 11
Source File: TracingHandlerTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private HttpServerExchange buildExchange() {
    HeaderMap requestHeaders = new HeaderMap();
    HeaderMap responseHeaders = new HeaderMap();
    HttpServerExchange exchange = new HttpServerExchange(serverConnection, requestHeaders, responseHeaders, 0);
    exchange.setRequestURI(uri);
    exchange.setRequestPath(uri);
    exchange.setDestinationAddress(new InetSocketAddress("localhost", 8080));
    exchange.setRequestScheme("http");
    exchange.setRequestMethod(Methods.GET);
    return exchange;
}
 
Example 12
Source File: PathSeparatorHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    boolean handlingRequired = File.separatorChar != '/';
    if (handlingRequired) {
        exchange.setRequestPath(canonicalize(exchange.getRequestPath().replace(File.separatorChar, '/')));
        exchange.setRelativePath(canonicalize(exchange.getRelativePath().replace(File.separatorChar, '/')));
        exchange.setResolvedPath(canonicalize(exchange.getResolvedPath().replace(File.separatorChar, '/')));
    }
    next.handleRequest(exchange);
}
 
Example 13
Source File: PathSeparatorHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    boolean handlingRequired = File.separatorChar != '/';
    if (handlingRequired) {
        exchange.setRequestPath(canonicalize(exchange.getRequestPath().replace(File.separatorChar, '/')));
        exchange.setRelativePath(canonicalize(exchange.getRelativePath().replace(File.separatorChar, '/')));
        exchange.setResolvedPath(canonicalize(exchange.getResolvedPath().replace(File.separatorChar, '/')));
    }
    next.handleRequest(exchange);
}
 
Example 14
Source File: HttpRequestParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void handleFullUrl(ParseState state, HttpServerExchange exchange, int canonicalPathStart, boolean urlDecodeRequired, String path) {
    String thePath = decode(path.substring(canonicalPathStart), urlDecodeRequired, state, allowEncodedSlash, false);
    exchange.setRequestPath(thePath);
    exchange.setRelativePath(thePath);
    exchange.setRequestURI(path, true);
}
 
Example 15
Source File: HttpRequestParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses a path value
 *
 * @param buffer   The buffer
 * @param state    The current state
 * @param exchange The exchange builder
 * @return The number of bytes remaining
 */
@SuppressWarnings("unused")
final void handlePath(ByteBuffer buffer, ParseState state, HttpServerExchange exchange) throws BadRequestException {
    StringBuilder stringBuilder = state.stringBuilder;
    int parseState = state.parseState;
    int canonicalPathStart = state.pos;
    boolean urlDecodeRequired = state.urlDecodeRequired;

    while (buffer.hasRemaining()) {
        char next = (char) (buffer.get() & 0xFF);
        if(!allowUnescapedCharactersInUrl && !ALLOWED_TARGET_CHARACTER[next]) {
            throw new BadRequestException(UndertowMessages.MESSAGES.invalidCharacterInRequestTarget(next));
        }
        if (next == ' ' || next == '\t') {
            if (stringBuilder.length() != 0) {
                final String path = stringBuilder.toString();
                if(parseState == SECOND_SLASH) {
                    exchange.setRequestPath("/");
                    exchange.setRelativePath("/");
                    exchange.setRequestURI(path);
                } else if (parseState < HOST_DONE) {
                    String decodedPath = decode(path, urlDecodeRequired, state, allowEncodedSlash, false);
                    exchange.setRequestPath(decodedPath);
                    exchange.setRelativePath(decodedPath);
                    exchange.setRequestURI(path);
                } else {
                    handleFullUrl(state, exchange, canonicalPathStart, urlDecodeRequired, path);
                }
                exchange.setQueryString("");
                state.state = ParseState.VERSION;
                state.stringBuilder.setLength(0);
                state.parseState = 0;
                state.pos = 0;
                state.urlDecodeRequired = false;
                return;
            }
        } else if (next == '\r' || next == '\n') {
            throw UndertowMessages.MESSAGES.failedToParsePath();
        } else if (next == '?' && (parseState == START || parseState == HOST_DONE || parseState == IN_PATH)) {
            beginQueryParameters(buffer, state, exchange, stringBuilder, parseState, canonicalPathStart, urlDecodeRequired);
            return;
        } else if (next == ';' && (parseState == START || parseState == HOST_DONE || parseState == IN_PATH)) {
            beginPathParameters(state, exchange, stringBuilder, parseState, canonicalPathStart, urlDecodeRequired);
            handlePathParameters(buffer, state, exchange);
            return;
        } else {

            if (decode && (next == '%' || next > 127)) {
                urlDecodeRequired = true;
            } else if (next == ':' && parseState == START) {
                parseState = FIRST_COLON;
            } else if (next == '/' && parseState == FIRST_COLON) {
                parseState = FIRST_SLASH;
            } else if (next == '/' && parseState == FIRST_SLASH) {
                parseState = SECOND_SLASH;
            } else if (next == '/' && parseState == SECOND_SLASH) {
                parseState = HOST_DONE;
                canonicalPathStart = stringBuilder.length();
            } else if (parseState == FIRST_COLON || parseState == FIRST_SLASH) {
                parseState = IN_PATH;
            } else if (next == '/' && parseState != HOST_DONE) {
                parseState = IN_PATH;
            }
            stringBuilder.append(next);
        }

    }
    state.parseState = parseState;
    state.pos = canonicalPathStart;
    state.urlDecodeRequired = urlDecodeRequired;
}
 
Example 16
Source File: MultiAppProxyClient.java    From bouncr with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void getConnection(ProxyTarget target, HttpServerExchange exchange, ProxyCallback<ProxyConnection> callback, long timeout, TimeUnit timeUnit) {
    Realm realm = realmCache.matches(exchange.getRequestPath());
    if (realm == null) {
        exchange.setStatusCode(404);
        exchange.endExchange();
        return;
    }

    parseToken(exchange).ifPresent(token -> {
        Optional<HashMap<String, Object>> userCache = authenticate(token);

        userCache.ifPresent(u -> {
            Map<String, List<String>> permissionsByRealm = (Map<String, List<String>>) u.remove("permissionsByRealm");
            List<String> permissions = permissionsByRealm.get(realm.getId().toString());

            Map<String, Object> body = new HashMap<>(u);
            body.put("permissions", Optional.ofNullable(permissions).orElse(Collections.emptyList()));
            exchange.getRequestHeaders().put(HttpString.tryFromString(config.getBackendHeaderName()),
                    jwt.sign(body, jwtHeader, (byte[]) null));
        });
    });

    Application application = realmCache.getApplication(realm);
    if (connectionCache) {
        ClientConnection existing = exchange.getConnection().getAttachment(clientAttachmentKey);
        if (existing != null) {
            if (existing.isOpen()) {
                //this connection already has a client, re-use it
                String path = exchange.getRequestURI();
                if (path.startsWith(application.getVirtualPath())) {
                    String passTo = calculatePathTo(path, application);
                    exchange.setRequestPath(passTo);
                    exchange.setRequestURI(passTo);
                }
                callback.completed(exchange, new ProxyConnection(existing, "/"));
                return;
            } else {
                exchange.getConnection().removeAttachment(clientAttachmentKey);
            }
        }
    }

    try {
        URI uri = application.getUriToPass();
        LOG.debug("PASS: {}", uri);
        client.connect(new ConnectNotifier(callback, exchange),
                new URI(uri.getScheme(), /*userInfo*/null, uri.getHost(), uri.getPort(),
                        /*path*/null, /*query*/null, /*fragment*/null),
                exchange.getIoThread(),
                exchange.getConnection().getByteBufferPool(), OptionMap.EMPTY);
    } catch (URISyntaxException e) {
        throw new MisconfigurationException("bouncr.proxy.WRONG_URI", application.getUriToPass(), e);
    }
}
 
Example 17
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);
    }
}