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

The following examples show how to use io.undertow.server.HttpServerExchange#getRequestURI() . 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: SinglePortConfidentialityHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
protected URI getRedirectURI(HttpServerExchange exchange, int port) throws URISyntaxException {
    String host = exchange.getHostName();

    String queryString = exchange.getQueryString();
    String uri = exchange.getRequestURI();
    if(exchange.isHostIncludedInRequestURI()) {
        int slashCount = 0;
        for(int i = 0; i < uri.length(); ++i) {
            if(uri.charAt(i) == '/') {
                slashCount++;
                if(slashCount == 3) {
                    uri = uri.substring(i);
                    break;
                }
            }
        }
    }
    return new URI("https", null, host, port, uri,
            queryString == null || queryString.length() == 0 ? null : queryString, null);
}
 
Example 2
Source File: RequestTimeLogger.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) {
    try {
        long end = System.currentTimeMillis();
        long duration = end - start;
        if (duration > this.timeThreshold) {
            String method = exchange.getRequestMethod().toString();
            String query = exchange.getQueryString();
            String request_url = exchange.getRequestURI() + (query.isEmpty() ? "" : ("?" + query));
            HeaderMap headers = exchange.getRequestHeaders();
            if (headers.contains(tenantHeader)) {
                String tenantId = headers.get(tenantHeader, 0);
                log.warnf("Request %s %s took: %d ms, exceeds %d ms threshold, tenant-id: %s",
                        method, request_url, duration, timeThreshold, tenantId);
            } else {
                log.warnf("Request %s %s took: %d ms, exceeds %d ms threshold, no tenant",
                        method, request_url, duration, timeThreshold);
            }

        }
    } finally {
        if (nextListener != null) {
            nextListener.proceed();
        }
    }
}
 
Example 3
Source File: SinglePortConfidentialityHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected URI getRedirectURI(HttpServerExchange exchange, int port) throws URISyntaxException {
    String host = exchange.getHostName();

    String queryString = exchange.getQueryString();
    String uri = exchange.getRequestURI();
    if(exchange.isHostIncludedInRequestURI()) {
        int slashCount = 0;
        for(int i = 0; i < uri.length(); ++i) {
            if(uri.charAt(i) == '/') {
                slashCount++;
                if(slashCount == 3) {
                    uri = uri.substring(i);
                    break;
                }
            }
        }
    }
    return new URI("https", null, host, port, uri,
            queryString == null || queryString.length() == 0 ? null : queryString, null);
}
 
Example 4
Source File: ValidatorHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    OpenApiOperation openApiOperation = null;
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    if(auditInfo != null) {
        openApiOperation = (OpenApiOperation)auditInfo.get(Constants.OPENAPI_OPERATION_STRING);
    }
    if(openApiOperation == null) {
        setExchangeStatus(exchange, STATUS_MISSING_OPENAPI_OPERATION);
        return;
    }
    Status status = requestValidator.validateRequest(requestPath, exchange, openApiOperation);
    if(status != null) {
        setExchangeStatus(exchange, status);
        if(config.logError) logger.error("ValidationError:" + status.toString());
        return;
    }

    if(config.validateResponse) {
        validateResponse(exchange, openApiOperation);
    }
    Handler.next(exchange, next);
}
 
Example 5
Source File: ValidatorHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    SwaggerOperation swaggerOperation = null;
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    if(auditInfo != null) {
        swaggerOperation = (SwaggerOperation)auditInfo.get(Constants.SWAGGER_OPERATION_STRING);
    }
    if(swaggerOperation == null) {
        setExchangeStatus(exchange, STATUS_MISSING_SWAGGER_OPERATION);
        return;
    }

    Status status = requestValidator.validateRequest(requestPath, exchange, swaggerOperation);
    if(status != null) {
        exchange.setStatusCode(status.getStatusCode());
        status.setDescription(status.getDescription().replaceAll("\\\\", "\\\\\\\\"));
        exchange.getResponseSender().send(status.toString());
        if(config.isLogError()) logger.error("ValidationError:" + status.toString());
        return;
    }
    Handler.next(exchange, next);
}
 
Example 6
Source File: StuckThreadDetectionHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    // Save the thread/runnable
    // Keeping a reference to the thread object here does not prevent
    // GC'ing, as the reference is removed from the Map in the finally clause

    Long key = Thread.currentThread().getId();
    MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(), exchange.getRequestURI() + exchange.getQueryString());
    activeThreads.put(key, monitoredThread);
    if (timerKey == null) {
        synchronized (this) {
            if (timerKey == null) {
                timerKey = exchange.getIoThread().schedule(new StuckThreadTask(exchange.getIoThread()), 1, TimeUnit.SECONDS);
            }
        }
    }

    try {
        next.handleRequest(exchange);
    } finally {
        activeThreads.remove(key);
        if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) {
            completedStuckThreadsQueue.add(
                    new CompletedStuckThread(monitoredThread.getThread(),
                            monitoredThread.getActiveTimeInMillis()));
        }
    }
}
 
Example 7
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 8
Source File: RequestIDHandler.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (!"".equals(requestIdHeader.toString()) && !exchange.getRequestHeaders().contains(requestIdHeader)) {
        exchange.getRequestHeaders().add(requestIdHeader, UUID.randomUUID().toString());
    }
    if (next != null) {
        next.handleRequest(exchange);
    } else {
        if (exchange.getRequestURI() != null) ResponseCodeOnError.PROXY_HANDLER_NULL.getHandler().handleRequest(exchange);
    }
}
 
Example 9
Source File: StuckThreadDetectionHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    // Save the thread/runnable
    // Keeping a reference to the thread object here does not prevent
    // GC'ing, as the reference is removed from the Map in the finally clause

    Long key = Thread.currentThread().getId();
    MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(), exchange.getRequestURI() + exchange.getQueryString());
    activeThreads.put(key, monitoredThread);
    if(timerKey == null) {
        synchronized (this) {
            if(timerKey == null) {
                timerKey = exchange.getIoThread().executeAfter(stuckThreadTask, 1, TimeUnit.SECONDS);
            }
        }
    }

    try {
        next.handleRequest(exchange);
    } finally {
        activeThreads.remove(key);
        if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) {
            completedStuckThreadsQueue.add(
                    new CompletedStuckThread(monitoredThread.getThread(),
                        monitoredThread.getActiveTimeInMillis()));
        }
    }
}
 
Example 10
Source File: SwaggerHandler.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {

    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    final Optional<NormalisedPath> maybeApiPath = SwaggerHelper.findMatchingApiPath(requestPath);
    if (!maybeApiPath.isPresent()) {
        setExchangeStatus(exchange, STATUS_INVALID_REQUEST_PATH, requestPath.normalised());
        return;
    }

    final NormalisedPath swaggerPathString = maybeApiPath.get();
    final Path swaggerPath = SwaggerHelper.swagger.getPath(swaggerPathString.original());

    final HttpMethod httpMethod = HttpMethod.valueOf(exchange.getRequestMethod().toString());
    final Operation operation = swaggerPath.getOperationMap().get(httpMethod);

    if (operation == null) {
        setExchangeStatus(exchange, STATUS_METHOD_NOT_ALLOWED);
        return;
    }

    // This handler can identify the swaggerOperation and endpoint only. Other info will be added by JwtVerifyHandler.
    final SwaggerOperation swaggerOperation = new SwaggerOperation(swaggerPathString, swaggerPath, httpMethod, operation);
    String endpoint = swaggerPathString.normalised() + "@" + httpMethod.toString().toLowerCase();
    Map<String, Object> auditInfo = new HashMap<>();
    auditInfo.put(Constants.ENDPOINT_STRING, endpoint);
    auditInfo.put(Constants.SWAGGER_OPERATION_STRING, swaggerOperation);
    exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo);

    Handler.next(exchange, next);
}
 
Example 11
Source File: OpenApiHandler.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath);
    if (!maybeApiPath.isPresent()) {
        setExchangeStatus(exchange, STATUS_INVALID_REQUEST_PATH, requestPath.normalised());
        return;
    }

    final NormalisedPath openApiPathString = maybeApiPath.get();
    final Path path = OpenApiHelper.openApi3.getPath(openApiPathString.original());

    final String httpMethod = exchange.getRequestMethod().toString().toLowerCase();
    final Operation operation = path.getOperation(httpMethod);

    if (operation == null) {
        setExchangeStatus(exchange, STATUS_METHOD_NOT_ALLOWED);
        return;
    }

    // This handler can identify the openApiOperation and endpoint only. Other info will be added by JwtVerifyHandler.
    final OpenApiOperation openApiOperation = new OpenApiOperation(openApiPathString, path, httpMethod, operation);
    
    try {
    	ParameterDeserializer.deserialize(exchange, openApiOperation);
    }catch (Throwable t) {// do not crash the handler
    	logger.error(t.getMessage(), t);
    }
    
    String endpoint = openApiPathString.normalised() + "@" + httpMethod.toString().toLowerCase();
    Map<String, Object> auditInfo = new HashMap<>();
    auditInfo.put(Constants.ENDPOINT_STRING, endpoint);
    auditInfo.put(Constants.OPENAPI_OPERATION_STRING, openApiOperation);
    exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo);

    Handler.next(exchange, next);
}
 
Example 12
Source File: HttpServerExchangeAdaptor.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Override
public String getRpcName(HttpServerExchange request) {
    return request.getRequestURI();
}
 
Example 13
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 14
Source File: PathParameterDeserializer.java    From light-rest-4j with Apache License 2.0 4 votes vote down vote up
@Override
public Object deserialize(HttpServerExchange exchange, Parameter parameter, ValueType valueType,
		boolean exploade) {
	Collection<String> values = exchange.getPathParameters().get(parameter.getName());
	String delimiter = exploade?Delimiters.SEMICOLON:Delimiters.COMMA;
	String start = String.format("%s%s=", Delimiters.SEMICOLON, parameter.getName());
	
	if (ValueType.PRIMITIVE == valueType) {
		StringBuilder builder = new StringBuilder();
		values.forEach(v->builder.append(trimStart(v, start)));
		return builder.toString();
	}else if (ValueType.ARRAY == valueType) {
		List<String> valueList = new ArrayList<>();
		
		if (!exploade) {
			values.forEach(v->valueList.addAll(asList(trimStart(v, start), delimiter)));
		}else {
			String prefix = String.format("%s=", parameter.getName());
			values.forEach(v->valueList.addAll(asList(replace(trimStart(v, Delimiters.SEMICOLON), prefix,StringUtils.EMPTY), delimiter)));
		}
		
		if (StringUtils.isBlank(valueList.get(valueList.size()-1))) {
			// this is a undertow-specific trick.
			// undertow parses matrix style path parameters and removes path parameters from request path
			// as a result, a space is added by com.networknt.handler.Handler.start()
			
			valueList.remove(valueList.size()-1);
		}
		
		return valueList;			
	}else if (ValueType.OBJECT == valueType) {
		Map<String, String> valueMap = new HashMap<>();
		
		if (!exploade) {
			values.forEach(v->valueMap.putAll(asMap(v, delimiter)));
		}else {
			Schema schema = parameter.getSchema();
			String requestURI = exchange.getRequestURI();
			
			schema.getProperties().keySet().forEach(k->valueMap.put(k, getValue(k, requestURI)));
		}
		
		return valueMap;
	}
	
	return null;
}
 
Example 15
Source File: RequestURLAttribute.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.getRequestURI();
}
 
Example 16
Source File: AccessLogCompletionListener.java    From galeb with Apache License 2.0 4 votes vote down vote up
public JsonObject getJsonObject(HttpServerExchange exchange) {
    final String remoteAddr = remoteIp().readAttribute(exchange);
    final String host = localServerName().readAttribute(exchange);
    final String requestElements[] = requestList().readAttribute(exchange).split(" ");
    final String method = exchange.getRequestMethod().toString();
    final String requestUri = exchange.getRequestURI();
    final String proto = exchange.getProtocol().toString();
    final String httpReferer = requestElements.length > 3 ? requestElements[3] : null;
    final String xMobileGroup = requestElements.length > 4 ? requestElements[4] : null;
    final int originalStatusCode = Integer.parseInt(responseCode().readAttribute(exchange));
    final long responseBytesSent = exchange.getResponseBytesSent();
    final String bytesSent = Long.toString(responseBytesSent);
    final String bytesSentOrDash = responseBytesSent == 0L ? "-" : bytesSent;
    final Integer responseTime = Math.round(Float.parseFloat(responseTimeAttribute.readAttribute(exchange)));
    final String realDestAttached = exchange.getAttachment(HostSelector.REAL_DEST);
    final String realDest = realDestAttached != null ? realDestAttached : extractXGalebErrorHeader(exchange.getResponseHeaders());
    final String userAgent = requestHeader(Headers.USER_AGENT).readAttribute(exchange);
    final String requestId = !"".equals(REQUESTID_HEADER) ? requestHeader(RequestIDHandler.requestIdHeader()).readAttribute(exchange) : null;
    final String xForwardedFor = requestHeader(Headers.X_FORWARDED_FOR).readAttribute(exchange);

    final int fakeStatusCode = getFakeStatusCode(realDestAttached, originalStatusCode, responseBytesSent, responseTime, MAX_REQUEST_TIME);
    final int statusCode = fakeStatusCode != ProcessorLocalStatusCode.NOT_MODIFIED ? fakeStatusCode : originalStatusCode;

    JsonObject json = new JsonObject();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX"); // ISO-8601
    json.addProperty("@timestamp", dateFormat.format(new Date()));
    json.addProperty("@version", "1");
    json.addProperty("host", SystemEnv.HOSTNAME.getValue());
    json.addProperty("short_message", SHORT_MESSAGE);
    json.addProperty("vhost", host);
    json.addProperty("_tags", SystemEnv.LOGGING_TAGS.getValue() + ",ACCESS");
    json.addProperty("remote_addr", remoteAddr);
    json.addProperty("request_method", method);
    json.addProperty("request_uri", requestUri);
    json.addProperty("server_protocol", proto);
    json.addProperty("http_referer", (httpReferer != null ? httpReferer : "-"));
    json.addProperty("http_x_mobile_group", (xMobileGroup != null ? xMobileGroup : "-"));
    json.addProperty("status", Integer.toString(statusCode));
    json.addProperty("body_bytes_sent", bytesSent);
    json.addProperty("request_time", Integer.toString(responseTime));
    json.addProperty("upstream_addr", realDest);
    json.addProperty("upstream_status", Integer.toString(originalStatusCode));
    json.addProperty("upstream_response_length", bytesSentOrDash);
    json.addProperty("http_user_agent", (userAgent != null ? userAgent : "-"));
    json.addProperty("request_id_final",(requestId != null ? requestId : "-"));
    json.addProperty("http_x_forwarded_for", (xForwardedFor != null ? xForwardedFor : "-"));
    return json;
}
 
Example 17
Source File: EventBusToServerSentEvents.java    From syndesis with Apache License 2.0 4 votes vote down vote up
protected boolean reservationCheck(HttpServerExchange exchange) {
    HeaderMap requestHeaders = exchange.getRequestHeaders();
    String origin = requestHeaders.getFirst(CorsHeaders.ORIGIN);
    if (cors.getAllowedOrigins().contains("*") || cors.getAllowedOrigins().contains(origin)) {
        HeaderMap responseHeaders = exchange.getResponseHeaders();
        responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), origin);

        String value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_HEADERS), value);
        }

        value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS), value);
        }

        value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_METHODS), value);
        }
    }

    String uri = exchange.getRequestURI();
    if (uri.indexOf(path + "/") != 0) {
        exchange.setStatusCode(404);
        return false;
    }

    final String subscriptionId = uri.substring(path.length() + 1);
    if (subscriptionId.isEmpty()) {
        exchange.setStatusCode(404);
        return false;
    }

    EventReservationsHandler.Reservation reservation = eventReservationsHandler.existsReservation(subscriptionId);
    if (reservation == null) {
        exchange.setStatusCode(404);
        return false;
    }
    return true;
}
 
Example 18
Source File: RequestURLAttribute.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    return exchange.getRequestURI();
}