io.netty.handler.codec.http.HttpStatusClass Java Examples

The following examples show how to use io.netty.handler.codec.http.HttpStatusClass. 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: CocWebApiInterface.java    From async-gamequery-lib with MIT License 6 votes vote down vote up
/**
 * Handle Error Events
 *
 * @param response
 * @param error
 */
@Override
protected void interceptResponse(CocWebApiResponse response, Throwable error) {
    if (error != null)
        throw new CocWebApiException(error);
    if (response.getStatus() == HttpStatusClass.CLIENT_ERROR) {
        if (response.getProcessedContent() != null) {
            CocErrorResponse err = builder().fromJson(response.getProcessedContent(), CocErrorResponse.class);
            log.error("[ERROR FROM {}]: Reason: {}, Message: {}", response.sender(), err.getReason(), err.getMessage());
        }
        switch (response.getMessage().getStatusCode()) {
            case 400:
                throw new CocIncorrectParametersException("Incorrect parameters provided for request");
            default:
                break;
        }
        //Let the base class handle the rest
        super.interceptResponse(response, error);
    }
}
 
Example #4
Source File: AbstractWebApiInterface.java    From async-gamequery-lib with MIT License 6 votes vote down vote up
/**
 * The default error handler. Override this if needed.
 *
 * @param response An instance of {@link AbstractWebApiResponse} or <code>null</code> if an exception was thrown.
 * @param error    A {@link Throwable} instance or <code>null</code> if no error has occured.
 *
 * @throws WebException thrown if a server/client error occurs
 */
protected void interceptResponse(Res response, Throwable error) {
    if (error != null)
        throw new WebException(error);
    log.debug("Handling response for {}, with status code = {}", response.getMessage().getUri(), response.getMessage().getStatusCode());
    if (response.getStatus() == HttpStatusClass.SERVER_ERROR ||
            response.getStatus() == HttpStatusClass.CLIENT_ERROR) {
        switch (response.getMessage().getStatusCode()) {
            case 400:
                throw new BadRequestException("Incorrect parameters provided for request");
            case 403:
                throw new AccessDeniedException("Access denied, either because of missing/incorrect credentials or used API token does not grant access to the requested resource.");
            case 404:
                throw new ResourceNotFoundException("Resource was not found.");
            case 429:
                throw new TooManyRequestsException("Request was throttled, because amount of requests was above the threshold defined for the used API token.");
            case 500:
                throw new UnknownWebException("An internal error occured in server");
            case 503:
                throw new ServiceUnavailableException("Service is temprorarily unavailable. Possible maintenance on-going.");
            default:
                throw new WebException("Unknown error occured on request send");
        }
    }
}
 
Example #5
Source File: DefaultHttp2ConnectionEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static boolean validateHeadersSentState(Http2Stream stream, Http2Headers headers, boolean isServer,
                                                boolean endOfStream) {
    boolean isInformational = isServer && HttpStatusClass.valueOf(headers.status()) == INFORMATIONAL;
    if ((isInformational || !endOfStream) && stream.isHeadersSent() || stream.isTrailersSent()) {
        throw new IllegalStateException("Stream " + stream.id() + " sent too many headers EOS: " + endOfStream);
    }
    return isInformational;
}
 
Example #6
Source File: InboundHttp2ToHttpAdapter.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean mustSendImmediately(FullHttpMessage msg) {
    if (msg instanceof FullHttpResponse) {
        return ((FullHttpResponse) msg).status().codeClass() == HttpStatusClass.INFORMATIONAL;
    }
    if (msg instanceof FullHttpRequest) {
        return msg.headers().contains(HttpHeaderNames.EXPECT);
    }
    return false;
}
 
Example #7
Source File: ServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testRequestTimeoutInvocation() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpPost req = new HttpPost(server.httpUri() + "/timeout");
        req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(HttpStatusClass.valueOf(res.getStatusLine().getStatusCode()))
                    .isNotEqualTo(HttpStatusClass.SUCCESS);
        }
    }
}
 
Example #8
Source File: ServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testDynamicRequestTimeoutInvocation() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpPost req = new HttpPost(server.httpUri() + "/timeout-not");
        req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(HttpStatusClass.valueOf(res.getStatusLine().getStatusCode()))
                    .isEqualTo(HttpStatusClass.SUCCESS);
        }
    }
}
 
Example #9
Source File: DefaultHttp2ConnectionDecoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,
        short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {
    Http2Stream stream = connection.stream(streamId);
    boolean allowHalfClosedRemote = false;
    if (stream == null && !connection.streamMayHaveExisted(streamId)) {
        stream = connection.remote().createStream(streamId, endOfStream);
        // Allow the state to be HALF_CLOSE_REMOTE if we're creating it in that state.
        allowHalfClosedRemote = stream.state() == HALF_CLOSED_REMOTE;
    }

    if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, "HEADERS")) {
        return;
    }

    boolean isInformational = !connection.isServer() &&
            HttpStatusClass.valueOf(headers.status()) == INFORMATIONAL;
    if ((isInformational || !endOfStream) && stream.isHeadersReceived() || stream.isTrailersReceived()) {
        throw streamError(streamId, PROTOCOL_ERROR,
                          "Stream %d received too many headers EOS: %s state: %s",
                          streamId, endOfStream, stream.state());
    }

    switch (stream.state()) {
        case RESERVED_REMOTE:
            stream.open(endOfStream);
            break;
        case OPEN:
        case HALF_CLOSED_LOCAL:
            // Allowed to receive headers in these states.
            break;
        case HALF_CLOSED_REMOTE:
            if (!allowHalfClosedRemote) {
                throw streamError(stream.id(), STREAM_CLOSED, "Stream %d in unexpected state: %s",
                        stream.id(), stream.state());
            }
            break;
        case CLOSED:
            throw streamError(stream.id(), STREAM_CLOSED, "Stream %d in unexpected state: %s",
                    stream.id(), stream.state());
        default:
            // Connection error.
            throw connectionError(PROTOCOL_ERROR, "Stream %d in unexpected state: %s", stream.id(),
                    stream.state());
    }

    stream.headersReceived(isInformational);
    encoder.flowController().updateDependencyTree(streamId, streamDependency, weight, exclusive);

    listener.onHeadersRead(ctx, streamId, headers, streamDependency, weight, exclusive, padding, endOfStream);

    // If the headers completes this stream, close it.
    if (endOfStream) {
        lifecycleManager.closeStreamRemote(stream, ctx.newSucceededFuture());
    }
}
 
Example #10
Source File: AbstractWebResponse.java    From async-gamequery-lib with MIT License 4 votes vote down vote up
public HttpStatusClass getStatus() {
    return HttpStatusClass.valueOf(this.response.getStatusCode());
}
 
Example #11
Source File: HttpTrafficHandler.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
static boolean isInformational(HttpResponse response) {
	return response.status()
	               .codeClass() == HttpStatusClass.INFORMATIONAL;
}
 
Example #12
Source File: NettyResponseChannel.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Provided a cause, returns an error response with the right status and error message.
 * @param cause the cause of the error.
 * @return a {@link FullHttpResponse} with the error message that can be sent to the client.
 */
private FullHttpResponse getErrorResponse(Throwable cause) {
  HttpResponseStatus status;
  RestServiceErrorCode restServiceErrorCode = null;
  String errReason = null;
  if (cause instanceof RestServiceException) {
    RestServiceException restServiceException = (RestServiceException) cause;
    restServiceErrorCode = restServiceException.getErrorCode();
    errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode);
    status = getHttpResponseStatus(errorResponseStatus);
    if (shouldSendFailureReason(status, restServiceException)) {
      errReason = new String(
          Utils.getRootCause(cause).getMessage().replaceAll("[\n\t\r]", " ").getBytes(StandardCharsets.US_ASCII),
          StandardCharsets.US_ASCII);
    }
  } else if (Utils.isPossibleClientTermination(cause)) {
    nettyMetrics.clientEarlyTerminationCount.inc();
    status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    errorResponseStatus = ResponseStatus.InternalServerError;
  } else {
    nettyMetrics.internalServerErrorCount.inc();
    status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    errorResponseStatus = ResponseStatus.InternalServerError;
  }
  logger.trace("Constructed error response for the client - [{} - {}]", status, errReason);
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
  response.headers().set(HttpHeaderNames.DATE, new GregorianCalendar().getTime());
  HttpUtil.setContentLength(response, 0);
  if (errReason != null) {
    response.headers().set(FAILURE_REASON_HEADER, errReason);
  }
  if (restServiceErrorCode != null && HttpStatusClass.CLIENT_ERROR.contains(status.code())) {
    response.headers().set(ERROR_CODE_HEADER, restServiceErrorCode.name());
  }
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
  // if there is an ALLOW header in the response so far constructed, copy it
  if (responseMetadata.headers().contains(HttpHeaderNames.ALLOW)) {
    response.headers().set(HttpHeaderNames.ALLOW, responseMetadata.headers().get(HttpHeaderNames.ALLOW));
  } else if (errorResponseStatus == ResponseStatus.MethodNotAllowed) {
    logger.warn("Response is {} but there is no value for {}", ResponseStatus.MethodNotAllowed,
        HttpHeaderNames.ALLOW);
  }
  copyTrackingHeaders(responseMetadata, response);
  HttpUtil.setKeepAlive(response, shouldKeepAlive(status));
  return response;
}