feign.Request.Options Java Examples

The following examples show how to use feign.Request.Options. 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: FeignAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static Object onRequest(final Object arg1, final Object arg2) {
  final Request request = (Request)arg1;
  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(request.method())
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .start();

  for (final FeignSpanDecorator decorator : Configuration.spanDecorators)
    decorator.onRequest(request, (Options)arg2, span);

  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(COMPONENT_NAME, span, scope);

  return inject(tracer, span.context(), request);
}
 
Example #2
Source File: AsyncClient.java    From feign with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Response> execute(Request request,
                                           Options options,
                                           Optional<C> requestContext) {
  final CompletableFuture<Response> result = new CompletableFuture<>();
  final Future<?> future = executorService.submit(() -> {
    try {
      result.complete(client.execute(request, options));
    } catch (final Exception e) {
      result.completeExceptionally(e);
    }
  });
  result.whenComplete((response, throwable) -> {
    if (result.isCancelled()) {
      future.cancel(true);
    }
  });
  return result;
}
 
Example #3
Source File: Feign.java    From feign with Apache License 2.0 6 votes vote down vote up
public Feign build() {
  Client client = Capability.enrich(this.client, capabilities);
  Retryer retryer = Capability.enrich(this.retryer, capabilities);
  List<RequestInterceptor> requestInterceptors = this.requestInterceptors.stream()
      .map(ri -> Capability.enrich(ri, capabilities))
      .collect(Collectors.toList());
  Logger logger = Capability.enrich(this.logger, capabilities);
  Contract contract = Capability.enrich(this.contract, capabilities);
  Options options = Capability.enrich(this.options, capabilities);
  Encoder encoder = Capability.enrich(this.encoder, capabilities);
  Decoder decoder = Capability.enrich(this.decoder, capabilities);
  InvocationHandlerFactory invocationHandlerFactory =
      Capability.enrich(this.invocationHandlerFactory, capabilities);
  QueryMapEncoder queryMapEncoder = Capability.enrich(this.queryMapEncoder, capabilities);

  SynchronousMethodHandler.Factory synchronousMethodHandlerFactory =
      new SynchronousMethodHandler.Factory(client, retryer, requestInterceptors, logger,
          logLevel, decode404, closeAfterDecode, propagationPolicy, forceDecoding);
  ParseHandlersByName handlersByName =
      new ParseHandlersByName(contract, options, encoder, decoder, queryMapEncoder,
          errorDecoder, synchronousMethodHandlerFactory);
  return new ReflectiveFeign(handlersByName, invocationHandlerFactory, queryMapEncoder);
}
 
Example #4
Source File: SynchronousMethodHandler.java    From feign with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(Object[] argv) throws Throwable {
  RequestTemplate template = buildTemplateFromArgs.create(argv);
  Options options = findOptions(argv);
  Retryer retryer = this.retryer.clone();
  while (true) {
    try {
      return executeAndDecode(template, options);
    } catch (RetryableException e) {
      try {
        retryer.continueOrPropagate(e);
      } catch (RetryableException th) {
        Throwable cause = th.getCause();
        if (propagationPolicy == UNWRAP && cause != null) {
          throw cause;
        } else {
          throw th;
        }
      }
      if (logLevel != Logger.Level.NONE) {
        logger.logRetry(metadata.configKey(), logLevel);
      }
      continue;
    }
  }
}
 
Example #5
Source File: JAXRSClient.java    From feign with Apache License 2.0 6 votes vote down vote up
@Override
public feign.Response execute(feign.Request request, Options options) throws IOException {
  final Response response = clientBuilder
      .connectTimeout(options.connectTimeoutMillis(), TimeUnit.MILLISECONDS)
      .readTimeout(options.readTimeoutMillis(), TimeUnit.MILLISECONDS)
      .build()
      .target(request.url())
      .request()
      .headers(toMultivaluedMap(request.headers()))
      .method(request.httpMethod().name(), createRequestEntity(request));

  return feign.Response.builder()
      .request(request)
      .body(response.readEntity(InputStream.class),
          integerHeader(response, HttpHeaders.CONTENT_LENGTH))
      .headers(toMap(response.getStringHeaders()))
      .status(response.getStatus())
      .reason(response.getStatusInfo().getReasonPhrase())
      .build();
}
 
Example #6
Source File: Http2Client.java    From feign with Apache License 2.0 6 votes vote down vote up
@Override
public Response execute(Request request, Options options) throws IOException {
  final HttpRequest httpRequest = newRequestBuilder(request).build();

  HttpResponse<byte[]> httpResponse;
  try {
    httpResponse = client.send(httpRequest, BodyHandlers.ofByteArray());
  } catch (final InterruptedException e) {
    throw new IOException("Invalid uri " + request.url(), e);
  }

  final OptionalLong length = httpResponse.headers().firstValueAsLong("Content-Length");

  final Response response = Response.builder()
      .body(new ByteArrayInputStream(httpResponse.body()),
          length.isPresent() ? (int) length.getAsLong() : null)
      .reason(httpResponse.headers().firstValue("Reason-Phrase").orElse("OK"))
      .request(request)
      .status(httpResponse.statusCode())
      .headers(castMapCollectType(httpResponse.headers().map()))
      .build();
  return response;
}
 
Example #7
Source File: ReactiveFeignIntegrationTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void testClient() throws Exception {
  Client client = mock(Client.class);
  given(client.execute(any(Request.class), any(Options.class)))
      .willAnswer((Answer<Response>) invocation -> Response.builder()
          .status(200)
          .headers(Collections.emptyMap())
          .body("1.0", Charset.defaultCharset())
          .request((Request) invocation.getArguments()[0])
          .build());

  TestReactorService service = ReactorFeign.builder()
      .client(client)
      .target(TestReactorService.class, this.getServerUrl());
  StepVerifier.create(service.version())
      .expectNext("1.0")
      .expectComplete()
      .verify();
  verify(client, times(1)).execute(any(Request.class), any(Options.class));
}
 
Example #8
Source File: ReflectiveFeign.java    From feign with Apache License 2.0 6 votes vote down vote up
ParseHandlersByName(
    Contract contract,
    Options options,
    Encoder encoder,
    Decoder decoder,
    QueryMapEncoder queryMapEncoder,
    ErrorDecoder errorDecoder,
    SynchronousMethodHandler.Factory factory) {
  this.contract = contract;
  this.options = options;
  this.factory = factory;
  this.errorDecoder = errorDecoder;
  this.queryMapEncoder = queryMapEncoder;
  this.encoder = checkNotNull(encoder, "encoder");
  this.decoder = checkNotNull(decoder, "decoder");
}
 
Example #9
Source File: UltraDNSProvider.java    From denominator with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
Feign feign(Logger logger, Logger.Level logLevel) {

  /**
   * {@link UltraDNS#updateDirectionalPoolRecord(DirectionalRecord, DirectionalGroup)} and {@link
   * UltraDNS#addDirectionalPoolRecord(DirectionalRecord, DirectionalGroup, String)} can take up
   * to 10 minutes to complete.
   */
  Options options = new Options(10 * 1000, 10 * 60 * 1000);
  Decoder decoder = decoder();
  return Feign.builder()
      .logger(logger)
      .logLevel(logLevel)
      .options(options)
      .encoder(new UltraDNSFormEncoder())
      .decoder(decoder)
      .errorDecoder(new UltraDNSErrorDecoder(decoder))
      .build();
}
 
Example #10
Source File: AsyncApacheHttp5Client.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Response> execute(Request request,
                                           Options options,
                                           Optional<HttpClientContext> requestContext) {
  final SimpleHttpRequest httpUriRequest = toClassicHttpRequest(request, options);

  final CompletableFuture<Response> result = new CompletableFuture<>();
  final FutureCallback<SimpleHttpResponse> callback = new FutureCallback<SimpleHttpResponse>() {

    @Override
    public void completed(SimpleHttpResponse httpResponse) {
      result.complete(toFeignResponse(httpResponse, request));
    }

    @Override
    public void failed(Exception ex) {
      result.completeExceptionally(ex);
    }

    @Override
    public void cancelled() {
      result.cancel(false);
    }
  };

  client.execute(httpUriRequest,
      configureTimeouts(options, requestContext.orElseGet(HttpClientContext::new)),
      callback);

  return result;
}
 
Example #11
Source File: AsyncApacheHttp5Client.java    From feign with Apache License 2.0 5 votes vote down vote up
protected HttpClientContext configureTimeouts(Request.Options options,
                                              HttpClientContext context) {
  // per request timeouts
  final RequestConfig requestConfig =
      (client instanceof Configurable
          ? RequestConfig.copy(((Configurable) client).getConfig())
          : RequestConfig.custom())
              .setConnectTimeout(options.connectTimeout(), options.connectTimeoutUnit())
              .setResponseTimeout(options.readTimeout(), options.readTimeoutUnit())
              .build();
  context.setRequestConfig(requestConfig);
  return context;
}
 
Example #12
Source File: AsyncApacheHttp5Client.java    From feign with Apache License 2.0 5 votes vote down vote up
SimpleHttpRequest toClassicHttpRequest(Request request,
                                       Request.Options options) {
  final SimpleHttpRequest httpRequest =
      new SimpleHttpRequest(request.httpMethod().name(), request.url());

  // request headers
  boolean hasAcceptHeader = false;
  for (final Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
    final String headerName = headerEntry.getKey();
    if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
      hasAcceptHeader = true;
    }

    if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
      // The 'Content-Length' header is always set by the Apache client and it
      // doesn't like us to set it as well.
      continue;
    }

    for (final String headerValue : headerEntry.getValue()) {
      httpRequest.addHeader(headerName, headerValue);
    }
  }
  // some servers choke on the default accept string, so we'll set it to anything
  if (!hasAcceptHeader) {
    httpRequest.addHeader(ACCEPT_HEADER_NAME, "*/*");
  }

  // request body
  // final Body requestBody = request.requestBody();
  final byte[] data = request.body();
  if (data != null) {
    httpRequest.setBodyBytes(data, getContentType(request));
  }

  return httpRequest;
}
 
Example #13
Source File: ReactiveFeignIntegrationTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void testReactorTargetFull() throws Exception {
  this.webServer.enqueue(new MockResponse().setBody("1.0"));
  this.webServer.enqueue(new MockResponse().setBody("{ \"username\": \"test\" }"));

  TestReactorService service = ReactorFeign.builder()
      .encoder(new JacksonEncoder())
      .decoder(new JacksonDecoder())
      .logger(new ConsoleLogger())
      .decode404()
      .options(new Options())
      .logLevel(Level.FULL)
      .target(TestReactorService.class, this.getServerUrl());
  assertThat(service).isNotNull();

  StepVerifier.create(service.version())
      .expectNext("1.0")
      .expectComplete()
      .verify();
  assertThat(webServer.takeRequest().getPath()).isEqualToIgnoringCase("/version");


  /* test encoding and decoding */
  StepVerifier.create(service.user("test"))
      .assertNext(user -> assertThat(user).hasFieldOrPropertyWithValue("username", "test"))
      .expectComplete()
      .verify();
  assertThat(webServer.takeRequest().getPath()).isEqualToIgnoringCase("/users/test");

}
 
Example #14
Source File: SynchronousMethodHandler.java    From feign with Apache License 2.0 5 votes vote down vote up
public MethodHandler create(Target<?> target,
                            MethodMetadata md,
                            RequestTemplate.Factory buildTemplateFromArgs,
                            Options options,
                            Decoder decoder,
                            ErrorDecoder errorDecoder) {
  return new SynchronousMethodHandler(target, client, retryer, requestInterceptors, logger,
      logLevel, md, buildTemplateFromArgs, options, decoder,
      errorDecoder, decode404, closeAfterDecode, propagationPolicy, forceDecoding);
}
 
Example #15
Source File: MeteredClient.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Response execute(Request request, Options options) throws IOException {
  final RequestTemplate template = request.requestTemplate();
  try (final Timer.Context classTimer =
      metricRegistry.timer(
          metricName.metricName(template.methodMetadata(), template.feignTarget()),
          metricSuppliers.timers()).time()) {
    return client.execute(request, options);
  }
}
 
Example #16
Source File: MeteredClient.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Response execute(Request request, Options options) throws IOException {
  final RequestTemplate template = request.requestTemplate();
  try (final Context classTimer =
      metricRegistry.timer(
          metricName.metricName(template.methodMetadata(), template.feignTarget()),
          metricSuppliers.timers()).time()) {
    return client.execute(request, options);
  }
}
 
Example #17
Source File: SynchronousMethodHandler.java    From feign with Apache License 2.0 5 votes vote down vote up
Options findOptions(Object[] argv) {
  if (argv == null || argv.length == 0) {
    return this.options;
  }
  return Stream.of(argv)
      .filter(Options.class::isInstance)
      .map(Options.class::cast)
      .findFirst()
      .orElse(this.options);
}
 
Example #18
Source File: SynchronousMethodHandler.java    From feign with Apache License 2.0 5 votes vote down vote up
private SynchronousMethodHandler(Target<?> target, Client client, Retryer retryer,
    List<RequestInterceptor> requestInterceptors, Logger logger,
    Logger.Level logLevel, MethodMetadata metadata,
    RequestTemplate.Factory buildTemplateFromArgs, Options options,
    Decoder decoder, ErrorDecoder errorDecoder, boolean decode404,
    boolean closeAfterDecode, ExceptionPropagationPolicy propagationPolicy,
    boolean forceDecoding) {

  this.target = checkNotNull(target, "target");
  this.client = checkNotNull(client, "client for %s", target);
  this.retryer = checkNotNull(retryer, "retryer for %s", target);
  this.requestInterceptors =
      checkNotNull(requestInterceptors, "requestInterceptors for %s", target);
  this.logger = checkNotNull(logger, "logger for %s", target);
  this.logLevel = checkNotNull(logLevel, "logLevel for %s", target);
  this.metadata = checkNotNull(metadata, "metadata for %s", target);
  this.buildTemplateFromArgs = checkNotNull(buildTemplateFromArgs, "metadata for %s", target);
  this.options = checkNotNull(options, "options for %s", target);
  this.propagationPolicy = propagationPolicy;

  if (forceDecoding) {
    // internal only: usual handling will be short-circuited, and all responses will be passed to
    // decoder directly!
    this.decoder = decoder;
    this.asyncResponseHandler = null;
  } else {
    this.decoder = null;
    this.asyncResponseHandler = new AsyncResponseHandler(logLevel, logger, decoder, errorDecoder,
        decode404, closeAfterDecode);
  }
}
 
Example #19
Source File: AsyncClient.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Response> execute(Request request,
                                           Options options,
                                           Optional<C> requestContext) {
  final CompletableFuture<Response> result = new CompletableFuture<>();
  try {
    result.complete(client.execute(request, options));
  } catch (final Exception e) {
    result.completeExceptionally(e);
  }

  return result;
}
 
Example #20
Source File: AsyncFeign.java    From feign with Apache License 2.0 5 votes vote down vote up
private Response stageExecution(Request request, Options options) {
  final Response result = Response.builder()
      .status(200)
      .request(request)
      .build();

  final AsyncInvocation<C> invocationContext = activeContext.get();

  invocationContext.setResponseFuture(
      client.execute(request, options, Optional.ofNullable(invocationContext.context())));


  return result;
}
 
Example #21
Source File: CapabilityTest.java    From feign with Apache License 2.0 4 votes vote down vote up
@Override
public Response execute(Request request, Options options) throws IOException {
  return null;
}
 
Example #22
Source File: CapabilityTest.java    From feign with Apache License 2.0 4 votes vote down vote up
@Override
public Response execute(Request request, Options options) throws IOException {
  return null;
}
 
Example #23
Source File: MockSpanDecorator.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@Override
public void onRequest(final Request request, final Options options, final Span span) {
  span.setTag(MOCK_TAG_KEY, MOCK_TAG_VALUE);
}
 
Example #24
Source File: Capability.java    From feign with Apache License 2.0 4 votes vote down vote up
default Options enrich(Options options) {
  return options;
}
 
Example #25
Source File: Client.java    From feign with Apache License 2.0 4 votes vote down vote up
HttpURLConnection convertAndSend(Request request, Options options) throws IOException {
  final URL url = new URL(request.url());
  final HttpURLConnection connection = this.getConnection(url);
  if (connection instanceof HttpsURLConnection) {
    HttpsURLConnection sslCon = (HttpsURLConnection) connection;
    if (sslContextFactory != null) {
      sslCon.setSSLSocketFactory(sslContextFactory);
    }
    if (hostnameVerifier != null) {
      sslCon.setHostnameVerifier(hostnameVerifier);
    }
  }
  connection.setConnectTimeout(options.connectTimeoutMillis());
  connection.setReadTimeout(options.readTimeoutMillis());
  connection.setAllowUserInteraction(false);
  connection.setInstanceFollowRedirects(options.isFollowRedirects());
  connection.setRequestMethod(request.httpMethod().name());

  Collection<String> contentEncodingValues = request.headers().get(CONTENT_ENCODING);
  boolean gzipEncodedRequest =
      contentEncodingValues != null && contentEncodingValues.contains(ENCODING_GZIP);
  boolean deflateEncodedRequest =
      contentEncodingValues != null && contentEncodingValues.contains(ENCODING_DEFLATE);

  boolean hasAcceptHeader = false;
  Integer contentLength = null;
  for (String field : request.headers().keySet()) {
    if (field.equalsIgnoreCase("Accept")) {
      hasAcceptHeader = true;
    }
    for (String value : request.headers().get(field)) {
      if (field.equals(CONTENT_LENGTH)) {
        if (!gzipEncodedRequest && !deflateEncodedRequest) {
          contentLength = Integer.valueOf(value);
          connection.addRequestProperty(field, value);
        }
      } else {
        connection.addRequestProperty(field, value);
      }
    }
  }
  // Some servers choke on the default accept string.
  if (!hasAcceptHeader) {
    connection.addRequestProperty("Accept", "*/*");
  }

  if (request.body() != null) {
    if (disableRequestBuffering) {
      if (contentLength != null) {
        connection.setFixedLengthStreamingMode(contentLength);
      } else {
        connection.setChunkedStreamingMode(8196);
      }
    }
    connection.setDoOutput(true);
    OutputStream out = connection.getOutputStream();
    if (gzipEncodedRequest) {
      out = new GZIPOutputStream(out);
    } else if (deflateEncodedRequest) {
      out = new DeflaterOutputStream(out);
    }
    try {
      out.write(request.body());
    } finally {
      try {
        out.close();
      } catch (IOException suppressed) { // NOPMD
      }
    }
  }
  return connection;
}
 
Example #26
Source File: Client.java    From feign with Apache License 2.0 4 votes vote down vote up
@Override
public Response execute(Request request, Options options) throws IOException {
  HttpURLConnection connection = convertAndSend(request, options);
  return convertResponse(connection, request);
}
 
Example #27
Source File: FeignSpanDecoratorConfiguration.java    From java-spring-cloud with Apache License 2.0 4 votes vote down vote up
@Override
public void onResponse(Response response, Options options, Span span) {
}
 
Example #28
Source File: FeignSpanDecoratorConfiguration.java    From java-spring-cloud with Apache License 2.0 4 votes vote down vote up
@Override
public void onRequest(Request request, Options options, Span span) {
  span.setTag(TAG_NAME, TAG_VALUE);
}
 
Example #29
Source File: FeignSpanDecoratorConfiguration.java    From java-spring-cloud with Apache License 2.0 4 votes vote down vote up
@Override
public void onResponse(Response response, Options options, Span span) {
}
 
Example #30
Source File: FeignSpanDecoratorConfiguration.java    From java-spring-cloud with Apache License 2.0 4 votes vote down vote up
@Override
public void onRequest(Request request, Options options, Span span) {
  span.setTag(TAG_NAME, TAG_VALUE);
}