Java Code Examples for io.vertx.core.http.HttpServerResponse#closed()

The following examples show how to use io.vertx.core.http.HttpServerResponse#closed() . 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: MetricsHttpService.java    From besu with Apache License 2.0 6 votes vote down vote up
private Handler<RoutingContext> checkAllowlistHostHeader() {
  return event -> {
    final Optional<String> hostHeader = getAndValidateHostHeader(event);
    if (config.getHostsAllowlist().contains("*")
        || (hostHeader.isPresent() && hostIsInAllowlist(hostHeader.get()))) {
      event.next();
    } else {
      final HttpServerResponse response = event.response();
      if (!response.closed()) {
        response
            .setStatusCode(403)
            .putHeader("Content-Type", "application/json; charset=utf-8")
            .end("{\"message\":\"Host not authorized.\"}");
      }
    }
  };
}
 
Example 2
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
void endRequestWithError(RoutingContext rc, int status, boolean chunked, String message, boolean[] isValid) {
  if (isValid[0]) {
    HttpServerResponse response = rc.response();
    if (!response.closed()) {
      response.setChunked(chunked);
      response.setStatusCode(status);
      if (status == 422) {
        response.putHeader("Content-type", SUPPORTED_CONTENT_TYPE_JSON_DEF);
      } else {
        response.putHeader("Content-type", SUPPORTED_CONTENT_TYPE_TEXT_DEF);
      }
      if (message != null) {
        response.write(message);
      } else {
        message = "";
      }
      response.end();
    }
    LogUtil.formatStatsLogMessage(rc.request().remoteAddress().toString(), rc.request().method().toString(),
      rc.request().version().toString(), response.getStatusCode(), -1, rc.response().bytesWritten(),
      rc.request().path(), rc.request().query(), response.getStatusMessage(), null, message);
  }
  // once we are here the call is not valid
  isValid[0] = false;
}
 
Example 3
Source File: HttpStatusAccessItem.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void appendServerFormattedItem(ServerAccessLogEvent accessLogEvent, StringBuilder builder) {
  HttpServerResponse response = accessLogEvent.getRoutingContext().response();
  if (null == response) {
    builder.append(EMPTY_RESULT);
    return;
  }
  if (response.closed() && !response.ended()) {
    LOGGER.warn(
        "Response is closed before sending any data. "
            + "Please check idle connection timeout for provider is properly configured.");
    builder.append(EMPTY_RESULT);
    return;
  }
  builder.append(response.getStatusCode());
}
 
Example 4
Source File: GraphQLHttpService.java    From besu with Apache License 2.0 6 votes vote down vote up
private Handler<RoutingContext> checkWhitelistHostHeader() {
  return event -> {
    final Optional<String> hostHeader = getAndValidateHostHeader(event);
    if (config.getHostsAllowlist().contains("*")
        || (hostHeader.isPresent() && hostIsInAllowlist(hostHeader.get()))) {
      event.next();
    } else {
      final HttpServerResponse response = event.response();
      if (!response.closed()) {
        response
            .setStatusCode(403)
            .putHeader("Content-Type", "application/json; charset=utf-8")
            .end("{\"message\":\"Host not authorized.\"}");
      }
    }
  };
}
 
Example 5
Source File: HealthService.java    From besu with Apache License 2.0 6 votes vote down vote up
public void handleRequest(final RoutingContext routingContext) {
  final int statusCode;
  final String statusText;
  if (healthCheck.isHealthy(name -> routingContext.queryParams().get(name))) {
    statusCode = HEALTHY_STATUS_CODE;
    statusText = HEALTHY_STATUS_TEXT;
  } else {
    statusCode = UNHEALTHY_STATUS_CODE;
    statusText = UNHEALTHY_STATUS_TEXT;
  }
  final HttpServerResponse response = routingContext.response();
  if (!response.closed()) {
    response
        .setStatusCode(statusCode)
        .end(new JsonObject(singletonMap("status", statusText)).encodePrettily());
  }
}
 
Example 6
Source File: JsonRpcHttpService.java    From besu with Apache License 2.0 6 votes vote down vote up
private Handler<RoutingContext> checkAllowlistHostHeader() {
  return event -> {
    final Optional<String> hostHeader = getAndValidateHostHeader(event);
    if (config.getHostsAllowlist().contains("*")
        || (hostHeader.isPresent() && hostIsInAllowlist(hostHeader.get()))) {
      event.next();
    } else {
      final HttpServerResponse response = event.response();
      if (!response.closed()) {
        response
            .setStatusCode(403)
            .putHeader("Content-Type", "application/json; charset=utf-8")
            .end("{\"message\":\"Host not authorized.\"}");
      }
    }
  };
}
 
Example 7
Source File: JsonRpcHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private void handleJsonRpcError(
    final RoutingContext routingContext, final Object id, final JsonRpcError error) {
  final HttpServerResponse response = routingContext.response();
  if (!response.closed()) {
    response
        .setStatusCode(HttpResponseStatus.BAD_REQUEST.code())
        .end(Json.encode(new JsonRpcErrorResponse(id, error)));
  }
}
 
Example 8
Source File: JsonRpcHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private void handleJsonRpcUnauthorizedError(
    final RoutingContext routingContext, final Object id, final JsonRpcError error) {
  final HttpServerResponse response = routingContext.response();
  if (!response.closed()) {
    response
        .setStatusCode(HttpResponseStatus.UNAUTHORIZED.code())
        .end(Json.encode(new JsonRpcErrorResponse(id, error)));
  }
}
 
Example 9
Source File: WebSocketService.java    From besu with Apache License 2.0 5 votes vote down vote up
private Handler<RoutingContext> checkAllowlistHostHeader() {
  return event -> {
    if (hasAllowedHostnameHeader(Optional.ofNullable(event.request().host()))) {
      event.next();
    } else {
      final HttpServerResponse response = event.response();
      if (!response.closed()) {
        response
            .setStatusCode(403)
            .putHeader("Content-Type", "application/json; charset=utf-8")
            .end("{\"message\":\"Host not authorized.\"}");
      }
    }
  };
}
 
Example 10
Source File: AbstractEdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected void onFailure(RoutingContext context) {
  LOGGER.error("edge server failed.", context.failure());
  HttpServerResponse response = context.response();
  if (response.closed() || response.ended()) {
    return;
  }

  if (context.failure() instanceof InvocationException) {
    InvocationException exception = (InvocationException) context.failure();
    response.setStatusCode(exception.getStatusCode());
    response.setStatusMessage(exception.getReasonPhrase());
    if (null == exception.getErrorData()) {
      response.end();
      return;
    }

    String responseBody;
    try {
      responseBody = RestObjectMapperFactory.getRestObjectMapper().writeValueAsString(exception.getErrorData());
      response.putHeader("Content-Type", MediaType.APPLICATION_JSON);
    } catch (JsonProcessingException e) {
      responseBody = exception.getErrorData().toString();
      response.putHeader("Content-Type", MediaType.TEXT_PLAIN);
    }
    response.end(responseBody);
  } else {
    response.setStatusCode(Status.BAD_GATEWAY.getStatusCode());
    response.setStatusMessage(Status.BAD_GATEWAY.getReasonPhrase());
    response.end();
  }
}
 
Example 11
Source File: GraphQLHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private void handleGraphQLError(final RoutingContext routingContext, final Exception ex) {
  LOG.debug("Error handling GraphQL request", ex);
  final HttpServerResponse response = routingContext.response();
  if (!response.closed()) {
    response
        .setStatusCode(HttpResponseStatus.BAD_REQUEST.code())
        .end(Json.encode(new GraphQLErrorResponse(ex.getMessage())));
  }
}
 
Example 12
Source File: HttpResponse.java    From okapi with Apache License 2.0 5 votes vote down vote up
/**
 * Produce HTTP response with status code and text/plain message.
 * @param ctx routing context from where HTTP response is generated
 * @param code status code
 * @param msg message to be part of HTTP response
 */
public static void responseError(RoutingContext ctx, int code, String msg) {
  String text = (msg == null) ? "(null)" : msg;
  if (code < 200 || code >= 300) {
    logger.error("HTTP response code={} msg={}", code, text);
  }
  HttpServerResponse res = responseText(ctx, code);
  if (!res.closed()) {
    res.end(text);
  }
}
 
Example 13
Source File: HttpResponse.java    From okapi with Apache License 2.0 5 votes vote down vote up
/**
 * Produce HTTP response with status code and text/plain header.
 * @param ctx routing context from where HTTP response is generated
 * @param code status code
 * @return HTTP server response
 */
public static HttpServerResponse responseText(RoutingContext ctx, int code) {
  HttpServerResponse res = ctx.response();
  if (!res.closed()) {
    res.setStatusCode(code).putHeader("Content-Type", "text/plain");
  }
  return res;
}
 
Example 14
Source File: HttpResponse.java    From okapi with Apache License 2.0 5 votes vote down vote up
/**
 * Produce HTTP response with status code and application/json header.
 * @param ctx routing context from where HTTP response is generated
 * @param code status code
 * @return HTTP server response
 */
public static HttpServerResponse responseJson(RoutingContext ctx, int code) {
  HttpServerResponse res = ctx.response();
  if (!res.closed()) {
    res.setStatusCode(code).putHeader("Content-Type", "application/json");
  }
  return res;
}
 
Example 15
Source File: GraphQLHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private void handleEmptyRequestAndRedirect(final RoutingContext routingContext) {
  final HttpServerResponse response = routingContext.response();
  if (response.closed()) {
    return;
  }
  response.setStatusCode(HttpResponseStatus.PERMANENT_REDIRECT.code());
  response.putHeader("Location", "/graphql");
  response.end();
}
 
Example 16
Source File: WebSocketService.java    From besu with Apache License 2.0 4 votes vote down vote up
private static void handleHttpNotSupported(final RoutingContext http) {
  final HttpServerResponse response = http.response();
  if (!response.closed()) {
    response.setStatusCode(400).end("Websocket endpoint can't handle HTTP requests");
  }
}
 
Example 17
Source File: TlsEnabledHttpServerFactory.java    From besu with Apache License 2.0 4 votes vote down vote up
private static void handleRequest(final RoutingContext context) {
  final HttpServerResponse response = context.response();
  if (!response.closed()) {
    response.end("I'm up!");
  }
}
 
Example 18
Source File: HttpUtils.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Writes a Buffer to an HTTP response body.
 * <p>
 * This method also sets the <em>content-length</em> and <em>content-type</em>
 * headers of the HTTP response accordingly but does not end the response.
 * <p>
 * If the response is already ended or closed or the buffer is {@code null}, this method
 * does nothing.
 *
 * @param response The HTTP response.
 * @param buffer The Buffer to set as the response body (may be {@code null}).
 * @param contentType The type of the content. If {@code null}, a default value of
 *                    {@link #CONTENT_TYPE_OCTET_STREAM} will be used.
 * @throws NullPointerException if response is {@code null}.
 */
public static void setResponseBody(final HttpServerResponse response, final Buffer buffer, final String contentType) {

    Objects.requireNonNull(response);
    if (!response.ended() && !response.closed() && buffer != null) {
        if (contentType == null) {
            response.putHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_OCTET_STREAM);
        } else {
            response.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
        }
        response.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length()));
        response.write(buffer);
    }
}