com.linecorp.armeria.common.HttpStatusClass Java Examples

The following examples show how to use com.linecorp.armeria.common.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: StorageClient.java    From curiostack with MIT License 6 votes vote down vote up
public CompletableFuture<Void> delete(String filename) {
  String url = objectUrlPrefix + urlPathSegmentEscaper().escape(filename);
  RequestHeaders headers =
      RequestHeaders.builder(HttpMethod.DELETE, url).contentType(MediaType.JSON_UTF_8).build();
  return httpClient
      .execute(headers)
      .aggregate()
      .handle(
          (msg, t) -> {
            if (t != null) {
              throw new RuntimeException("Unexpected error deleting file.", t);
            }
            if (msg.status().codeClass().equals(HttpStatusClass.SUCCESS)) {
              return null;
            } else {
              throw new IllegalStateException(
                  "Could not delete file at " + url + ": " + msg.content().toStringUtf8());
            }
          });
}
 
Example #2
Source File: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static <T> T handleErrorResponse(AggregatedHttpResponse res) {
    final HttpStatus status = res.status();
    if (status.codeClass() != HttpStatusClass.SUCCESS) {
        final JsonNode node = toJson(res, JsonNodeType.OBJECT);
        final JsonNode exceptionNode = node.get("exception");
        final JsonNode messageNode = node.get("message");

        if (exceptionNode != null) {
            final String typeName = exceptionNode.textValue();
            if (typeName != null) {
                final Function<String, CentralDogmaException> exceptionFactory =
                        EXCEPTION_FACTORIES.get(typeName);
                if (exceptionFactory != null) {
                    throw exceptionFactory.apply(messageNode.textValue());
                }
            }
        }
    }

    throw new CentralDogmaException("unexpected response: " + res.headers() + ", " + res.contentUtf8());
}
 
Example #3
Source File: AbstractRuleBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es.
 */
public AbstractRuleBuilder onStatusClass(Iterable<HttpStatusClass> statusClasses) {
    requireNonNull(statusClasses, "statusClasses");
    checkArgument(!Iterables.isEmpty(statusClasses), "statusClasses can't be empty.");

    final Set<HttpStatusClass> statusClasses0 = Sets.immutableEnumSet(statusClasses);
    onResponseHeaders(headers -> statusClasses0.contains(headers.status().codeClass()));
    return this;
}
 
Example #4
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void buildFluently() {
    final Backoff idempotentBackoff = Backoff.fixed(100);
    final Backoff unprocessedBackoff = Backoff.fixed(200);
    final RetryRule retryRule =
            RetryRule.of(RetryRule.builder(HttpMethod.idempotentMethods())
                                  .onStatus(HttpStatus.INTERNAL_SERVER_ERROR)
                                  .onException(ClosedChannelException.class)
                                  .onStatusClass(HttpStatusClass.CLIENT_ERROR)
                                  .thenBackoff(idempotentBackoff),
                         RetryRule.builder()
                                  .onUnprocessed()
                                  .thenBackoff(unprocessedBackoff));

    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR));

    assertBackoff(retryRule.shouldRetry(ctx1, null)).isSameAs(idempotentBackoff);

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.POST, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR));
    assertBackoff(retryRule.shouldRetry(ctx2, null)).isNull();

    final ClientRequestContext ctx3 = ClientRequestContext.of(HttpRequest.of(HttpMethod.PUT, "/"));
    assertBackoff(retryRule.shouldRetry(ctx3, new ClosedChannelException())).isSameAs(idempotentBackoff);

    final ClientRequestContext ctx4 = ClientRequestContext.of(HttpRequest.of(HttpMethod.PUT, "/"));
    assertBackoff(retryRule.shouldRetry(ctx4,
                                        UnprocessedRequestException.of(new ClosedChannelException())))
            .isSameAs(unprocessedBackoff);
}
 
Example #5
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void onStatusClass() {
    final RetryRule rule = RetryRule.onStatusClass(HttpStatusClass.CLIENT_ERROR);

    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.BAD_REQUEST));
    assertBackoff(rule.shouldRetry(ctx1, null)).isSameAs(Backoff.ofDefault());

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.OK));
    assertBackoff(rule.shouldRetry(ctx2, null)).isNull();
}
 
Example #6
Source File: ArmeriaPendingResult.java    From curiostack with MIT License 5 votes vote down vote up
private T parseResponse(AggregatedHttpResponse message) throws ApiException, IOException {
  HttpStatus status = message.status();

  String contentType = message.headers().get(HttpHeaderNames.CONTENT_TYPE);
  if (contentType != null
      && contentType.startsWith("image")
      && responseClass == ImageResult.Response.class
      && status.equals(HttpStatus.OK)) {
    var result = new ImageResult(contentType, message.content().array());
    @SuppressWarnings("unchecked")
    T castResult = (T) result;
    return castResult;
  }

  final R resp;
  try {
    resp = gson.fromJson(message.contentUtf8(), responseClass);
  } catch (JsonSyntaxException e) {
    if (!status.codeClass().equals(HttpStatusClass.SUCCESS)) {
      // Some of the APIs return 200 even when the API request fails, as long as the transport
      // mechanism succeeds. In these cases, INVALID_RESPONSE, etc are handled by the Gson
      // parsing.
      throw new IOException(
          String.format("Server Error: %d %s", status.code(), status.reasonPhrase()));
    }

    // Otherwise just cough up the syntax exception.
    throw e;
  }

  if (resp.successful()) {
    return resp.getResult();
  } else {
    // TODO(choko): Retry on retryable exceptions ideally without implementing retry business
    // logic itself.
    throw resp.getError();
  }
}
 
Example #7
Source File: RetryRuleBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es for a {@link RetryRule} which will retry
 * if a class of the response status is one of the specified {@link HttpStatusClass}es.
 */
@Override
public RetryRuleBuilder onStatusClass(HttpStatusClass... statusClasses) {
    return (RetryRuleBuilder) super.onStatusClass(statusClasses);
}
 
Example #8
Source File: FileWriter.java    From curiostack with MIT License 4 votes vote down vote up
private CompletableFuture<Void> doUploadChunk(ByteBuf chunk, boolean endOfFile) {

    int length = chunk.readableBytes();
    long limit = filePosition + length;

    StringBuilder range = new StringBuilder("bytes ");
    if (length == 0) {
      range.append('*');
    } else {
      range.append(filePosition).append('-').append(limit - 1);
    }
    range.append('/');
    if (endOfFile) {
      range.append(limit);
    } else {
      range.append('*');
    }

    RequestHeaders headers =
        RequestHeaders.of(
            HttpMethod.PUT, uploadUrl, HttpHeaderNames.CONTENT_RANGE, range.toString());

    HttpData data = new ByteBufHttpData(chunk, true);
    chunk.retain();

    return httpClient
        .execute(headers, data)
        .aggregate(eventLoop)
        .thenComposeAsync(
            msg -> {
              ResponseHeaders responseHeaders = msg.headers();
              if (!responseHeaders.status().codeClass().equals(HttpStatusClass.SUCCESS)
                  && responseHeaders.status().code() != 308) {
                chunk.release();
                throw new RuntimeException(
                    "Unsuccessful response uploading chunk: endOfFile: "
                        + endOfFile
                        + " Request headers: "
                        + headers
                        + "\n"
                        + " Response headers: "
                        + responseHeaders
                        + "\n"
                        + msg.content().toStringUtf8());
              }

              String responseRange = responseHeaders.get(HttpHeaderNames.RANGE);
              if (responseRange == null) {
                chunk.release();
                return completedFuture(null);
              }

              long responseLimit = rangeHeaderLimit(responseHeaders.get(HttpHeaderNames.RANGE));
              filePosition = responseLimit + 1;
              int notUploaded = (int) (limit - 1 - responseLimit);
              if (notUploaded > 0) {
                chunk.readerIndex(chunk.writerIndex() - notUploaded);

                if (endOfFile) {
                  return doUploadChunk(chunk, true);
                }

                if (unfinishedChunk == null) {
                  copyUnfinishedBuffer(chunk);
                } else {
                  ByteBuf newUnfinished =
                      alloc.buffer(chunk.readableBytes() + unfinishedChunk.readableBytes());
                  newUnfinished.writeBytes(chunk).writeBytes(unfinishedChunk);
                  unfinishedChunk.release();
                  unfinishedChunk = newUnfinished;
                }
              }
              chunk.release();
              return completedFuture(null);
            },
            eventLoop);
  }
 
Example #9
Source File: HttpHealthChecker.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public void onNext(HttpObject obj) {
    if (closeable.isClosing()) {
        subscription.cancel();
        return;
    }

    try {
        if (!(obj instanceof ResponseHeaders)) {
            ReferenceCountUtil.release(obj);
            return;
        }

        final ResponseHeaders headers = (ResponseHeaders) obj;
        updateLongPollingSettings(headers);

        final HttpStatus status = headers.status();
        final HttpStatusClass statusClass = status.codeClass();
        switch (statusClass) {
            case INFORMATIONAL:
                maybeSchedulePingCheck();
                break;
            case SERVER_ERROR:
                receivedExpectedResponse = true;
                break;
            case SUCCESS:
                isHealthy = true;
                receivedExpectedResponse = true;
                break;
            default:
                if (status == HttpStatus.NOT_MODIFIED) {
                    isHealthy = wasHealthy;
                    receivedExpectedResponse = true;
                } else {
                    // Do not use long polling on an unexpected status for safety.
                    maxLongPollingSeconds = 0;

                    if (statusClass == HttpStatusClass.CLIENT_ERROR) {
                        logger.warn("{} Unexpected 4xx health check response: {} A 4xx response " +
                                    "generally indicates a misconfiguration of the client. " +
                                    "Did you happen to forget to configure the {}'s client options?",
                                    reqCtx, headers, HealthCheckedEndpointGroup.class.getSimpleName());
                    } else {
                        logger.warn("{} Unexpected health check response: {}", reqCtx, headers);
                    }
                }
        }
    } finally {
        subscription.request(1);
    }
}
 
Example #10
Source File: RetryRuleWithContentBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es for a {@link RetryRuleWithContent} which will retry
 * if a class of the response status is one of the specified {@link HttpStatusClass}es.
 */
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onStatusClass(Iterable<HttpStatusClass> statusClasses) {
    return (RetryRuleWithContentBuilder<T>) super.onStatusClass(statusClasses);
}
 
Example #11
Source File: RetryRuleWithContentBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es for a {@link RetryRuleWithContent} which will retry
 * if a class of the response status is one of the specified {@link HttpStatusClass}es.
 */
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onStatusClass(HttpStatusClass... statusClasses) {
    return (RetryRuleWithContentBuilder<T>) super.onStatusClass(statusClasses);
}
 
Example #12
Source File: RetryRuleBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es for a {@link RetryRule} which will retry
 * if a class of the response status is one of the specified {@link HttpStatusClass}es.
 */
@Override
public RetryRuleBuilder onStatusClass(Iterable<HttpStatusClass> statusClasses) {
    return (RetryRuleBuilder) super.onStatusClass(statusClasses);
}
 
Example #13
Source File: AbstractRuleBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the {@link HttpStatusClass#SERVER_ERROR}.
 */
public AbstractRuleBuilder onServerErrorStatus() {
    return onStatusClass(HttpStatusClass.SERVER_ERROR);
}
 
Example #14
Source File: AbstractRuleBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es.
 */
public AbstractRuleBuilder onStatusClass(HttpStatusClass... statusClasses) {
    return onStatusClass(ImmutableSet.copyOf(requireNonNull(statusClasses, "statusClasses")));
}
 
Example #15
Source File: CircuitBreakerRule.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a newly created {@link CircuitBreakerRule} that will report a {@link Response} as a failure,
 * if the class of the response status is one of the specified {@link HttpStatusClass}es.
 */
static CircuitBreakerRule onStatusClass(Iterable<HttpStatusClass> statusClasses) {
    return builder().onStatusClass(statusClasses).thenFailure();
}
 
Example #16
Source File: CircuitBreakerRule.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a newly created {@link CircuitBreakerRule} that will report a {@link Response} as a failure,
 * if the class of the response status is one of the specified {@link HttpStatusClass}es.
 */
static CircuitBreakerRule onStatusClass(HttpStatusClass statusClass) {
    return builder().onStatusClass(statusClass).thenFailure();
}
 
Example #17
Source File: RetryRule.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a newly created {@link RetryRule} that will retry with
 * the {@linkplain Backoff#ofDefault() default backoff} if the class of the response status is
 * the specified {@link HttpStatusClass}.
 */
static RetryRule onStatusClass(HttpStatusClass statusClass) {
    return builder().onStatusClass(statusClass).thenBackoff();
}
 
Example #18
Source File: RetryRule.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a newly created {@link RetryRule} that will retry with
 * the {@linkplain Backoff#ofDefault() default backoff} if the class of the response status is
 * one of the specified {@link HttpStatusClass}es.
 */
static RetryRule onStatusClass(Iterable<HttpStatusClass> statusClasses) {
    return builder().onStatusClass(statusClasses).thenBackoff();
}
 
Example #19
Source File: CircuitBreakerRuleWithContentBuilder.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es for a {@link CircuitBreakerRuleWithContent}.
 * If the class of the response status is one of the specified {@link HttpStatusClass}es,
 * depending on the build methods({@link #thenSuccess()}, {@link #thenFailure()} and {@link #thenIgnore()}),
 * a {@link Response} is reported as a success or failure to a {@link CircuitBreaker} or ignored.
 */
@SuppressWarnings("unchecked")
@Override
public CircuitBreakerRuleWithContentBuilder<T> onStatusClass(Iterable<HttpStatusClass> statusClasses) {
    return (CircuitBreakerRuleWithContentBuilder<T>) super.onStatusClass(statusClasses);
}
 
Example #20
Source File: CircuitBreakerRuleWithContentBuilder.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es for a {@link CircuitBreakerRuleWithContent}.
 * If the class of the response status is one of the specified {@link HttpStatusClass}es,
 * depending on the build methods({@link #thenSuccess()}, {@link #thenFailure()} and {@link #thenIgnore()}),
 * a {@link Response} is reported as a success or failure to a {@link CircuitBreaker} or ignored.
 */
@SuppressWarnings("unchecked")
@Override
public CircuitBreakerRuleWithContentBuilder<T> onStatusClass(HttpStatusClass... statusClasses) {
    return (CircuitBreakerRuleWithContentBuilder<T>) super.onStatusClass(statusClasses);
}
 
Example #21
Source File: CircuitBreakerRuleBuilder.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es for a {@link CircuitBreakerRule}.
 * If the class of the response status is one of the specified {@link HttpStatusClass}es,
 * depending on the build methods({@link #thenSuccess()}, {@link #thenFailure()} and {@link #thenIgnore()}),
 * a {@link Response} is reported as a success or failure to a {@link CircuitBreaker} or ignored.
 */
@Override
public CircuitBreakerRuleBuilder onStatusClass(Iterable<HttpStatusClass> statusClasses) {
    return (CircuitBreakerRuleBuilder) super.onStatusClass(statusClasses);
}
 
Example #22
Source File: CircuitBreakerRuleBuilder.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Adds the specified {@link HttpStatusClass}es for a {@link CircuitBreakerRule}.
 * If the class of the response status is one of the specified {@link HttpStatusClass}es,
 * depending on the build methods({@link #thenSuccess()}, {@link #thenFailure()} and {@link #thenIgnore()}),
 * a {@link Response} is reported as a success or failure to a {@link CircuitBreaker} or ignored.
 */
@Override
public CircuitBreakerRuleBuilder onStatusClass(HttpStatusClass... statusClasses) {
    return (CircuitBreakerRuleBuilder) super.onStatusClass(statusClasses);
}