feign.codec.Encoder Java Examples

The following examples show how to use feign.codec.Encoder. 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: JAXBCodecTest.java    From feign with Apache License 2.0 7 votes vote down vote up
@Test
public void encodesXmlWithCustomJAXBSchemaLocation() throws Exception {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder()
          .withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd")
          .build();

  Encoder encoder = new JAXBEncoder(jaxbContextFactory);

  MockObject mock = new MockObject();
  mock.value = "Test";

  RequestTemplate template = new RequestTemplate();
  encoder.encode(mock, MockObject.class, template);

  assertThat(template).hasBody("<?xml version=\"1.0\" encoding=\"UTF-8\" " +
      "standalone=\"yes\"?><mockObject xsi:schemaLocation=\"http://apihost " +
      "http://apihost/schema.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
      "<value>Test</value></mockObject>");
}
 
Example #2
Source File: OpenFeignFieldLevelEncryptionEncoderTest.java    From client-encryption-java with MIT License 7 votes vote down vote up
@Test
public void testEncode_ShouldThrowEncodeException_WhenEncryptionFails() throws Exception {

    // GIVEN
    FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder()
            .withEncryptionPath("$.foo", "$.encryptedFoo")
            .withEncryptionCertificate(TestUtils.getTestInvalidEncryptionCertificate()) // Invalid certificate
            .build();
    Type type = mock(Type.class);
    Encoder delegate = mock(Encoder.class);
    Object object = mock(Object.class);
    RequestTemplate request = mock(RequestTemplate.class);
    when(request.body()).thenReturn("{\"foo\":\"bar\"}".getBytes());

    // THEN
    expectedException.expect(EncodeException.class);
    expectedException.expectMessage("Failed to intercept and encrypt request!");
    expectedException.expectCause(isA(EncryptionException.class));

    // WHEN
    OpenFeignFieldLevelEncryptionEncoder instanceUnderTest = new OpenFeignFieldLevelEncryptionEncoder(config, delegate);
    instanceUnderTest.encode(object, type, request);
}
 
Example #3
Source File: JAXBCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void encodesXmlWithCustomJAXBFormattedOutput() {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build();

  Encoder encoder = new JAXBEncoder(jaxbContextFactory);

  MockObject mock = new MockObject();
  mock.value = "Test";

  RequestTemplate template = new RequestTemplate();
  encoder.encode(mock, MockObject.class, template);

  // RequestTemplate always expects a UNIX style newline.
  assertThat(template).hasBody(
      new StringBuilder().append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
          .append("\n")
          .append("<mockObject>")
          .append("\n")
          .append("    <value>Test</value>")
          .append("\n")
          .append("</mockObject>")
          .append("\n")
          .toString());
}
 
Example #4
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 #5
Source File: OpenFeignFieldLevelEncryptionEncoderTest.java    From client-encryption-java with MIT License 6 votes vote down vote up
@Test
public void testEncode_ShouldDoNothing_WhenNoPayload() throws Exception {

    // GIVEN
    FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder()
            .withEncryptionPath("$.foo", "$.encryptedFoo")
            .build();
    Type type = mock(Type.class);
    Encoder delegate = mock(Encoder.class);
    Object object = mock(Object.class);
    RequestTemplate request = mock(RequestTemplate.class);
    when(request.body()).thenReturn(null);

    // WHEN
    OpenFeignFieldLevelEncryptionEncoder instanceUnderTest = new OpenFeignFieldLevelEncryptionEncoder(config, delegate);
    instanceUnderTest.encode(object, type, request);

    // THEN
    verify(request).body();
    verifyNoMoreInteractions(request);
}
 
Example #6
Source File: OpenFeignFieldLevelEncryptionEncoderTest.java    From client-encryption-java with MIT License 6 votes vote down vote up
@Test
public void testEncode_ShouldDoNothing_WhenEmptyPayload() throws Exception {

    // GIVEN
    FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder()
            .withEncryptionPath("$.foo", "$.encryptedFoo")
            .build();
    Type type = mock(Type.class);
    Encoder delegate = mock(Encoder.class);
    Object object = mock(Object.class);
    RequestTemplate request = mock(RequestTemplate.class);
    when(request.body()).thenReturn("".getBytes());

    // WHEN
    OpenFeignFieldLevelEncryptionEncoder instanceUnderTest = new OpenFeignFieldLevelEncryptionEncoder(config, delegate);
    instanceUnderTest.encode(object, type, request);

    // THEN
    verify(request).body();
    verifyNoMoreInteractions(request);
}
 
Example #7
Source File: MethodMetadataPresenceTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void encoder() throws Exception {
  server.enqueue(new MockResponse().setBody("response data"));

  final String url = "http://localhost:" + server.getPort();
  final TestInterface api = Feign.builder()
      .encoder((object, bodyType, template) -> {
        assertNotNull(template);
        assertNotNull(template.methodMetadata());
        assertNotNull(template.feignTarget());
        new Encoder.Default().encode(object, bodyType, template);
      })
      .target(TestInterface.class, url);

  final Response response = api.codecPost("request data");
  assertEquals("response data", Util.toString(response.body().asReader(Util.UTF_8)));

  assertThat(server.takeRequest())
      .hasBody("request data");
}
 
Example #8
Source File: FeignUnderAsyncTest.java    From feign with Apache License 2.0 6 votes vote down vote up
/**
 * The type of a parameter value may not be the desired type to encode as. Prefer the interface
 * type.
 */
@Test
public void bodyTypeCorrespondsWithParameterType() throws Exception {
  server.enqueue(new MockResponse().setBody("foo"));

  final AtomicReference<Type> encodedType = new AtomicReference<>();
  TestInterface api = new TestInterfaceBuilder()
      .encoder(new Encoder.Default() {
        @Override
        public void encode(Object object, Type bodyType, RequestTemplate template) {
          encodedType.set(bodyType);
        }
      })
      .target("http://localhost:" + server.getPort());

  api.body(Arrays.asList("netflix", "denominator", "password"));

  server.takeRequest();

  assertThat(encodedType.get()).isEqualTo(new TypeToken<List<String>>() {}.getType());
}
 
Example #9
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
/**
 * The type of a parameter value may not be the desired type to encode as. Prefer the interface
 * type.
 */
@Test
public void bodyTypeCorrespondsWithParameterType() throws Exception {
  server.enqueue(new MockResponse().setBody("foo"));

  final AtomicReference<Type> encodedType = new AtomicReference<>();
  TestInterface api = new TestInterfaceBuilder()
      .encoder(new Encoder.Default() {
        @Override
        public void encode(Object object, Type bodyType, RequestTemplate template) {
          encodedType.set(bodyType);
        }
      })
      .target("http://localhost:" + server.getPort());

  api.body(Arrays.asList("netflix", "denominator", "password"));

  server.takeRequest();

  assertThat(encodedType.get()).isEqualTo(new TypeToken<List<String>>() {}.getType());
}
 
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: FeignClientsConfiguration.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
@ConditionalOnMissingBean
public Encoder feignEncoderPageable(
		ObjectProvider<AbstractFormWriter> formWriterProvider) {
	PageableSpringEncoder encoder = new PageableSpringEncoder(
			springEncoder(formWriterProvider));

	if (springDataWebProperties != null) {
		encoder.setPageParameter(
				springDataWebProperties.getPageable().getPageParameter());
		encoder.setSizeParameter(
				springDataWebProperties.getPageable().getSizeParameter());
		encoder.setSortParameter(
				springDataWebProperties.getSort().getSortParameter());
	}
	return encoder;
}
 
Example #12
Source File: AsyncFeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
/**
 * The type of a parameter value may not be the desired type to encode as. Prefer the interface
 * type.
 */
@Test
public void bodyTypeCorrespondsWithParameterType() throws Exception {
  server.enqueue(new MockResponse().setBody("foo"));

  final AtomicReference<Type> encodedType = new AtomicReference<Type>();
  TestInterfaceAsync api = new TestInterfaceAsyncBuilder().encoder(new Encoder.Default() {
    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) {
      encodedType.set(bodyType);
    }
  }).target("http://localhost:" + server.getPort());

  CompletableFuture<?> cf = api.body(Arrays.asList("netflix", "denominator", "password"));

  server.takeRequest();

  assertThat(encodedType.get()).isEqualTo(new TypeToken<List<String>>() {}.getType());

  checkCFCompletedSoon(cf);
}
 
Example #13
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 #14
Source File: PageableEncoderTests.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Test
public void testPaginationAndSortingRequest() {
	Encoder encoder = this.context.getInstance("foo", Encoder.class);
	assertThat(encoder).isNotNull();
	RequestTemplate request = new RequestTemplate();
	encoder.encode(createPageAndSortRequest(), null, request);

	// Request queries shall contain three entries
	assertThat(request.queries()).hasSize(3);
	// Request page shall contain page
	assertThat(request.queries().get("page")).contains(String.valueOf(PAGE));
	// Request size shall contain size
	assertThat(request.queries().get("size")).contains(String.valueOf(SIZE));
	// Request sort size shall contain sort entries
	assertThat(request.queries().get("sort")).hasSize(2);
}
 
Example #15
Source File: SpringEncoderTests.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomHttpMessageConverter() {
	Encoder encoder = this.context.getInstance("foo", Encoder.class);
	assertThat(encoder).isNotNull();
	RequestTemplate request = new RequestTemplate();

	encoder.encode("hi", MyType.class, request);

	Collection<String> contentTypeHeader = request.headers().get("Content-Type");
	assertThat(contentTypeHeader).as("missing content type header").isNotNull();
	assertThat(contentTypeHeader.isEmpty()).as("missing content type header")
			.isFalse();

	String header = contentTypeHeader.iterator().next();
	assertThat(header).as("content type header is wrong")
			.isEqualTo("application/mytype");

	assertThat(request.requestCharset()).as("request charset is null").isNotNull();
	assertThat(request.requestCharset()).as("request charset is wrong")
			.isEqualTo(StandardCharsets.UTF_8);
}
 
Example #16
Source File: GitHubExample.java    From feign with Apache License 2.0 6 votes vote down vote up
static GitHub connect() {
  final Decoder decoder = new GsonDecoder();
  final Encoder encoder = new GsonEncoder();
  return Feign.builder()
      .encoder(encoder)
      .decoder(decoder)
      .errorDecoder(new GitHubErrorDecoder(decoder))
      .logger(new Logger.ErrorLogger())
      .logLevel(Logger.Level.BASIC)
      .requestInterceptor(template -> {
        template.header(
            // not available when building PRs...
            // https://docs.travis-ci.com/user/environment-variables/#defining-encrypted-variables-in-travisyml
            "Authorization",
            "token 383f1c1b474d8f05a21e7964976ab0d403fee071");
      })
      .target(GitHub.class, "https://api.github.com");
}
 
Example #17
Source File: SOAPCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodeAnnotatedParameterizedTypes() throws Exception {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build();

  Encoder encoder = new SOAPEncoder(jaxbContextFactory);

  Box<String> boxStr = new Box<>();
  boxStr.set("hello");
  Box<Box<String>> boxBoxStr = new Box<>();
  boxBoxStr.set(boxStr);
  RequestTemplate template = new RequestTemplate();
  encoder.encode(boxBoxStr, Box.class, template);

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(template.body())
      .build();

  new SOAPDecoder(new JAXBContextFactory.Builder().build()).decode(response, Box.class);

}
 
Example #18
Source File: SOAPCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void encodesSoapWithCustomJAXBNoSchemaLocation() {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder()
          .withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd")
          .build();

  Encoder encoder = new SOAPEncoder(jaxbContextFactory);

  GetPrice mock = new GetPrice();
  mock.item = new Item();
  mock.item.value = "Apples";

  RequestTemplate template = new RequestTemplate();
  encoder.encode(mock, GetPrice.class, template);

  assertThat(template).hasBody("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
      + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
      + "<SOAP-ENV:Header/>"
      + "<SOAP-ENV:Body>"
      + "<GetPrice xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://apihost/schema.xsd\">"
      + "<Item>Apples</Item>"
      + "</GetPrice>"
      + "</SOAP-ENV:Body>"
      + "</SOAP-ENV:Envelope>");
}
 
Example #19
Source File: SOAPCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void encodesSoapWithCustomJAXBSchemaLocation() {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder()
          .withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd")
          .build();

  Encoder encoder = new SOAPEncoder(jaxbContextFactory);

  GetPrice mock = new GetPrice();
  mock.item = new Item();
  mock.item.value = "Apples";

  RequestTemplate template = new RequestTemplate();
  encoder.encode(mock, GetPrice.class, template);

  assertThat(template).hasBody("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
      + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
      + "<SOAP-ENV:Header/>"
      + "<SOAP-ENV:Body>"
      + "<GetPrice xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://apihost http://apihost/schema.xsd\">"
      + "<Item>Apples</Item>"
      + "</GetPrice>"
      + "</SOAP-ENV:Body>"
      + "</SOAP-ENV:Envelope>");
}
 
Example #20
Source File: BuildTemplateByResolvingArgs.java    From feign-vertx with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestTemplate resolve(
    final Object[] argv,
    final RequestTemplate mutable,
    final Map<String, Object> variables) {
  final Map<String, Object> formVariables = new HashMap<>();

  for (final Map.Entry<String, Object> entry : variables.entrySet()) {
    if (metadata.formParams().contains(entry.getKey())) {
      formVariables.put(entry.getKey(), entry.getValue());
    }
  }

  try {
    encoder.encode(formVariables, Encoder.MAP_STRING_WILDCARD, mutable);
  } catch (final EncodeException encodeException) {
    throw encodeException;
  } catch (final RuntimeException unexpectedException) {
    throw new EncodeException(unexpectedException.getMessage(), unexpectedException);
  }

  return super.resolve(argv, mutable, variables);
}
 
Example #21
Source File: SOAPCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void encodesSoap() {
  Encoder encoder = new SOAPEncoder.Builder()
      .withJAXBContextFactory(new JAXBContextFactory.Builder().build())
      .build();

  GetPrice mock = new GetPrice();
  mock.item = new Item();
  mock.item.value = "Apples";

  RequestTemplate template = new RequestTemplate();
  encoder.encode(mock, GetPrice.class, template);

  String soapEnvelop = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" +
      "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
      "<SOAP-ENV:Header/>" +
      "<SOAP-ENV:Body>" +
      "<GetPrice>" +
      "<Item>Apples</Item>" +
      "</GetPrice>" +
      "</SOAP-ENV:Body>" +
      "</SOAP-ENV:Envelope>";
  assertThat(template).hasBody(soapEnvelop);
}
 
Example #22
Source File: JAXBCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodeAnnotatedParameterizedTypes() throws Exception {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build();

  Encoder encoder = new JAXBEncoder(jaxbContextFactory);

  Box<String> boxStr = new Box<>();
  boxStr.set("hello");
  Box<Box<String>> boxBoxStr = new Box<>();
  boxBoxStr.set(boxStr);
  RequestTemplate template = new RequestTemplate();
  encoder.encode(boxBoxStr, Box.class, template);

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.<String, Collection<String>>emptyMap())
      .body(template.body())
      .build();

  new JAXBDecoder(new JAXBContextFactory.Builder().build()).decode(response, Box.class);

}
 
Example #23
Source File: JAXBCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void encodesXmlWithCustomJAXBEncoding() throws Exception {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build();

  Encoder encoder = new JAXBEncoder(jaxbContextFactory);

  MockObject mock = new MockObject();
  mock.value = "Test";

  RequestTemplate template = new RequestTemplate();
  encoder.encode(mock, MockObject.class, template);

  assertThat(template).hasBody("<?xml version=\"1.0\" encoding=\"UTF-16\" "
      + "standalone=\"yes\"?><mockObject><value>Test</value></mockObject>");
}
 
Example #24
Source File: JAXBCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void encodesXmlWithCustomJAXBNoNamespaceSchemaLocation() throws Exception {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder()
          .withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd").build();

  Encoder encoder = new JAXBEncoder(jaxbContextFactory);

  MockObject mock = new MockObject();
  mock.value = "Test";

  RequestTemplate template = new RequestTemplate();
  encoder.encode(mock, MockObject.class, template);

  assertThat(template)
      .hasBody(
          "<?xml version=\"1.0\" encoding=\"UTF-8\" "
              + "standalone=\"yes\"?><mockObject xsi:noNamespaceSchemaLocation=\"http://apihost/schema.xsd\" "
              + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
              + "<value>Test</value></mockObject>");
}
 
Example #25
Source File: SpringEncoderTests.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipartFile2() {
	Encoder encoder = this.context.getInstance("foo", Encoder.class);
	assertThat(encoder).isNotNull();
	RequestTemplate request = new RequestTemplate();
	request.header(ACCEPT, MediaType.MULTIPART_FORM_DATA_VALUE);
	request.header(CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);

	MultipartFile multipartFile = new MockMultipartFile("test_multipart_file",
			"hi".getBytes());
	encoder.encode(multipartFile, MultipartFile.class, request);

	assertThat((String) ((List) request.headers().get(CONTENT_TYPE)).get(0))
			.as("Request Content-Type is not multipart/form-data")
			.contains("multipart/form-data; charset=UTF-8; boundary=");
	assertThat(request.headers().get(CONTENT_TYPE).size())
			.as("There is more than one Content-Type request header").isEqualTo(1);
	assertThat(((List) request.headers().get(ACCEPT)).get(0))
			.as("Request Accept header is not multipart/form-data")
			.isEqualTo(MULTIPART_FORM_DATA_VALUE);
	assertThat(((List) request.headers().get(CONTENT_LENGTH)).get(0))
			.as("Request Content-Length is not equal to 186").isEqualTo("186");
	assertThat(new String(request.requestBody().asBytes()))
			.as("Body content cannot be decoded").contains("hi");
}
 
Example #26
Source File: VertxFeign.java    From feign-vertx with Apache License 2.0 5 votes vote down vote up
private ParseHandlersByName(
    final Contract contract,
    final HttpClientOptions options,
    final Encoder encoder,
    final Decoder decoder,
    final ErrorDecoder errorDecoder,
    final AsynchronousMethodHandler.Factory factory) {
  this.contract = contract;
  this.options = options;
  this.factory = factory;
  this.errorDecoder = errorDecoder;
  this.encoder = encoder;
  this.decoder = decoder;
}
 
Example #27
Source File: TppUiBeFeignConfiguration.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@Bean
public Encoder feignEncoder() {
    objectMapper.addMixIn(ScaUserDataTO.class, ScaUserDataMixedIn.class)
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
    ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
    return new SpringEncoder(objectFactory);
}
 
Example #28
Source File: FeignTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void okIfEncodeRootCauseHasNoMessage() throws Exception {
  server.enqueue(new MockResponse().setBody("success!"));
  thrown.expect(EncodeException.class);

  TestInterface api = new TestInterfaceBuilder()
      .encoder(new Encoder() {
        @Override
        public void encode(Object object, Type bodyType, RequestTemplate template) {
          throw new RuntimeException();
        }
      }).target("http://localhost:" + server.getPort());

  api.body(Arrays.asList("foo"));
}
 
Example #29
Source File: MultipartFormContentProcessor.java    From feign-form with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor with specific delegate encoder.
 *
 * @param delegate specific delegate encoder for cases, when this processor couldn't handle request parameter.
 */
public MultipartFormContentProcessor (Encoder delegate) {
  writers = new LinkedList<Writer>();
  addWriter(new ByteArrayWriter());
  addWriter(new FormDataWriter());
  addWriter(new SingleFileWriter());
  addWriter(new ManyFilesWriter());
  addWriter(new SingleParameterWriter());
  addWriter(new ManyParametersWriter());
  addWriter(new PojoWriter(writers));

  defaultPerocessor = new DelegateWriter(delegate);
}
 
Example #30
Source File: FormEncoder.java    From feign-form with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor with specified delegate encoder.
 *
 * @param delegate  delegate encoder, if this encoder couldn't encode object.
 */
public FormEncoder (Encoder delegate) {
  this.delegate = delegate;

  val list = asList(
      new MultipartFormContentProcessor(delegate),
      new UrlencodedFormContentProcessor()
  );

  processors = new HashMap<ContentType, ContentProcessor>(list.size(), 1.F);
  for (ContentProcessor processor : list) {
    processors.put(processor.getSupportedContentType(), processor);
  }
}