Java Code Examples for feign.codec.Decoder

The following examples show how to use feign.codec.Decoder. These examples are extracted from open source projects. 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
@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 2
@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 3
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 4
@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 5
Source Project: feign-form   Source File: DownloadClient.java    License: 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 6
Source Project: feign-vertx   Source File: AsynchronousMethodHandler.java    License: 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 7
Source Project: feign-vertx   Source File: AsynchronousMethodHandler.java    License: 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 8
Source Project: intellij-swagger   Source File: HttpZallyService.java    License: 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 9
Source Project: feign   Source File: BaseApiTest.java    License: 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 10
Source Project: feign   Source File: FeignTest.java    License: 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 11
Source Project: denominator   Source File: UltraDNSProvider.java    License: 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 12
Source Project: feign   Source File: BaseApiTest.java    License: 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 13
Source Project: feign   Source File: FeignTest.java    License: 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 14
Source Project: feign   Source File: FeignUnderAsyncTest.java    License: 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 15
Source Project: feign   Source File: FeignUnderAsyncTest.java    License: 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 16
Source Project: feign   Source File: Feign.java    License: 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 17
Source Project: feign   Source File: AsyncFeignTest.java    License: 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 18
Source Project: feign   Source File: AsyncFeignTest.java    License: 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 19
Source Project: XS2A-Sandbox   Source File: FeignConfig.java    License: 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 20
@Test
public void testDecode_ShouldThrowDecodeException_WhenDecryptionFails() throws Exception {

    // GIVEN
    String encryptedPayload = "{" +
            "    \"encryptedData\": {" +
            "        \"iv\": \"a2c494ca28dec4f3d6ce7d68b1044cfe\"," +
            "        \"encryptedKey\": \"NOT A VALID KEY!\"," +
            "        \"encryptedValue\": \"0672589113046bf692265b6ea6088184\"" +
            "    }" +
            "}";
    FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder()
            .withDecryptionPath("$.encryptedData", "$.data")
            .build();
    Type type = mock(Type.class);
    Response response = mock(Response.class);
    when(response.body()).thenReturn(buildResponseBody(encryptedPayload));
    Decoder delegate = mock(Decoder.class);

    // THEN
    expectedException.expect(DecodeException.class);
    expectedException.expectMessage("Failed to intercept and decrypt response!");
    expectedException.expectCause(isA(EncryptionException.class));

    // WHEN
    OpenFeignFieldLevelEncryptionDecoder instanceUnderTest = new OpenFeignFieldLevelEncryptionDecoder(config, delegate);
    instanceUnderTest.decode(response, type);
}
 
Example 21
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    applicationContext.getBeanFactory().registerSingleton("summerErrorAdapterApiResultHandler",
        new SummerErrorAdapterApiResultHandler());
    applicationContext.getBeanFactory().registerSingleton("summer2ErrorApiResultHandler",
        new Summer2ErrorApiResultHandler());
    applicationContext.getBeanFactory().addBeanPostProcessor(new InstantiationAwareBeanPostProcessorAdapter() {
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof Decoder && !(bean instanceof ApiResultDecoder)) {
                Decoder decode = (Decoder)bean;
                return new ApiResultDecoder(decode, applicationContext.getBeansOfType(ApiResultHandler.class)
                    .values().stream().collect(Collectors.toList()));
            } else if (bean instanceof RequestParamMethodArgumentResolver) {
                RequestParamMethodArgumentResolver requestParamMethodArgumentResolver =
                    (RequestParamMethodArgumentResolver)bean;
                Field useDefaultResolution = ReflectionUtils.findField(RequestParamMethodArgumentResolver.class,
                    "useDefaultResolution", RequestParamMethodArgumentResolver.class);
                ReflectionUtils.makeAccessible(useDefaultResolution);
                Boolean useDefaultResolutionValue =
                    (Boolean)ReflectionUtils.getField(useDefaultResolution, requestParamMethodArgumentResolver);
                return new RequestParamMethodArgumentResolverExt(useDefaultResolutionValue);
            } else {
                return bean;
            }

        }
    });

}
 
Example 22
Source Project: summerframework   Source File: ApiResultDecoder.java    License: Apache License 2.0 5 votes vote down vote up
public ApiResultDecoder(Decoder delegate, List<ApiResultHandler> apiResultHandlers) {
    Assert.notEmpty(apiResultHandlers, "List<ApiResultHandler> must not be empty");
    Objects.requireNonNull(delegate, "Decoder must not be null. ");
    this.delegate = delegate;
    mapper = new ObjectMapper();
    this.apiResultHandlers = apiResultHandlers;
}
 
Example 23
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty("feign.compression.response.useGzipDecoder")
public Decoder defaultGzipDecoder() {
	return new OptionalDecoder(new ResponseEntityDecoder(
			new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
}
 
Example 24
Source Project: denominator   Source File: Route53Provider.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
Feign feign(Logger logger, Logger.Level logLevel) {
  Decoder decoder = decoder();
  return Feign.builder()
      .logger(logger)
      .logLevel(logLevel)
      .encoder(new EncodeChanges())
      .decoder(decoder)
      .errorDecoder(new Route53ErrorDecoder(decoder))
      .build();
}
 
Example 25
Source Project: feign   Source File: FeignUnderAsyncTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void okIfDecodeRootCauseHasNoMessage() throws Exception {
  server.enqueue(new MockResponse().setBody("success!"));
  thrown.expect(DecodeException.class);

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

  api.post();
}
 
Example 26
Source Project: zuihou-admin-cloud   Source File: CorsConfiguration.java    License: Apache License 2.0 5 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 27
ExceptionGenerator(Integer bodyIndex, Integer requestIndex, Integer headerMapIndex,
    Integer numOfParams, Type bodyType,
    Class<? extends Exception> exceptionType, Decoder bodyDecoder) {
  this.bodyIndex = bodyIndex;
  this.requestIndex = requestIndex;
  this.headerMapIndex = headerMapIndex;
  this.numOfParams = numOfParams;
  this.bodyType = bodyType;
  this.exceptionType = exceptionType;
  this.bodyDecoder = bodyDecoder;
}
 
Example 28
static ErrorHandlingDefinition readAnnotation(ErrorHandling errorHandling,
                                              Decoder responseBodyDecoder) {
  ExceptionGenerator defaultException = new ExceptionGenerator.Builder()
      .withResponseBodyDecoder(responseBodyDecoder)
      .withExceptionType(errorHandling.defaultException())
      .build();
  Map<Integer, ExceptionGenerator> statusCodesDefinition =
      new HashMap<Integer, ExceptionGenerator>();

  for (ErrorCodes statusCodeDefinition : errorHandling.codeSpecific()) {
    for (int statusCode : statusCodeDefinition.codes()) {
      if (statusCodesDefinition.containsKey(statusCode)) {
        throw new IllegalStateException(
            "Status Code [" + statusCode + "] " +
                "has already been declared to throw ["
                + statusCodesDefinition.get(statusCode).getExceptionType().getName() + "] " +
                "and [" + statusCodeDefinition.generate() + "] - dupe definition");
      }
      statusCodesDefinition.put(statusCode,
          new ExceptionGenerator.Builder()
              .withResponseBodyDecoder(responseBodyDecoder)
              .withExceptionType(statusCodeDefinition.generate())
              .build());
    }
  }

  return new ErrorHandlingDefinition(defaultException, statusCodesDefinition);
}
 
Example 29
@Test
public void testIfExceptionIsNotInTheList() throws Exception {
  AnnotationErrorDecoder decoder = AnnotationErrorDecoder
      .builderFor(TestClientInterfaceWithDifferentExceptionConstructors.class)
      .withResponseBodyDecoder(new OptionalDecoder(new Decoder.Default()))
      .build();

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

  assertThat(genericException)
      .isInstanceOf(ErrorHandling.NO_DEFAULT.class)
      .hasMessage("Endpoint responded with -1, reason: null");
}
 
Example 30
@Autowired
public MovieController(Decoder decoder, Encoder encoder, Client client, Contract contract) {
  // 这边的decoder、encoder、client、contract,可以debug看看是什么实例。
  this.userUserFeignClient = Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract)
      .requestInterceptor(new BasicAuthRequestInterceptor("user", "password1")).target(UserFeignClient.class, "http://microservice-provider-user/");
  this.adminUserFeignClient = Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract)
      .requestInterceptor(new BasicAuthRequestInterceptor("admin", "password2"))
      .target(UserFeignClient.class, "http://microservice-provider-user/");
}