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

The following examples show how to use io.undertow.server.HttpServerExchange#getStatusCode() . 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 exchangeEvent(HttpServerExchange exchange) {
    if (exchange.getStatusCode() == 200 && referer != null) {
        //for now only cache 200 response codes
        String lmString = exchange.getResponseHeader(HttpHeaderNames.LAST_MODIFIED);
        String etag = exchange.getResponseHeader(HttpHeaderNames.ETAG);
        long lastModified = -1;
        if(lmString != null) {
            Date dt = DateUtils.parseDate(lmString);
            if(dt != null) {
                lastModified = dt.getTime();
            }
        }
        Map<String, PushedRequest> pushes = cache.get(referer);
        if(pushes == null) {
            synchronized (cache) {
                pushes = cache.get(referer);
                if(pushes == null) {
                    cache.add(referer, pushes = Collections.synchronizedMap(new HashMap<String, PushedRequest>()));
                }
            }
        }
        pushes.put(fullPath, new PushedRequest(new HashMap<>(), requestPath, etag, lastModified));
    }
}
 
Example 2
Source File: ServletAuthenticationCallHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
/**
 * Only allow the request through if successfully authenticated or if authentication is not required.
 *
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if(exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }
    SecurityContext context = exchange.getSecurityContext();
    if (context.authenticate()) {
        if(!exchange.isComplete()) {
           next.handleRequest(exchange);
        }
    } else {
        if(exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
            ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
            src.getOriginalResponse().sendError(exchange.getStatusCode());
        } else {
            exchange.endExchange();
        }
    }
}
 
Example 3
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 4
Source File: ResponseValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the given response against the API operation.
 *
 * @param exchange The exchange to validate
 * @param swaggerOperation The API operation to validate the response against
 *
 * @return A status containing validation error
 */
public Status validateResponse(final HttpServerExchange exchange, final SwaggerOperation swaggerOperation) {
    requireNonNull(exchange, "An exchange is required");
    requireNonNull(swaggerOperation, "A swagger operation is required");

    io.swagger.models.Response swaggerResponse = swaggerOperation.getOperation().getResponses().get(Integer.toString(exchange.getStatusCode()));
    if (swaggerResponse == null) {
        swaggerResponse = swaggerOperation.getOperation().getResponses().get("default"); // try the default response
    }

    if (swaggerResponse == null) {
        return new Status("ERR11015", exchange.getStatusCode(), swaggerOperation.getPathString().original());
    }

    if (swaggerResponse.getSchema() == null) {
        return null;
    }
    String body = exchange.getOutputStream().toString();

    if (body == null || body.length() == 0) {
        return new Status("ERR11016", swaggerOperation.getMethod(), swaggerOperation.getPathString().original());
    }
    return schemaValidator.validate(body, swaggerResponse.getSchema());
}
 
Example 5
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 6
Source File: ServletAuthenticationCallHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Only allow the request through if successfully authenticated or if authentication is not required.
 *
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if(exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }
    SecurityContext context = exchange.getSecurityContext();
    if (context.authenticate()) {
        if(!exchange.isComplete()) {
           next.handleRequest(exchange);
        }
    } else {
        if(exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
            ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
            src.getOriginalResponse().sendError(exchange.getStatusCode());
        } else {
            exchange.endExchange();
        }
    }
}
 
Example 7
Source File: AllowedContentEncodings.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public StreamSinkConduit wrap(final ConduitFactory<StreamSinkConduit> factory, final HttpServerExchange exchange) {
    if (exchange.getResponseHeaders().contains(Headers.CONTENT_ENCODING)) {
        //already encoded
        return factory.create();
    }
    //if this is a zero length response we don't want to encode
    if (exchange.getResponseContentLength() != 0
            && exchange.getStatusCode() != StatusCodes.NO_CONTENT
            && exchange.getStatusCode() != StatusCodes.NOT_MODIFIED) {
        EncodingMapping encoding = getEncoding();
        if (encoding != null) {
            exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, encoding.getName());
            if (exchange.getRequestMethod().equals(Methods.HEAD)) {
                //we don't create an actual encoder for HEAD requests, but we set the header
                return factory.create();
            } else {
                return encoding.getEncoding().getResponseWrapper().wrap(factory, exchange);
            }
        }
    }
    return factory.create();
}
 
Example 8
Source File: SimpleErrorPageHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean handleDefaultResponse(final HttpServerExchange exchange) {
    if (!exchange.isResponseChannelAvailable()) {
        return false;
    }
    Set<Integer> codes = responseCodes;
    if (codes == null ? exchange.getStatusCode() >= StatusCodes.BAD_REQUEST : codes.contains(Integer.valueOf(exchange.getStatusCode()))) {
        final String errorPage = "<html><head><title>Error</title></head><body>" + exchange.getStatusCode() + " - " + StatusCodes.getReason(exchange.getStatusCode()) + "</body></html>";
        exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + errorPage.length());
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
        Sender sender = exchange.getResponseSender();
        sender.send(errorPage);
        return true;
    }
    return false;
}
 
Example 9
Source File: ConnectorsExecuteRootHandlerInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private int getStatusCode(final HttpServerExchange response) {
    try {
        return response.getStatusCode();
    } catch (Exception ignored) {
    }
    return 0;
}
 
Example 10
Source File: StatusCodeHandler.java    From StubbornJava with MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    /**
     * Call the underlying handler first since it may be setting the status code.
     * Assume there are no exceptions.  We should catch and handle them before this.
     */
    handler.handleRequest(exchange);

    int code = exchange.getStatusCode();
    Meter meter = Metrics.meter(prefix, String.valueOf(code));
    meter.mark();
}
 
Example 11
Source File: StatusCodeHandler.java    From StubbornJava with MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    /**
     * Call the underlying handler first since it may be setting the status code.
     * Assume there are no exceptions.  We should catch and handle them before this.
     */
    handler.handleRequest(exchange);

    int code = exchange.getStatusCode();
    Meter meter = Metrics.meter(prefix, String.valueOf(code));
    meter.mark();
}
 
Example 12
Source File: JDBCLogHandler.java    From lams with GNU General Public License v2.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.getConnection().getPeerAddress()).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.getRequestHeaders().getFirst(Headers.HOST);
        jdbcLogAttribute.method = exchange.getRequestMethod().toString();
        jdbcLogAttribute.referer = exchange.getRequestHeaders().getFirst(Headers.REFERER);
        jdbcLogAttribute.userAgent = exchange.getRequestHeaders().getFirst(Headers.USER_AGENT);
    }

    this.pendingMessages.add(jdbcLogAttribute);
    int state = stateUpdater.get(this);
    if (state == 0) {
        if (stateUpdater.compareAndSet(this, 0, 1)) {
            this.executor = exchange.getConnection().getWorker();
            this.executor.execute(this);
        }
    }
}
 
Example 13
Source File: LearningPushHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) {
    if (exchange.getStatusCode() == 200 && referer != null) {
        //for now only cache 200 response codes
        String lmString = exchange.getResponseHeaders().getFirst(Headers.LAST_MODIFIED);
        String etag = exchange.getResponseHeaders().getFirst(Headers.ETAG);
        long lastModified = -1;
        if(lmString != null) {
            Date dt = DateUtils.parseDate(lmString);
            if(dt != null) {
                lastModified = dt.getTime();
            }
        }
        Map<String, PushedRequest> pushes = cache.get(referer);
        if(pushes == null) {
            synchronized (cache) {
                pushes = cache.get(referer);
                if(pushes == null) {
                    cache.add(referer, pushes = Collections.synchronizedMap(new HashMap<String, PushedRequest>()));
                }
            }
        }
        pushes.put(fullPath, new PushedRequest(new HeaderMap(), requestPath, etag, lastModified));
    }

    nextListener.proceed();
}
 
Example 14
Source File: StatsdCompletionListener.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Override
public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) {
    try {
        String virtualhost = exchange.getHostName();
        virtualhost = virtualhost != null ? virtualhost : UNDEF;
        String poolName = exchange.getAttachment(POOL_NAME);
        poolName = poolName != null ? poolName : UNDEF;
        String targetUri = exchange.getAttachment(HostSelector.REAL_DEST);
        targetUri = targetUri != null ? targetUri : extractXGalebErrorHeader(exchange.getResponseHeaders());
        final boolean isTargetUnknown = targetIsUnknown(targetUri);
        final Integer statusCode = exchange.getStatusCode();
        final String method = exchange.getRequestMethod().toString();
        final Integer responseTime = getResponseTime(exchange);

        // @formatter:off
        final String key = ENV_TAG    + environmentName + "." +
                           VH_TAG     + cleanUpKey(virtualhost) + "." +
                           POOL_TAG   + cleanUpKey(poolName) + "." +
                           TARGET_TAG + cleanUpKey(targetUri);
        // @formatter:on

        sendStatusCodeCount(key, statusCode, isTargetUnknown);
        sendHttpMethodCount(key, method);
        sendResponseTime(key, responseTime, isTargetUnknown);
        if (sendOpenconnCounter) sendActiveConnCount(key, exchange.getAttachment(ClientStatisticsMarker.TARGET_CONN), isTargetUnknown);

    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    } finally {
        nextListener.proceed();
    }
}
 
Example 15
Source File: QuarkusAuthMechanism.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
    VertxHttpExchange delegate = (VertxHttpExchange) exchange.getDelegate();
    RoutingContext context = (RoutingContext) delegate.getContext();
    HttpAuthenticator authenticator = context.get(HttpAuthenticator.class.getName());
    if (authenticator == null) {
        exchange.setStatusCode(StatusCodes.UNAUTHORIZED);
        exchange.endExchange();
        return new ChallengeResult(true, exchange.getStatusCode());
    }
    authenticator.sendChallenge(context).await().indefinitely();
    exchange.endExchange();
    return new ChallengeResult(true, exchange.getStatusCode());
}
 
Example 16
Source File: SikulixServer.java    From SikuliX1 with MIT License 5 votes vote down vote up
protected static void sendResponse(HttpServerExchange exchange, int stateCode, Object responseObject) {
  exchange.setStatusCode(stateCode);
  exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
  String head = exchange.getProtocol() + " " + exchange.getStatusCode() + " " + StatusCodes.getReason(exchange.getStatusCode());
  try {
    String body = mapper.writeValueAsString(responseObject);
    exchange.getResponseSender().send(body);
    dolog("returned for <%s %s %s> from %s:\n%s\n%s",
          exchange.getRequestMethod(), exchange.getRequestURI(), exchange.getProtocol(), exchange.getSourceAddress(),
          head, body);
  } catch (JsonProcessingException ex) {
    dolog(-1, "serialize to json: Exception:\n" + ex);
    ex.printStackTrace();
  }
}
 
Example 17
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 18
Source File: SimpleErrorPageHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleDefaultResponse(final HttpServerExchange exchange) {
    if (exchange.isResponseStarted()) {
        return false;
    }
    Set<Integer> codes = responseCodes;
    if (codes == null ? exchange.getStatusCode() >= StatusCodes.BAD_REQUEST : codes.contains(Integer.valueOf(exchange.getStatusCode()))) {
        final String errorPage = "<html><head><title>Error</title></head><body>" + exchange.getStatusCode() + " - " + StatusCodes.getReason(exchange.getStatusCode()) + "</body></html>";
        exchange.setResponseHeader(HttpHeaderNames.CONTENT_LENGTH, "" + errorPage.length());
        exchange.setResponseHeader(HttpHeaderNames.CONTENT_TYPE, "text/html");
        exchange.writeAsync(errorPage);
        return true;
    }
    return false;
}
 
Example 19
Source File: TracingHttpHandlerConfiguration.java    From pivotal-bank-demo with Apache License 2.0 4 votes vote down vote up
@Override public Integer statusCode(HttpServerExchange response) {
  return response.getStatusCode();
}