com.linecorp.armeria.client.HttpClient Java Examples

The following examples show how to use com.linecorp.armeria.client.HttpClient. 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: RetryingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private WebClient client(RetryRuleWithContent<HttpResponse> retryRuleWithContent,
                         long responseTimeoutMillis,
                         long responseTimeoutForEach, int maxTotalAttempts) {
    final Function<? super HttpClient, RetryingClient> retryingDecorator =
            RetryingClient.builder(retryRuleWithContent)
                          .responseTimeoutMillisForEachAttempt(responseTimeoutForEach)
                          .useRetryAfter(true)
                          .maxTotalAttempts(maxTotalAttempts)
                          .newDecorator();

    return WebClient.builder(server.httpUri())
                    .factory(clientFactory)
                    .responseTimeoutMillis(responseTimeoutMillis)
                    .decorator(LoggingClient.newDecorator())
                    .decorator(retryingDecorator)
                    .build();
}
 
Example #2
Source File: LoggingClient.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance that logs {@link Request}s and {@link Response}s at the specified
 * {@link LogLevel}s with the specified sanitizers.
 * If the logger is null, it means that the default logger is used.
 */
LoggingClient(
        HttpClient delegate,
        @Nullable Logger logger,
        Function<? super RequestOnlyLog, LogLevel> requestLogLevelMapper,
        Function<? super RequestLog, LogLevel> responseLogLevelMapper,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> requestHeadersSanitizer,
        BiFunction<? super RequestContext, Object, ?> requestContentSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> requestTrailersSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> responseHeadersSanitizer,
        BiFunction<? super RequestContext, Object, ?> responseContentSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> responseTrailersSanitizer,
        BiFunction<? super RequestContext, ? super Throwable, ?> responseCauseSanitizer,
        Sampler<? super ClientRequestContext> sampler) {

    super(delegate, logger, requestLogLevelMapper, responseLogLevelMapper,
          requestHeadersSanitizer, requestContentSanitizer, requestTrailersSanitizer,
          responseHeadersSanitizer, responseContentSanitizer, responseTrailersSanitizer,
          responseCauseSanitizer, sampler);
}
 
Example #3
Source File: ContentPreviewingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Function<? super HttpClient, ContentPreviewingClient> decodingContentPreviewDecorator() {
    final BiPredicate<? super RequestContext, ? super HttpHeaders> previewerPredicate =
            (requestContext, headers) -> "gzip".equals(headers.get(HttpHeaderNames.CONTENT_ENCODING));
    final BiFunction<HttpHeaders, ByteBuf, String> producer = (headers, data) -> {
        final byte[] bytes = new byte[data.readableBytes()];
        data.getBytes(0, bytes);
        final byte[] decoded;
        try (GZIPInputStream unzipper = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
            decoded = ByteStreams.toByteArray(unzipper);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
        return new String(decoded, StandardCharsets.UTF_8);
    };

    final ContentPreviewerFactory factory =
            ContentPreviewerFactory.builder()
                                   .maxLength(100)
                                   .binary(producer, previewerPredicate)
                                   .build();

    return ContentPreviewingClient.newDecorator(factory);
}
 
Example #4
Source File: ArmeriaChannel.java    From armeria with Apache License 2.0 6 votes vote down vote up
ArmeriaChannel(ClientBuilderParams params,
               HttpClient httpClient,
               MeterRegistry meterRegistry,
               SessionProtocol sessionProtocol,
               SerializationFormat serializationFormat,
               @Nullable GrpcJsonMarshaller jsonMarshaller) {
    this.params = params;
    this.httpClient = PooledHttpClient.of(httpClient);
    this.meterRegistry = meterRegistry;
    this.sessionProtocol = sessionProtocol;
    this.serializationFormat = serializationFormat;
    this.jsonMarshaller = jsonMarshaller;

    advertisedEncodingsHeader = String.join(
            ",", DecompressorRegistry.getDefaultInstance().getAdvertisedMessageEncodings());
}
 
Example #5
Source File: CircuitBreakerClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link HttpClient}.
 */
CircuitBreakerClient(HttpClient delegate, CircuitBreakerMapping mapping,
                     CircuitBreakerRuleWithContent<HttpResponse> ruleWithContent, int maxContentLength) {
    super(delegate, mapping, ruleWithContent);
    needsContentInRule = true;
    this.maxContentLength = maxContentLength;
}
 
Example #6
Source File: AWSSignatureVersion4.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
AWSSignatureVersion4(HttpClient delegate, String region, AWSCredentials.Provider credentials) {
  super(delegate);
  if (region == null) throw new NullPointerException("region == null");
  if (credentials == null) throw new NullPointerException("credentials == null");
  this.region = region;
  this.regionBytes = region.getBytes(UTF_8);
  this.credentials = credentials;
}
 
Example #7
Source File: CircuitBreakerClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void invoke(
        Function<? super HttpClient, CircuitBreakerClient> decorator,
        HttpRequest req) throws Exception {
    final HttpClient client = mock(HttpClient.class);
    final HttpClient decorated = decorator.apply(client);

    decorated.execute(ctx, req);
}
 
Example #8
Source File: BraveClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new tracing {@link HttpClient} decorator using the specified {@link HttpTracing} instance.
 */
public static Function<? super HttpClient, BraveClient> newDecorator(
        HttpTracing httpTracing) {
    try {
        ensureScopeUsesRequestContext(httpTracing.tracing());
    } catch (IllegalStateException e) {
        logger.warn("{} - it is appropriate to ignore this warning if this client is not being used " +
                    "inside an Armeria server (e.g., this is a normal spring-mvc tomcat server).",
                    e.getMessage());
    }
    return delegate -> new BraveClient(delegate, httpTracing);
}
 
Example #9
Source File: RetryingClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void retryWhenContentMatched() {
    final Function<? super HttpClient, RetryingClient> retryingDecorator =
            RetryingClient.builder(new RetryIfContentMatch("Need to retry"))
                          .contentPreviewLength(1024)
                          .newDecorator();
    final WebClient client = WebClient.builder(server.httpUri())
                                      .factory(clientFactory)
                                      .decorator(retryingDecorator)
                                      .build();

    final AggregatedHttpResponse res = client.get("/retry-content").aggregate().join();
    assertThat(res.contentUtf8()).isEqualTo("Succeeded after retry");
}
 
Example #10
Source File: RetryingClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void retryWithContentOnUnprocessedException() {
    final Backoff backoff = Backoff.fixed(2000);
    final RetryRuleWithContent<HttpResponse> strategy =
            RetryRuleWithContent.<HttpResponse>onResponse((unused, response) -> {
                return response.aggregate().thenApply(unused0 -> false);
            }).orElse(RetryRuleWithContent.onResponse((unused, response) -> {
                return response.aggregate().thenApply(unused0 -> false);
            })).orElse(RetryRuleWithContent.<HttpResponse>onResponse((unused, response) -> {
                return response.aggregate().thenApply(unused0 -> false);
            }).orElse(RetryRule.builder()
                               .onException(UnprocessedRequestException.class)
                               .thenBackoff(backoff)));
    final Function<? super HttpClient, RetryingClient> retryingDecorator =
            RetryingClient.builder(strategy)
                          .maxTotalAttempts(5)
                          .newDecorator();

    final WebClient client = WebClient.builder("http://127.0.0.1:1")
                                      .factory(ClientFactory.builder()
                                                            .options(clientFactory.options())
                                                            .connectTimeoutMillis(Long.MAX_VALUE)
                                                            .build())
                                      .responseTimeoutMillis(0)
                                      .decorator(LoggingClient.newDecorator())
                                      .decorator(retryingDecorator)
                                      .build();
    final Stopwatch stopwatch = Stopwatch.createStarted();
    assertThatThrownBy(() -> client.get("/unprocessed-exception").aggregate().join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(UnprocessedRequestException.class);
    assertThat(stopwatch.elapsed()).isBetween(Duration.ofSeconds(7), Duration.ofSeconds(20));
}
 
Example #11
Source File: ZipkinElasticsearchAwsStorageModule.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
@Bean @Qualifier(QUALIFIER)
Consumer<ClientOptionsBuilder> awsSignatureVersion4(String region,
    AWSCredentials.Provider credentials) {
  Function<HttpClient, HttpClient> decorator =
      AWSSignatureVersion4.newDecorator(region, credentials);
  return client -> client.decorator(decorator);
}
 
Example #12
Source File: LoggingModule.java    From curiostack with MIT License 5 votes vote down vote up
@Provides
@Singleton
static Function<HttpClient, LoggingClient> loggingClient(
    LoggingConfig config,
    @RequestHeaderSanitizer Set<Consumer<HttpHeadersBuilder>> requestHeaderSanitizers,
    @ResponseHeaderSanitizer Set<Consumer<HttpHeadersBuilder>> responseHeaderSanitizers) {
  LoggingClientBuilder builder = LoggingClient.builder();
  configureLoggingDecorator(builder, config, requestHeaderSanitizers, responseHeaderSanitizers);
  if (config.getLogAllClientRequests()) {
    builder.requestLogLevel(LogLevel.INFO);
    builder.successfulResponseLogLevel(LogLevel.INFO);
  }
  return builder::build;
}
 
Example #13
Source File: GoogleCredentialsDecoratingClient.java    From curiostack with MIT License 5 votes vote down vote up
/** Creates a new instance that decorates the specified {@link Client}. */
private GoogleCredentialsDecoratingClient(
    HttpClient delegate,
    AccessTokenProvider accessTokenProvider,
    TokenType type,
    AsciiString header) {
  super(delegate);
  this.accessTokenProvider = accessTokenProvider;
  this.type = type;
  this.header = header;
}
 
Example #14
Source File: RetryingClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private WebClient client(RetryRule retryRule, long responseTimeoutMillis,
                         long responseTimeoutForEach, int maxTotalAttempts) {
    final Function<? super HttpClient, RetryingClient> retryingDecorator =
            RetryingClient.builder(retryRule)
                          .responseTimeoutMillisForEachAttempt(responseTimeoutForEach)
                          .useRetryAfter(true)
                          .maxTotalAttempts(maxTotalAttempts)
                          .newDecorator();

    return WebClient.builder(server.httpUri())
                    .factory(clientFactory)
                    .responseTimeoutMillis(responseTimeoutMillis)
                    .decorator(retryingDecorator)
                    .build();
}
 
Example #15
Source File: RetryingClientWithLoggingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private Function<? super HttpClient, ? extends HttpClient> loggingDecorator() {
    return delegate -> new SimpleDecoratingHttpClient(delegate) {
        @Override
        public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception {
            ctx.log().whenRequestComplete().thenAccept(log -> listener.accept(log.partial()));
            ctx.log().whenComplete().thenAccept(listener);
            return unwrap().execute(ctx, req);
        }
    };
}
 
Example #16
Source File: BraveClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new tracing {@link HttpClient} decorator using the specified {@link Tracing} instance
 * and the remote service name.
 */
public static Function<? super HttpClient, BraveClient> newDecorator(
        Tracing tracing, @Nullable String remoteServiceName) {
    HttpTracing httpTracing = HttpTracing.newBuilder(tracing)
                                         .clientRequestParser(ArmeriaHttpClientParser.get())
                                         .clientResponseParser(ArmeriaHttpClientParser.get())
                                         .build();
    if (remoteServiceName != null) {
        httpTracing = httpTracing.clientOf(remoteServiceName);
    }
    return newDecorator(httpTracing);
}
 
Example #17
Source File: CircuitBreakerClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void failFastInvocation(
        Function<? super HttpClient, CircuitBreakerClient> decorator, HttpMethod method, int count) {
    for (int i = 0; i < count; i++) {
        final HttpRequest req = HttpRequest.of(method, "/");
        assertThatThrownBy(() -> invoke(decorator, req)).isInstanceOf(FailFastException.class);
    }
}
 
Example #18
Source File: RetryingClientBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a newly-created {@link RetryingClient} based on the properties of this builder.
 */
public RetryingClient build(HttpClient delegate) {
    if (needsContentInRule) {
        return new RetryingClient(delegate, retryRuleWithContent(), maxTotalAttempts(),
                                  responseTimeoutMillisForEachAttempt(), useRetryAfter, maxContentLength);
    }

    return new RetryingClient(delegate, retryRule(), maxTotalAttempts(),
                              responseTimeoutMillisForEachAttempt(), useRetryAfter);
}
 
Example #19
Source File: RetryingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link HttpClient}.
 */
RetryingClient(HttpClient delegate,
               RetryRuleWithContent<HttpResponse> retryRuleWithContent, int totalMaxAttempts,
               long responseTimeoutMillisForEachAttempt, boolean useRetryAfter, int maxContentLength) {
    super(delegate, retryRuleWithContent, totalMaxAttempts, responseTimeoutMillisForEachAttempt);
    requiresResponseTrailers = retryRuleWithContent.requiresResponseTrailers();
    needsContentInRule = true;
    this.useRetryAfter = useRetryAfter;
    checkArgument(maxContentLength > 0,
                  "maxContentLength: %s (expected: > 0)", maxContentLength);
    this.maxContentLength = maxContentLength;
}
 
Example #20
Source File: RetryingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link HttpClient}.
 */
RetryingClient(HttpClient delegate, RetryRule retryRule, int totalMaxAttempts,
               long responseTimeoutMillisForEachAttempt, boolean useRetryAfter) {
    super(delegate, retryRule, totalMaxAttempts, responseTimeoutMillisForEachAttempt);
    requiresResponseTrailers = retryRule.requiresResponseTrailers();
    needsContentInRule = false;
    this.useRetryAfter = useRetryAfter;
    maxContentLength = 0;
}
 
Example #21
Source File: DecodingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link HttpClient} with the provided decoders.
 */
DecodingClient(HttpClient delegate,
               Iterable<? extends StreamDecoderFactory> decoderFactories) {
    super(delegate);
    this.decoderFactories = Streams.stream(decoderFactories)
                                   .collect(toImmutableMap(StreamDecoderFactory::encodingHeaderValue,
                                                           Function.identity()));
    acceptEncodingHeader = String.join(",", this.decoderFactories.keySet());
}
 
Example #22
Source File: CircuitBreakerClientBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a newly-created {@link CircuitBreakerClient} based on the properties of this builder.
 */
public CircuitBreakerClient build(HttpClient delegate) {
    if (needsContentInRule) {
        return new CircuitBreakerClient(delegate, mapping(), ruleWithContent(), maxContentLength);
    }

    return new CircuitBreakerClient(delegate, mapping(), rule());
}
 
Example #23
Source File: PooledHttpClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link PooledHttpClient} that delegates to the provided {@link HttpClient} for issuing
 * requests.
 */
static PooledHttpClient of(HttpClient delegate) {
    if (delegate instanceof PooledHttpClient) {
        return (PooledHttpClient) delegate;
    }
    return new DefaultPooledHttpClient(delegate);
}
 
Example #24
Source File: LoggingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link HttpClient} decorator that logs {@link Request}s and {@link Response}s at
 * {@link LogLevel#INFO} for success, {@link LogLevel#WARN} for failure.
 *
 * @see LoggingClientBuilder for more information on the default settings.
 */
public static Function<? super HttpClient, LoggingClient> newDecorator() {
    return builder().requestLogLevel(LogLevel.INFO)
                    .successfulResponseLogLevel(LogLevel.INFO)
                    .failureResponseLogLevel(LogLevel.WARN)
                    .newDecorator();
}
 
Example #25
Source File: LoggingClientBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a newly-created {@link LoggingClient} decorating {@code delegate} based on the properties of
 * this builder.
 */
public LoggingClient build(HttpClient delegate) {
    return new LoggingClient(delegate,
                             logger(),
                             requestLogLevelMapper(),
                             responseLogLevelMapper(),
                             requestHeadersSanitizer(),
                             requestContentSanitizer(),
                             requestTrailersSanitizer(),
                             responseHeadersSanitizer(),
                             responseContentSanitizer(),
                             responseTrailersSanitizer(),
                             responseCauseSanitizer(),
                             sampler());
}
 
Example #26
Source File: THttpClientDelegate.java    From armeria with Apache License 2.0 5 votes vote down vote up
THttpClientDelegate(HttpClient httpClient,
                    SerializationFormat serializationFormat) {
    super(PooledHttpClient.of(httpClient));
    this.serializationFormat = serializationFormat;
    protocolFactory = ThriftProtocolFactories.get(serializationFormat);
    mediaType = serializationFormat.mediaType();
}
 
Example #27
Source File: SimplePooledDecoratingHttpClientTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private PooledDecorator(HttpClient delegate) {
    super(delegate);
}
 
Example #28
Source File: ContentPreviewingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link HttpClient}.
 */
private ContentPreviewingClient(HttpClient delegate, ContentPreviewerFactory contentPreviewerFactory) {
    super(delegate);
    this.contentPreviewerFactory = contentPreviewerFactory;
}
 
Example #29
Source File: ContentPreviewingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new {@link ContentPreviewingClient} decorator with the specified
 * {@link ContentPreviewerFactory}.
 */
public static Function<? super HttpClient, ContentPreviewingClient> newDecorator(
        ContentPreviewerFactory contentPreviewerFactory) {
    requireNonNull(contentPreviewerFactory, "contentPreviewerFactory");
    return delegate -> new ContentPreviewingClient(delegate, contentPreviewerFactory);
}
 
Example #30
Source File: MetricCollectingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an {@link HttpClient} decorator that tracks request stats using {@link MeterRegistry}.
 */
public static Function<? super HttpClient, MetricCollectingClient> newDecorator(
        MeterIdPrefixFunction meterIdPrefixFunction) {
    requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
    return delegate -> new MetricCollectingClient(delegate, meterIdPrefixFunction);
}