feign.codec.Decoder Java Examples

The following examples show how to use feign.codec.Decoder. 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: FeignUnderAsyncTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void doesntRetryAfterResponseIsSent() throws Exception {
  server.enqueue(new MockResponse().setBody("success!"));
  thrown.expect(FeignException.class);
  thrown.expectMessage("timeout reading POST http://");

  TestInterface api = new TestInterfaceBuilder()
      .decoder(new Decoder() {
        @Override
        public Object decode(Response response, Type type) throws IOException {
          throw new IOException("timeout");
        }
      }).target("http://localhost:" + server.getPort());

  api.post();
}
 
Example #2
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 #3
Source File: AsyncFeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void doesntRetryAfterResponseIsSent() throws Throwable {
  server.enqueue(new MockResponse().setBody("success!"));
  thrown.expect(FeignException.class);
  thrown.expectMessage("timeout reading POST http://");

  TestInterfaceAsync api = new TestInterfaceAsyncBuilder().decoder(new Decoder() {
    @Override
    public Object decode(Response response, Type type) throws IOException {
      throw new IOException("timeout");
    }
  }).target("http://localhost:" + server.getPort());

  CompletableFuture<?> cf = api.post();
  server.takeRequest();
  unwrap(cf);
}
 
Example #4
Source File: AsyncFeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodingExceptionGetWrappedInDecode404Mode() throws Throwable {
  server.enqueue(new MockResponse().setResponseCode(404));
  thrown.expect(DecodeException.class);
  thrown.expectCause(isA(NoSuchElementException.class));;

  TestInterfaceAsync api = new TestInterfaceAsyncBuilder().decode404().decoder(new Decoder() {
    @Override
    public Object decode(Response response, Type type) throws IOException {
      assertEquals(404, response.status());
      throw new NoSuchElementException();
    }
  }).target("http://localhost:" + server.getPort());

  unwrap(api.post());
}
 
Example #5
Source File: OpenFeignFieldLevelEncryptionDecoderTest.java    From client-encryption-java with MIT License 6 votes vote down vote up
@Test
public void testDecode_ShouldDoNothing_WhenEmptyPayload() throws Exception {

    // GIVEN
    FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder().build();
    Type type = mock(Type.class);
    Response response = mock(Response.class);
    when(response.body()).thenReturn(buildResponseBody(""));
    Decoder delegate = mock(Decoder.class);

    // WHEN
    OpenFeignFieldLevelEncryptionDecoder instanceUnderTest = new OpenFeignFieldLevelEncryptionDecoder(config, delegate);
    instanceUnderTest.decode(response, type);

    // THEN
    verify(delegate).decode(any(Response.class), any(Type.class));
    verify(response).body();
    verifyNoMoreInteractions(response);
}
 
Example #6
Source File: OpenFeignFieldLevelEncryptionDecoderTest.java    From client-encryption-java with MIT License 6 votes vote down vote up
@Test
public void testDecode_ShouldDoNothing_WhenNoPayload() throws Exception {

    // GIVEN
    FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder().build();
    Type type = mock(Type.class);
    Response response = mock(Response.class);
    Decoder delegate = mock(Decoder.class);
    when(response.body()).thenReturn(null);

    // WHEN
    OpenFeignFieldLevelEncryptionDecoder instanceUnderTest = new OpenFeignFieldLevelEncryptionDecoder(config, delegate);
    instanceUnderTest.decode(response, type);

    // THEN
    verify(delegate).decode(any(Response.class), any(Type.class));
    verify(response).body();
    verifyNoMoreInteractions(response);
}
 
Example #7
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodingExceptionGetWrappedInDecode404Mode() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(404));
  thrown.expect(DecodeException.class);
  thrown.expectCause(isA(NoSuchElementException.class));;

  TestInterface api = new TestInterfaceBuilder()
      .decode404()
      .decoder(new Decoder() {
        @Override
        public Object decode(Response response, Type type) throws IOException {
          assertEquals(404, response.status());
          throw new NoSuchElementException();
        }
      }).target("http://localhost:" + server.getPort());
  api.post();
}
 
Example #8
Source File: FeignUnderAsyncTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodingExceptionGetWrappedInDecode404Mode() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(404));
  thrown.expect(DecodeException.class);
  thrown.expectCause(isA(NoSuchElementException.class));;

  TestInterface api = new TestInterfaceBuilder()
      .decode404()
      .decoder(new Decoder() {
        @Override
        public Object decode(Response response, Type type) throws IOException {
          assertEquals(404, response.status());
          throw new NoSuchElementException();
        }
      }).target("http://localhost:" + server.getPort());
  api.post();
}
 
Example #9
Source File: FeignClientFactoryBean.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
protected Feign.Builder feign(FeignContext context) {
	FeignLoggerFactory loggerFactory = get(context, FeignLoggerFactory.class);
	Logger logger = loggerFactory.create(this.type);

	// @formatter:off
	Feign.Builder builder = get(context, Feign.Builder.class)
			// required values
			.logger(logger)
			.encoder(get(context, Encoder.class))
			.decoder(get(context, Decoder.class))
			.contract(get(context, Contract.class));
	// @formatter:on

	configureFeign(context, builder);
	applyBuildCustomizers(context, builder);

	return builder;
}
 
Example #10
Source File: BaseApiTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void resolvesBodyParameter() throws InterruptedException {
  server.enqueue(new MockResponse().setBody("foo"));

  String baseUrl = server.url("/default").toString();

  Feign.builder()
      .encoder(new Encoder() {
        @Override
        public void encode(Object object, Type bodyType, RequestTemplate template) {
          assertThat(bodyType)
              .isEqualTo(new TypeToken<Keys<String>>() {}.getType());
        }
      })
      .decoder(new Decoder() {
        @Override
        public Object decode(Response response, Type type) {
          assertThat(type)
              .isEqualTo(new TypeToken<Entities<String, Long>>() {}.getType());
          return null;
        }
      })
      .target(MyApi.class, baseUrl).getAll(new Keys<String>());
}
 
Example #11
Source File: CorsConfiguration.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 升级版本后, 不加这个 gateway 使用feign会报错,不知道什么原因
 *
 * @return
 */
@Bean
public Decoder feignFormDecoder() {
    List<HttpMessageConverter<?>> converters = new RestTemplate().getMessageConverters();
    ObjectFactory<HttpMessageConverters> factory = () -> new HttpMessageConverters(converters);
    return new ResponseEntityDecoder(new SpringDecoder(factory));
}
 
Example #12
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 #13
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void doesntRetryAfterResponseIsSent() throws Exception {
  server.enqueue(new MockResponse().setBody("success!"));
  thrown.expect(FeignException.class);
  thrown.expectMessage("timeout reading POST http://");

  TestInterface api = new TestInterfaceBuilder()
      .decoder(new Decoder() {
        @Override
        public Object decode(Response response, Type type) throws IOException {
          throw new IOException("timeout");
        }
      }).target("http://localhost:" + server.getPort());

  api.post();
}
 
Example #14
Source File: BaseApiTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void resolvesParameterizedResult() throws InterruptedException {
  server.enqueue(new MockResponse().setBody("foo"));

  String baseUrl = server.url("/default").toString();

  Feign.builder()
      .decoder(new Decoder() {
        @Override
        public Object decode(Response response, Type type) {
          assertThat(type)
              .isEqualTo(new TypeToken<Entity<String, Long>>() {}.getType());
          return null;
        }
      })
      .target(MyApi.class, baseUrl).get("foo");

  assertThat(server.takeRequest()).hasPath("/default/api/foo");
}
 
Example #15
Source File: HttpZallyService.java    From intellij-swagger with MIT License 6 votes vote down vote up
private static ZallyApi connect() {
  final String zallyUrl = ServiceManager.getService(ZallySettings.class).getZallyUrl();

  if (zallyUrl == null || zallyUrl.isEmpty()) {
    throw new RuntimeException("Zally URL is missing");
  }

  final Gson gson =
      new GsonBuilder()
          .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
          .create();
  final Decoder decoder = new GsonDecoder(gson);

  return Feign.builder()
      .encoder(new GsonEncoder())
      .decoder(decoder)
      .errorDecoder(new LintingResponseErrorDecoder())
      .logger(new Logger.ErrorLogger())
      .logLevel(Logger.Level.BASIC)
      .target(ZallyApi.class, zallyUrl);
}
 
Example #16
Source File: AnnotationErrorDecoderExceptionConstructorsTest.java    From feign-annotation-error-decoder with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
  AnnotationErrorDecoder decoder = AnnotationErrorDecoder
      .builderFor(TestClientInterfaceWithDifferentExceptionConstructors.class)
      .withResponseBodyDecoder(new OptionalDecoder(new Decoder.Default()))
      .build();

  Exception genericException = decoder.decode(feignConfigKey("method1Test"),
      testResponse(errorCode, NON_NULL_BODY, NON_NULL_HEADERS));

  assertThat(genericException).isInstanceOf(expectedExceptionClass);

  ParametersException exception = (ParametersException) genericException;
  assertThat(exception.body()).isEqualTo(expectedBody);
  assertThat(exception.headers()).isEqualTo(expectedHeaders);
}
 
Example #17
Source File: AsynchronousMethodHandler.java    From feign-vertx with Apache License 2.0 6 votes vote down vote up
MethodHandler create(
    final Target<?> target,
    final MethodMetadata metadata,
    final RequestTemplate.Factory buildTemplateFromArgs,
    final Decoder decoder,
    final ErrorDecoder errorDecoder) {
  return new AsynchronousMethodHandler(
      target,
      client,
      retryer,
      requestInterceptors,
      logger,
      logLevel,
      metadata,
      buildTemplateFromArgs,
      decoder,
      errorDecoder,
      decode404);
}
 
Example #18
Source File: AsynchronousMethodHandler.java    From feign-vertx with Apache License 2.0 6 votes vote down vote up
private AsynchronousMethodHandler(
    final Target<?> target,
    final VertxHttpClient client,
    final Retryer retryer,
    final List<RequestInterceptor> requestInterceptors,
    final Logger logger,
    final Logger.Level logLevel,
    final MethodMetadata metadata,
    final RequestTemplate.Factory buildTemplateFromArgs,
    final Decoder decoder,
    final ErrorDecoder errorDecoder,
    final boolean decode404) {
  this.target = target;
  this.client = client;
  this.retryer = retryer;
  this.requestInterceptors = requestInterceptors;
  this.logger = logger;
  this.logLevel = logLevel;
  this.metadata = metadata;
  this.buildTemplateFromArgs = buildTemplateFromArgs;
  this.errorDecoder = errorDecoder;
  this.decoder = decoder;
  this.decode404 = decode404;
}
 
Example #19
Source File: DownloadClient.java    From feign-form with Apache License 2.0 6 votes vote down vote up
@Bean
public Decoder feignDecoder () {
  val springConverters = messageConverters.getObject().getConverters();
  val decoderConverters = new ArrayList<HttpMessageConverter<?>>(springConverters.size() + 1);

  decoderConverters.addAll(springConverters);
  decoderConverters.add(new SpringManyMultipartFilesReader(4096));

  val httpMessageConverters = new HttpMessageConverters(decoderConverters);

  return new SpringDecoder(new ObjectFactory<HttpMessageConverters>() {

    @Override
    public HttpMessageConverters getObject () {
        return httpMessageConverters;
    }
  });
}
 
Example #20
Source File: OptionalDecoderTests.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void simple404OptionalTest() throws IOException, InterruptedException {
  final MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse().setResponseCode(404));
  server.enqueue(new MockResponse().setBody("foo"));

  final OptionalInterface api = Feign.builder()
      .decode404()
      .decoder(new OptionalDecoder(new Decoder.Default()))
      .target(OptionalInterface.class, server.url("/").toString());

  assertThat(api.getAsOptional().isPresent()).isFalse();
  assertThat(api.getAsOptional().get()).isEqualTo("foo");
}
 
Example #21
Source File: FeignUnderAsyncTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void overrideTypeSpecificDecoder() throws Exception {
  server.enqueue(new MockResponse().setBody("success!"));

  TestInterface api = new TestInterfaceBuilder()
      .decoder(new Decoder() {
        @Override
        public Object decode(Response response, Type type) {
          return "fail";
        }
      }).target("http://localhost:" + server.getPort());

  assertEquals(api.post(), "fail");
}
 
Example #22
Source File: MeteredDecoder.java    From feign with Apache License 2.0 5 votes vote down vote up
public MeteredDecoder(Decoder decoder, MetricRegistry metricRegistry,
    MetricSuppliers metricSuppliers) {
  this.decoder = decoder;
  this.metricRegistry = metricRegistry;
  this.metricSuppliers = metricSuppliers;
  this.metricName = new FeignMetricName(Decoder.class);
}
 
Example #23
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 #24
Source File: ManuallyCreatedDelegateLoadBalancerFeignClientTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Bean
public AnnotatedFeignClient annotatedFeignClient(Client client, Decoder decoder,
		Encoder encoder, Contract contract) {
	return Feign.builder().client(client).encoder(encoder).decoder(decoder)
			.contract(contract).target(new HardCodedTarget<>(
					AnnotatedFeignClient.class, "foo", "http://foo"));
}
 
Example #25
Source File: AsyncFeignTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void okIfDecodeRootCauseHasNoMessage() throws Throwable {
  server.enqueue(new MockResponse().setBody("success!"));
  thrown.expect(DecodeException.class);

  TestInterfaceAsync api = new TestInterfaceAsyncBuilder().decoder(new Decoder() {
    @Override
    public Object decode(Response response, Type type) throws IOException {
      throw new RuntimeException();
    }
  }).target("http://localhost:" + server.getPort());

  unwrap(api.post());
}
 
Example #26
Source File: Route53Provider.java    From denominator with Apache License 2.0 5 votes vote down vote up
static Decoder decoder() {
  return SAXDecoder.builder()
      .registerContentHandler(GetHostedZoneResponseHandler.class)
      .registerContentHandler(ListHostedZonesResponseHandler.class)
      .registerContentHandler(ListResourceRecordSetsResponseHandler.class)
      .registerContentHandler(Messages.class)
      .registerContentHandler(Route53Error.class)
      .build();
}
 
Example #27
Source File: FeignBuilderTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void testOverrideDecoder() {
  server.enqueue(new MockResponse().setBody("success!"));

  String url = "http://localhost:" + server.getPort();
  Decoder decoder = (response, type) -> "fail";

  TestInterface api = Feign.builder().decoder(decoder).target(TestInterface.class, url);
  assertEquals("fail", api.decodedPost());

  assertEquals(1, server.getRequestCount());
}
 
Example #28
Source File: FeignBuilderTest.java    From feign with Apache License 2.0 5 votes vote down vote up
/**
 * This test ensures that the doNotCloseAfterDecode flag functions.
 *
 * It does so by creating a custom Decoder that lazily retrieves the response body when asked for
 * it and pops the value into an Iterator.
 *
 * Without the doNoCloseAfterDecode flag, the test will fail with a "stream is closed" exception.
 *
 */
@Test
public void testDoNotCloseAfterDecode() {
  server.enqueue(new MockResponse().setBody("success!"));

  String url = "http://localhost:" + server.getPort();
  Decoder decoder = (response, type) -> new Iterator<Object>() {
    private boolean called = false;

    @Override
    public boolean hasNext() {
      return !called;
    }

    @Override
    public Object next() {
      try {
        return Util.toString(response.body().asReader(Util.UTF_8));
      } catch (IOException e) {
        fail(e.getMessage());
        return null;
      } finally {
        Util.ensureClosed(response);
        called = true;
      }
    }
  };

  TestInterface api = Feign.builder()
      .decoder(decoder)
      .doNotCloseAfterDecode()
      .target(TestInterface.class, url);
  Iterator<String> iterator = api.decodedLazyPost();

  assertTrue(iterator.hasNext());
  assertEquals("success!", iterator.next());
  assertFalse(iterator.hasNext());

  assertEquals(1, server.getRequestCount());
}
 
Example #29
Source File: FeignConfig.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@Bean
public Decoder feignDecoder() {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
	objectMapper.registerModule(new JavaTimeModule());
	HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
	ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
	return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
}
 
Example #30
Source File: OptionalDecoderTests.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void simple204OptionalTest() throws IOException, InterruptedException {
  final MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse().setResponseCode(204));

  final OptionalInterface api = Feign.builder()
      .decoder(new OptionalDecoder(new Decoder.Default()))
      .target(OptionalInterface.class, server.url("/").toString());

  assertThat(api.getAsOptional().isPresent()).isFalse();
}