Java Code Examples for io.netty.handler.codec.http.HttpResponseStatus#code()

The following examples show how to use io.netty.handler.codec.http.HttpResponseStatus#code() . 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: BrpcHttpResponseEncoder.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmpty) {
    if (isAlwaysEmpty) {
        HttpResponseStatus status = msg.status();
        if (status.codeClass() == HttpStatusClass.INFORMATIONAL
                || status.code() == HttpResponseStatus.NO_CONTENT.code()) {

            // Stripping Content-Length:
            // See https://tools.ietf.org/html/rfc7230#section-3.3.2
            msg.headers().remove(HttpHeaderNames.CONTENT_LENGTH);

            // Stripping Transfer-Encoding:
            // See https://tools.ietf.org/html/rfc7230#section-3.3.1
            msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
        } else if (status.code() == HttpResponseStatus.RESET_CONTENT.code()) {

            // Stripping Transfer-Encoding:
            msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);

            // Set Content-Length: 0
            // https://httpstatuses.com/205
            msg.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        }
    }
}
 
Example 2
Source File: BrpcHttpResponseEncoder.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isContentAlwaysEmpty(HttpResponse msg) {
    // Correctly handle special cases as stated in:
    // https://tools.ietf.org/html/rfc7230#section-3.3.3
    HttpResponseStatus status = msg.status();

    if (status.codeClass() == HttpStatusClass.INFORMATIONAL) {

        if (status.code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
            // We need special handling for WebSockets version 00 as it will include an body.
            // Fortunally this version should not really be used in the wild very often.
            // See https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00#section-1.2
            return msg.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_VERSION);
        }
        return true;
    }
    return status.code() == HttpResponseStatus.NO_CONTENT.code()
            || status.code() == HttpResponseStatus.NOT_MODIFIED.code()
            || status.code() == HttpResponseStatus.RESET_CONTENT.code();
}
 
Example 3
Source File: SimpleHttpResponseCollector.java    From Velocity with MIT License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  try {
    if (msg instanceof HttpResponse) {
      HttpResponse response = (HttpResponse) msg;
      HttpResponseStatus status = response.status();
      this.httpCode = status.code();
    }

    if (msg instanceof HttpContent) {
      buffer.append(((HttpContent) msg).content().toString(StandardCharsets.UTF_8));

      if (msg instanceof LastHttpContent) {
        ctx.close();
        reply.complete(new SimpleHttpResponse(httpCode, buffer.toString()));
      }
    }
  } finally {
    ReferenceCountUtil.release(msg);
  }
}
 
Example 4
Source File: Tracker.java    From blueflood with Apache License 2.0 5 votes vote down vote up
public void trackResponse(HttpRequest request, FullHttpResponse response) {
    // check if tenantId is being tracked by JMX TenantTrackerMBean and log the response if it is
    // HttpRequest is needed for original request uri and tenantId
    if (request == null) return;
    if (response == null) return;

    String tenantId = findTid( request.getUri() );
    if (isTracking(tenantId)) {
        HttpResponseStatus status = response.getStatus();
        String messageBody = response.content().toString(Constants.DEFAULT_CHARSET);

        // get parameters
        String queryParams = getQueryParameters(request);

        // get headers
        String headers = "";
        for (String headerName : response.headers().names()) {
            headers += "\n" + headerName + "\t" + response.headers().get(headerName);
        }

        // get response content
        String responseContent = "";
        if ((messageBody != null) && (!messageBody.isEmpty())) {
            responseContent = "\nRESPONSE_CONTENT:\n" + messageBody;
        }

        String logMessage = "[TRACKER] " +
                "Response for tenantId " + tenantId + " " + request.getMethod() + " request " + request.getUri() + queryParams +
                "\nRESPONSE_STATUS: " + status.code() +
                "\nRESPONSE HEADERS: " + headers +
                responseContent;

        log.info(logMessage);
    }

}
 
Example 5
Source File: RiposteWingtipsNettyClientTagAdapter.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Integer getResponseHttpStatus(@Nullable HttpResponse response) {
    if (response == null) {
        return null;
    }

    HttpResponseStatus statusObj = response.status();
    if (statusObj == null) {
        return null;
    }

    return statusObj.code();
}
 
Example 6
Source File: WsRelayHandler.java    From timely with Apache License 2.0 5 votes vote down vote up
static public void sendErrorResponse(ChannelHandlerContext ctx, HttpResponseStatus status, Exception ex) {

        try {
            TimelyException te = new TimelyException(status.code(), ex.getMessage(), ex.getMessage());
            String json = mapper.writeValueAsString(te);
            ctx.writeAndFlush(new TextWebSocketFrame(json));
        } catch (JsonProcessingException e) {
            LOG.error("Error serializing exception");
        }
    }
 
Example 7
Source File: NettyUtils.java    From multi-model-server with Apache License 2.0 4 votes vote down vote up
public static void sendError(
        ChannelHandlerContext ctx, HttpResponseStatus status, Throwable t) {
    ErrorResponse error =
            new ErrorResponse(status.code(), t.getClass().getSimpleName(), t.getMessage());
    sendJsonResponse(ctx, error, status);
}
 
Example 8
Source File: JsonService.java    From glowroot with Apache License 2.0 4 votes vote down vote up
JsonServiceException(HttpResponseStatus status) {
    super();
    this.statusCode = status.code();
}
 
Example 9
Source File: JsonService.java    From glowroot with Apache License 2.0 4 votes vote down vote up
JsonServiceException(HttpResponseStatus status, String message) {
    super(message);
    this.statusCode = status.code();
}
 
Example 10
Source File: JsonService.java    From glowroot with Apache License 2.0 4 votes vote down vote up
JsonServiceException(HttpResponseStatus status, Throwable cause) {
    super("", cause);
    this.statusCode = status.code();
}
 
Example 11
Source File: TracingHttpServerHandler.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public int statusCode() {
  HttpResponseStatus status = delegate.status();
  return status != null ? status.code() : 0;
}
 
Example 12
Source File: MesosClient.java    From mesos-rxjava with Apache License 2.0 4 votes vote down vote up
@NotNull
// @VisibleForTesting
static <Send> Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> verifyResponseOk(
    @NotNull final Send subscription,
    @NotNull final AtomicReference<String> mesosStreamId,
    @NotNull final String receiveMediaType
) {
    return resp -> {
        final HttpResponseStatus status = resp.getStatus();
        final int code = status.code();

        final String contentType = resp.getHeaders().get(HttpHeaderNames.CONTENT_TYPE);
        if (code == 200 && receiveMediaType.equals(contentType)) {
            if (resp.getHeaders().contains(MESOS_STREAM_ID)) {
                final String streamId = resp.getHeaders().get(MESOS_STREAM_ID);
                mesosStreamId.compareAndSet(null, streamId);
            }
            return resp.getContent();
        } else {
            final HttpResponseHeaders headers = resp.getHeaders();
            return ResponseUtils.attemptToReadErrorResponse(resp).flatMap(msg -> {
                final List<Map.Entry<String, String>> entries = headers.entries();
                final MesosClientErrorContext context = new MesosClientErrorContext(code, msg, entries);
                if (code == 200) {
                    // this means that even though we got back a 200 it's not the sort of response we were expecting
                    // For example hitting an endpoint that returns an html document instead of a document of type
                    // `receiveMediaType`
                    throw new MesosException(
                        subscription,
                        context.withMessage(
                            String.format(
                                "Response had Content-Type \"%s\" expected \"%s\"",
                                contentType,
                                receiveMediaType
                            )
                        )
                    );
                } else if (400 <= code && code < 500) {
                    throw new Mesos4xxException(subscription, context);
                } else if (500 <= code && code < 600) {
                    throw new Mesos5xxException(subscription, context);
                } else {
                    LOGGER.warn("Unhandled error: context = {}", context);
                    // This shouldn't actually ever happen, but it's here for completeness of the if-else tree
                    // that always has to result in an exception being thrown so the compiler is okay with this
                    // lambda
                    throw new IllegalStateException("Unhandled error");
                }
            });
        }
    };
}
 
Example 13
Source File: NettyUtils.java    From multi-model-server with Apache License 2.0 4 votes vote down vote up
public static void sendError(
        ChannelHandlerContext ctx, HttpResponseStatus status, Throwable t, String msg) {
    ErrorResponse error = new ErrorResponse(status.code(), t.getClass().getSimpleName(), msg);
    sendJsonResponse(ctx, error, status);
}
 
Example 14
Source File: StatusMessageException.java    From reactor-guice with Apache License 2.0 4 votes vote down vote up
public StatusMessageException(HttpResponseStatus status, String errorMessage) {
    super(errorMessage);
    this.errorCode = status.code();
}
 
Example 15
Source File: HttpException.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public HttpException(HttpResponseStatus status, String message, Throwable cause) {
	super(message, cause);
	this.statusCode = status.code();
}
 
Example 16
Source File: HttpException.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public HttpException(HttpResponseStatus status, Throwable cause) {
	this(status, "Http Error " + status.code() + ": " + status.reasonPhrase(), cause);
}
 
Example 17
Source File: HttpException.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public HttpException(HttpResponseStatus status) {
	this(status, "Http Error " + status.code() + ": " + status.reasonPhrase(), null);
}
 
Example 18
Source File: NettyUtils.java    From serve with Apache License 2.0 4 votes vote down vote up
public static void sendError(
        ChannelHandlerContext ctx, HttpResponseStatus status, Throwable t, String msg) {
    ErrorResponse error = new ErrorResponse(status.code(), t.getClass().getSimpleName(), msg);
    sendJsonResponse(ctx, error, status);
}
 
Example 19
Source File: NettyUtils.java    From serve with Apache License 2.0 4 votes vote down vote up
public static void sendError(
        ChannelHandlerContext ctx, HttpResponseStatus status, Throwable t) {
    ErrorResponse error =
            new ErrorResponse(status.code(), t.getClass().getSimpleName(), t.getMessage());
    sendJsonResponse(ctx, error, status);
}
 
Example 20
Source File: StatusMessageException.java    From reactor-guice with Apache License 2.0 4 votes vote down vote up
public StatusMessageException(HttpResponseStatus status) {
    super(status.reasonPhrase());
    this.errorCode = status.code();
}