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

The following examples show how to use io.undertow.server.HttpServerExchange#setRequestURI() . 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: 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 4
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 5
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 6
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 7
Source File: PathParameterDeserializerTest.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Test
public void test_matrix_object_exploade() {
	Schema schema = new PojoSchema();
	schema.setType(ValueType.OBJECT.name().toLowerCase());
	schema.setProperties(PROPS);
	
	Parameter parameter = new PoJoParameter(PARAM_NAME,
			ParameterType.PATH.name().toLowerCase(),
			PathParameterStyle.MATRIX.name().toLowerCase(),
			true,
			schema);
	
	HttpServerExchange exchange = new HttpServerExchange(null);
	
	exchange.addPathParam(PARAM_NAME, "");
	
	// we cannot rely on the parsing result at call in this scenario
	// so, we use requestURI which has the original request path
	exchange.setRequestURI(";role=admin;firstName=Alex");
	
	checkMap(exchange, parameter, 3);
}
 
Example 8
Source File: AccessLogCompletionListenerTest.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Test
public void getJsonObjectTest() {
    environmentVariables.set("HOSTNAME", "hostname.localenv");
    environmentVariables.set("LOGGING_TAGS", "GALEB,OTHER");

    AccessLogCompletionListener accessLogCompletionListener = new AccessLogCompletionListener();

    HttpServerExchange httpServerExchange = new HttpServerExchange(Mockito.mock(ServerConnection.class), getRequestHeaders(), null, 0);
    httpServerExchange.setSourceAddress(new InetSocketAddress("1.2.3.4", 44444));
    httpServerExchange.setRequestMethod(HttpString.tryFromString("GET"));
    httpServerExchange.setRequestURI("/test");
    httpServerExchange.setProtocol(HttpString.tryFromString("HTTP"));
    httpServerExchange.setStatusCode(200);
    Connectors.setRequestStartTime(httpServerExchange);

    JsonObject jsonObject = accessLogCompletionListener.getJsonObject(httpServerExchange);

    Assert.assertEquals("1", jsonObject.getAsJsonPrimitive("@version").getAsString());
    Assert.assertEquals("hostname.localenv", jsonObject.getAsJsonPrimitive("host").getAsString());
    Assert.assertEquals(AccessLogCompletionListener.SHORT_MESSAGE, jsonObject.getAsJsonPrimitive("short_message").getAsString());
    Assert.assertEquals("vhost.host.virtual", jsonObject.getAsJsonPrimitive("vhost").getAsString());
    Assert.assertEquals("GALEB,OTHER,ACCESS", jsonObject.getAsJsonPrimitive("_tags").getAsString());
    Assert.assertEquals("1.2.3.4", jsonObject.getAsJsonPrimitive("remote_addr").getAsString());
    Assert.assertEquals("GET", jsonObject.getAsJsonPrimitive("request_method").getAsString());
    Assert.assertEquals("/test", jsonObject.getAsJsonPrimitive("request_uri").getAsString());
    Assert.assertEquals("HTTP", jsonObject.getAsJsonPrimitive("server_protocol").getAsString());
    Assert.assertEquals("-", jsonObject.getAsJsonPrimitive("http_referer").getAsString());
    Assert.assertEquals("-", jsonObject.getAsJsonPrimitive("http_x_mobile_group").getAsString());
    Assert.assertEquals("600", jsonObject.getAsJsonPrimitive("status").getAsString());
    Assert.assertNotNull(jsonObject.getAsJsonPrimitive("body_bytes_sent").getAsString());
    Assert.assertNotNull(jsonObject.getAsJsonPrimitive("request_time").getAsString());
    Assert.assertEquals("UNKNOWN_TARGET", jsonObject.getAsJsonPrimitive("upstream_addr").getAsString());
    Assert.assertEquals("200", jsonObject.getAsJsonPrimitive("upstream_status").getAsString());
    Assert.assertEquals("-", jsonObject.getAsJsonPrimitive("upstream_response_length").getAsString());
    Assert.assertEquals("-", jsonObject.getAsJsonPrimitive("http_user_agent").getAsString());
    Assert.assertEquals("-", jsonObject.getAsJsonPrimitive("request_id_final").getAsString());
    Assert.assertEquals("-", jsonObject.getAsJsonPrimitive("http_x_forwarded_for").getAsString());
}
 
Example 9
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 10
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 11
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 12
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 13
Source File: HttpRequestParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
final void handlePathParameters(ByteBuffer buffer, ParseState state, HttpServerExchange exchange) throws BadRequestException {
    StringBuilder stringBuilder = state.stringBuilder;
    int queryParamPos = state.pos;
    int mapCount = state.mapCount;
    boolean urlDecodeRequired = state.urlDecodeRequired;
    String nextQueryParam = state.nextQueryParam;

    //so this is a bit funky, because it not only deals with parsing, but
    //also deals with URL decoding the query parameters as well, while also
    //maintaining a non-decoded version to use as the query string
    //In most cases these string will be the same, and as we do not want to
    //build up two separate strings we don't use encodedStringBuilder unless
    //we encounter an encoded character

    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' || next == '?') {
            if (nextQueryParam == null) {
                if (queryParamPos != stringBuilder.length()) {
                    exchange.addPathParam(decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true), "");
                }
            } else {
                exchange.addPathParam(nextQueryParam, decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true));
            }
            exchange.setRequestURI(exchange.getRequestURI() + ';' + stringBuilder.toString(), state.parseState > HOST_DONE);
            state.stringBuilder.setLength(0);
            state.pos = 0;
            state.nextQueryParam = null;
            state.mapCount = 0;
            state.urlDecodeRequired = false;
            if (next == '?') {
                state.state = ParseState.QUERY_PARAMETERS;
                handleQueryParameters(buffer, state, exchange);
            } else {
                state.state = ParseState.VERSION;
            }
            return;
        } else if (next == '\r' || next == '\n') {
            throw UndertowMessages.MESSAGES.failedToParsePath();
        } else {
            if (decode && (next == '+' || next == '%' || next > 127)) {
                urlDecodeRequired = true;
            }
            if (next == '=' && nextQueryParam == null) {
                nextQueryParam = decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true);
                urlDecodeRequired = false;
                queryParamPos = stringBuilder.length() + 1;
            } else if (next == '&' && nextQueryParam == null) {
                if (++mapCount >= maxParameters) {
                    throw UndertowMessages.MESSAGES.tooManyQueryParameters(maxParameters);
                }
                exchange.addPathParam(decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true), "");
                urlDecodeRequired = false;
                queryParamPos = stringBuilder.length() + 1;
            } else if (next == '&') {
                if (++mapCount >= maxParameters) {
                    throw UndertowMessages.MESSAGES.tooManyQueryParameters(maxParameters);
                }

                exchange.addPathParam(nextQueryParam, decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true));
                urlDecodeRequired = false;
                queryParamPos = stringBuilder.length() + 1;
                nextQueryParam = null;
            }
            stringBuilder.append(next);

        }

    }
    state.pos = queryParamPos;
    state.nextQueryParam = nextQueryParam;
    state.mapCount = mapCount;
    state.urlDecodeRequired = urlDecodeRequired;
}
 
Example 14
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);
    }
}