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

The following examples show how to use io.undertow.server.HttpServerExchange#getRequestMethod() . 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: GraphHttpHandler.java    From greycat with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (exchange.getRequestMethod() == OPTIONS) {
        optionFunction(exchange);
    } else {
        exchange.dispatch(new Runnable() {
            @Override
            public void run() {
                GraphBuilder graphBuilder = server.toBufferGraphBuilder(builder);
                Graph graph = graphBuilder.build();
                graph.connect(on -> {
                    runTask(exchange, graph, new Callback<Boolean>() {
                        @Override
                        public void on(Boolean result) {
                            graph.disconnect(null);
                        }
                    });
                });
            }
        });
    }
}
 
Example 2
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 3
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 4
Source File: JDBCLogHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void logMessage(String pattern, HttpServerExchange exchange) {
    JDBCLogAttribute jdbcLogAttribute = new JDBCLogAttribute();

    if (pattern.equals("combined")) {
        jdbcLogAttribute.pattern = pattern;
    }
    jdbcLogAttribute.remoteHost = ((InetSocketAddress) exchange.getSourceAddress()).getAddress().getHostAddress();
    SecurityContext sc = exchange.getSecurityContext();
    if (sc == null || !sc.isAuthenticated()) {
        jdbcLogAttribute.user = null;
    } else {
        jdbcLogAttribute.user = sc.getAuthenticatedAccount().getPrincipal().getName();
    }
    jdbcLogAttribute.query = exchange.getQueryString();

    jdbcLogAttribute.bytes = exchange.getResponseContentLength();
    if (jdbcLogAttribute.bytes < 0) {
        jdbcLogAttribute.bytes = 0;
    }

    jdbcLogAttribute.status = exchange.getStatusCode();

    if (jdbcLogAttribute.pattern.equals("combined")) {
        jdbcLogAttribute.virtualHost = exchange.getRequestHeader(HttpHeaderNames.HOST);
        jdbcLogAttribute.method = exchange.getRequestMethod();
        jdbcLogAttribute.referer = exchange.getRequestHeader(HttpHeaderNames.REFERER);
        jdbcLogAttribute.userAgent = exchange.getRequestHeader(HttpHeaderNames.USER_AGENT);
    }

    this.pendingMessages.add(jdbcLogAttribute);
    int state = stateUpdater.get(this);
    if (state == 0) {
        if (stateUpdater.compareAndSet(this, 0, 1)) {
            this.executor = exchange.getWorker();
            this.executor.execute(this);
        }
    }
}
 
Example 5
Source File: UndertowIOHandler.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean hasBody(HttpServerExchange exchange) {
    int length = (int) exchange.getRequestContentLength();
    if (length == 0) return false;

    HttpString method = exchange.getRequestMethod();
    return Methods.POST.equals(method) || Methods.PUT.equals(method);
}
 
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: MCMPHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final HttpString method = exchange.getRequestMethod();
    if(!handlesMethod(method)) {
        next.handleRequest(exchange);
        return;
    }
    /*
     * Proxy the request that needs to be proxied and process others
     */
    // TODO maybe this should be handled outside here?
    final InetSocketAddress addr = exchange.getConnection().getLocalAddress(InetSocketAddress.class);
    if (!addr.isUnresolved() && addr.getPort() != config.getManagementSocketAddress().getPort() || !Arrays.equals(addr.getAddress().getAddress(), config.getManagementSocketAddress().getAddress().getAddress())) {
        next.handleRequest(exchange);
        return;
    }

    if(exchange.isInIoThread()) {
        //for now just do all the management stuff in a worker, as it uses blocking IO
        exchange.dispatch(this);
        return;
    }

    try {
        handleRequest(method, exchange);
    } catch (Exception e) {
        UndertowLogger.ROOT_LOGGER.failedToProcessManagementReq(e);
        exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
        exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
        final Sender sender = exchange.getResponseSender();
        sender.send("failed to process management request");
    }
}
 
Example 8
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 9
Source File: HTTPIOHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private boolean hasBody(HttpServerExchange exchange) {
    int length = (int) exchange.getRequestContentLength();
    if (length == 0) return false;  // if body is empty, skip reading

    HttpString method = exchange.getRequestMethod();
    return Methods.POST.equals(method) || Methods.PUT.equals(method) || Methods.PATCH.equals(method);
}
 
Example 10
Source File: DomainApiCheckHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean commonChecks(HttpServerExchange exchange) throws Exception {
    // AS7-2284 If we are starting or stopping the web console won't be available, tell caller the service is unavailable and to try again
    // later. If "stopping" it's either a reload, in which case trying again will eventually succeed,
    // or it's a true process stop eventually the server will have stopped.
    if (!consoleAvailability.isAvailable()) {
        exchange.getResponseHeaders().add(Headers.RETRY_AFTER, "2"); //  2 secs is just a guesstimate
        Common.SERVICE_UNAVAIABLE.handleRequest(exchange);
        return false;
    }

    /*
     * Completely disallow OPTIONS - if the browser suspects this is a cross site request just reject it.
     */
    final HttpString requestMethod = exchange.getRequestMethod();
    if (!Methods.POST.equals(requestMethod) && !Methods.GET.equals(requestMethod)) {
        if (Methods.OPTIONS.equals(requestMethod)) {
            ROOT_LOGGER.debug("Request rejected due to 'OPTIONS' method which is not supported.");
        } else {
            ROOT_LOGGER.debug("Request rejected as method not one of (GET,POST).");
        }
        Common.METHOD_NOT_ALLOWED_HANDLER.handleRequest(exchange);
        return false;
    }

    /*
     *  Origin check, if it is set the Origin header should match the Host otherwise reject the request.
     *
     *  This check is for cross site scripted GET and POST requests.
     */
    final HeaderMap headers = exchange.getRequestHeaders();
    if (headers.contains(Headers.ORIGIN)) {
       return matchOrigin(exchange, allowedOrigins) != null;
    }
    return true;
}
 
Example 11
Source File: AllowedMethodsHandler.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final HttpString requestMethod = exchange.getRequestMethod();
    if (allowedMethods.contains(requestMethod)) {
        next.handleRequest(exchange);
    } else {
        exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
        exchange.getResponseHeaders()
                .put(Headers.ALLOW, allowedMethodHeader)
                .put(Headers.CONTENT_TYPE, "text/plain; charset=utf-8");
        exchange.getResponseSender()
                .send("HTTP method " + requestMethod + " not allowed.", StandardCharsets.UTF_8);
        exchange.endExchange();
    }
}
 
Example 12
Source File: RequestMethodAttribute.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    return exchange.getRequestMethod();
}
 
Example 13
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);
}