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

The following examples show how to use io.undertow.server.HttpServerExchange#getRequestPath() . 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: LearningPushHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String fullPath;
    String requestPath;
    if(exchange.getQueryString().isEmpty()) {
        fullPath = exchange.getRequestURL();
        requestPath = exchange.getRequestPath();
    } else{
        fullPath = exchange.getRequestURL() + "?" + exchange.getQueryString();
        requestPath = exchange.getRequestPath() + "?" + exchange.getQueryString();
    }

    doPush(exchange, fullPath);
    String referrer = exchange.getRequestHeader(HttpHeaderNames.REFERER);
    if (referrer != null) {
        String accept = exchange.getRequestHeader(HttpHeaderNames.ACCEPT);
        if (accept == null || !accept.contains("text/html")) {
            //if accept contains text/html it generally means the user has clicked
            //a link to move to a new page, and is not a resource load for the current page
            //we only care about resources for the current page

            exchange.addExchangeCompleteListener(new PushCompletionListener(fullPath, requestPath, referrer));
        }
    }
    next.handleRequest(exchange);
}
 
Example 2
Source File: DirectoryUtils.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public static void renderDirectoryListing(HttpServerExchange exchange, Resource resource) {
    String requestPath = exchange.getRequestPath();
    if (!requestPath.endsWith("/")) {
        exchange.setStatusCode(StatusCodes.FOUND);
        exchange.setResponseHeader(HttpHeaderNames.LOCATION, RedirectBuilder.redirect(exchange, exchange.getRelativePath() + "/", true));
        exchange.endExchange();
        return;
    }

    StringBuilder builder = renderDirectoryListing(requestPath, resource);

    exchange.setResponseHeader(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
    exchange.setResponseHeader(HttpHeaderNames.LAST_MODIFIED, DateUtils.toDateString(new Date()));
    exchange.setResponseHeader(HttpHeaderNames.CACHE_CONTROL, "must-revalidate");
    exchange.writeAsync(builder.toString());

    exchange.endExchange();
}
 
Example 3
Source File: LearningPushHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String fullPath;
    String requestPath;
    if(exchange.getQueryString().isEmpty()) {
        fullPath = exchange.getRequestURL();
        requestPath = exchange.getRequestPath();
    } else{
        fullPath = exchange.getRequestURL() + "?" + exchange.getQueryString();
        requestPath = exchange.getRequestPath() + "?" + exchange.getQueryString();
    }

    doPush(exchange, fullPath);
    String referrer = exchange.getRequestHeaders().getFirst(Headers.REFERER);
    if (referrer != null) {
        String accept = exchange.getRequestHeaders().getFirst(Headers.ACCEPT);
        if (accept == null || !accept.contains("text/html")) {
            //if accept contains text/html it generally means the user has clicked
            //a link to move to a new page, and is not a resource load for the current page
            //we only care about resources for the current page

            exchange.addExchangeCompleteListener(new PushCompletionListener(fullPath, requestPath, referrer));
        }
    }
    next.handleRequest(exchange);
}
 
Example 4
Source File: CachedHttpRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public CachedHttpRequest(final HttpServerExchange exchange) {
    this.path = exchange.getRequestPath();
    this.etag = ETagUtils.getETag(exchange);
    this.contentLocation = exchange.getResponseHeaders().getFirst(Headers.CONTENT_LOCATION);
    this.language = exchange.getResponseHeaders().getFirst(Headers.CONTENT_LANGUAGE);
    this.contentType = exchange.getResponseHeaders().getFirst(Headers.CONTENT_TYPE);
    String lmString = exchange.getResponseHeaders().getFirst(Headers.LAST_MODIFIED);
    if (lmString == null) {
        this.lastModified = null;
    } else {
        this.lastModified = DateUtils.parseDate(lmString);
    }
    //the content encoding can be decided dynamically, based on the current state of the request
    //as the decision to compress generally depends on size and mime type
    final AllowedContentEncodings encoding = exchange.getAttachment(AllowedContentEncodings.ATTACHMENT_KEY);
    if(encoding != null) {
        this.contentEncoding = encoding.getCurrentContentEncoding();
    } else {
        this.contentEncoding = exchange.getResponseHeaders().getFirst(Headers.CONTENT_ENCODING);
    }
    this.responseCode = exchange.getStatusCode();
}
 
Example 5
Source File: HttpErrorLoggerExtension.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void exchangeEvent(HttpServerExchange exchange, ExchangeCompletionListener.NextListener nextListener) {
    int httpStatusCode = exchange.getStatusCode();
    if (httpStatusCode >= StatusCodes.BAD_REQUEST) {
        final String path;
        final String query = exchange.getQueryString();
        if (!query.isEmpty()) {
            path = exchange.getRequestPath() + "?" + query;
        } else {
            path = exchange.getRequestPath();
        }
        HttpString method = exchange.getRequestMethod();
        log.warnf("Endpoint %s %s fails with HTTP code: %d", method, path, httpStatusCode);
    }
    nextListener.proceed();
}
 
Example 6
Source File: MetricsHttpHandler.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    String requestPath = exchange.getRequestPath();

    if (dispatched.get() != null && dispatched.get().getCount() == 1) {
        next.handleRequest(exchange);
        dispatched.set(null);
        return;
    }

    if (!requestPath.startsWith("/metrics")) {
        next.handleRequest(exchange);
        return;
    }

    String method = exchange.getRequestMethod().toString();
    HeaderValues acceptHeaders = exchange.getRequestHeaders().get(Headers.ACCEPT);
    metricsHandler.handleRequest(requestPath, method, acceptHeaders == null ? null : acceptHeaders.stream(), (status, message, headers) -> {
        exchange.setStatusCode(status);
        headers.forEach(
                (key, value) -> exchange.getResponseHeaders().put(new HttpString(key), value)
        );
        exchange.getResponseSender().send(message);
    });

}
 
Example 7
Source File: TestWebServer.java    From jandy with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(HttpServerExchange exchange, String message) {
  String str = "Receive '"+exchange.getRequestPath()+"' ["+exchange.getRequestMethod()+"] --> " + message.replace("\n", "\\n") + "\n";
  System.out.println(str);
  if (logging) {
    try {
      FileUtils.writeStringToFile(loggingFile, str, UTF_8, true);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
 
Example 8
Source File: WebSocketHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
public void handle(HttpServerExchange exchange, RequestImpl request, ActionLog actionLog) {
    String path = exchange.getRequestPath();
    String action = "ws:" + path;
    actionLog.action(action + ":open");

    ChannelHandler handler = handlers.get(path);
    if (handler == null) throw new NotFoundException("not found, path=" + path, "PATH_NOT_FOUND");

    request.session = loadSession(request, actionLog);  // load session as late as possible, so for sniffer/scan request with sessionId, it won't call redis every time even for 404/405

    var webSocketExchange = new AsyncWebSocketHttpServerExchange(exchange, channels);
    exchange.upgradeChannel((connection, httpServerExchange) -> {
        WebSocketChannel channel = handshake.createChannel(webSocketExchange, connection, webSocketExchange.getBufferPool());
        try {
            var wrapper = new ChannelImpl(channel, context, handler);
            wrapper.action = action;
            wrapper.clientIP = request.clientIP();
            wrapper.refId = actionLog.id;   // with ws, correlationId and refId are same as parent http action id
            actionLog.context("channel", wrapper.id);
            channel.setAttribute(CHANNEL_KEY, wrapper);
            channel.addCloseTask(channelCloseListener);
            context.add(wrapper);

            handler.listener.onConnect(request, wrapper);
            actionLog.context("room", wrapper.rooms.toArray()); // may join room onConnect
            channel.getReceiveSetter().set(messageListener);
            channel.resumeReceives();

            channels.add(channel);
        } catch (Throwable e) {
            // upgrade is handled by io.undertow.server.protocol.http.HttpReadListener.exchangeComplete, and it catches all exceptions during onConnect
            logManager.logError(e);
            IoUtils.safeClose(connection);
        }
    });
    handshake.handshake(webSocketExchange);
}
 
Example 9
Source File: TracingHttpHandlerConfiguration.java    From pivotal-bank-demo with Apache License 2.0 4 votes vote down vote up
@Override public String path(HttpServerExchange request) {
  return request.getRequestPath();
}
 
Example 10
Source File: JaegerHandler.java    From light-4j with Apache License 2.0 4 votes vote down vote up
/**
 * Extract the context, start and stop the span here.
 *
 * @param exchange HttpServerExchange
 * @throws Exception Exception
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // get the path and method to construct the endpoint for the operation of tracing.
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    String endpoint = null;
    if(auditInfo != null) {
        endpoint = (String)auditInfo.get(Constants.ENDPOINT_STRING);
    } else {
        endpoint = exchange.getRequestPath() + "@" + exchange.getRequestMethod();
    }

    HeaderMap headerMap = exchange.getRequestHeaders();
    final HashMap<String, String> headers = new HashMap<>();
    for(HttpString key : headerMap.getHeaderNames()) {
        headers.put(key.toString(), headerMap.getFirst(key));
    }
    TextMap carrier = new TextMapAdapter(headers);

    // start the server span.
    Tracer.SpanBuilder spanBuilder;
    try {
        SpanContext parentSpanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, carrier);
        if (parentSpanCtx == null) {
            spanBuilder = tracer.buildSpan(endpoint);
        } else {
            spanBuilder = tracer.buildSpan(endpoint).asChildOf(parentSpanCtx);
        }
    } catch (IllegalArgumentException e) {
        spanBuilder = tracer.buildSpan(endpoint);
    }
    Span rootSpan = spanBuilder
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
            .withTag(Tags.PEER_HOSTNAME.getKey(), NetUtils.getLocalAddressByDatagram())
            .withTag(Tags.PEER_PORT.getKey(), Server.config.getHttpsPort())
            .start();
    tracer.activateSpan(rootSpan);
    // This can be retrieved in the business handler to add tags and logs for tracing.
    exchange.putAttachment(ROOT_SPAN, rootSpan);
    // The client module can use this to inject tracer.
    exchange.putAttachment(EXCHANGE_TRACER, tracer);

    // add an exchange complete listener to close the Root Span for the request.
    exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
        Span span = exchange1.getAttachment(ROOT_SPAN);
        if(span != null) {
            span.finish();
        }
        nextListener.proceed();
    });

    Handler.next(exchange, next);
}