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() . These examples are extracted from open source projects. 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
@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
@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 Project: Velocity   File: SimpleHttpResponseCollector.java    License: 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 Project: timely   File: WsRelayHandler.java    License: 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 5
@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 Project: blueflood   File: Tracker.java    License: 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 7
public StatusMessageException(HttpResponseStatus status, String errorMessage) {
    super(errorMessage);
    this.errorCode = status.code();
}
 
Example 8
public StatusMessageException(HttpResponseStatus status) {
    super(status.reasonPhrase());
    this.errorCode = status.code();
}
 
Example 9
Source Project: serve   File: NettyUtils.java    License: 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 10
Source Project: serve   File: NettyUtils.java    License: 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 11
Source Project: arcusplatform   File: HttpException.java    License: Apache License 2.0 4 votes vote down vote up
public HttpException(HttpResponseStatus status) {
	this(status, "Http Error " + status.code() + ": " + status.reasonPhrase(), null);
}
 
Example 12
Source Project: arcusplatform   File: HttpException.java    License: 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 13
Source Project: arcusplatform   File: HttpException.java    License: 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 14
Source Project: multi-model-server   File: NettyUtils.java    License: 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 15
Source Project: multi-model-server   File: NettyUtils.java    License: 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 16
Source Project: mesos-rxjava   File: MesosClient.java    License: 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 17
Source Project: brave   File: TracingHttpServerHandler.java    License: 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 18
Source Project: glowroot   File: JsonService.java    License: Apache License 2.0 4 votes vote down vote up
JsonServiceException(HttpResponseStatus status, Throwable cause) {
    super("", cause);
    this.statusCode = status.code();
}
 
Example 19
Source Project: glowroot   File: JsonService.java    License: Apache License 2.0 4 votes vote down vote up
JsonServiceException(HttpResponseStatus status, String message) {
    super(message);
    this.statusCode = status.code();
}
 
Example 20
Source Project: glowroot   File: JsonService.java    License: Apache License 2.0 4 votes vote down vote up
JsonServiceException(HttpResponseStatus status) {
    super();
    this.statusCode = status.code();
}