Java源码示例:feign.Request.HttpMethod

示例1
@Test
public void decodes() throws Exception {

  List<Zone> zones = new LinkedList<Zone>();
  zones.add(new Zone("denominator.io."));
  zones.add(new Zone("denominator.io.", "ABCD"));

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .headers(Collections.emptyMap())
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .body(zonesJson, UTF_8)
      .build();
  assertEquals(zones,
      new GsonDecoder().decode(response, new TypeToken<List<Zone>>() {}.getType()));
}
 
示例2
@Test
public void customDecoder() throws Exception {
  GsonDecoder decoder = new GsonDecoder(Collections.singletonList(upperZone));

  List<Zone> zones = new LinkedList<>();
  zones.add(new Zone("DENOMINATOR.IO."));
  zones.add(new Zone("DENOMINATOR.IO.", "ABCD"));

  Response response =
      Response.builder()
          .status(200)
          .reason("OK")
          .headers(Collections.emptyMap())
          .request(
              Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
          .body(zonesJson, UTF_8)
          .build();
  assertEquals(zones, decoder.decode(response, new TypeToken<List<Zone>>() {}.getType()));
}
 
示例3
@SuppressWarnings("deprecation")
@Test
public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable {
  final Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>();
  headers.put("Location", Arrays.asList("http://bar.com"));
  final Response response = Response.builder().status(302).reason("Found").headers(headers)
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0]).build();

  final ExecutorService execs = Executors.newSingleThreadExecutor();

  // fake client as Client.Default follows redirects.
  final TestInterfaceAsync api = AsyncFeign.<Void>asyncBuilder()
      .client(new AsyncClient.Default<>((request, options) -> response, execs))
      .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort());

  assertEquals(Collections.singletonList("http://bar.com"),
      unwrap(api.response()).headers().get("Location"));

  execs.shutdown();
}
 
示例4
@Test
public void testRibbonRequest() throws URISyntaxException {
  // test for RibbonRequest.toRequest()
  // the url has a query whose value is an encoded json string
  String urlWithEncodedJson = "http://test.feign.com/p?q=%7b%22a%22%3a1%7d";
  HttpMethod method = HttpMethod.GET;
  URI uri = new URI(urlWithEncodedJson);
  Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>();
  // create a Request for recreating another Request by toRequest()
  Request requestOrigin =
      Request.create(method, uri.toASCIIString(), headers, null, Charset.forName("utf-8"));
  RibbonRequest ribbonRequest = new RibbonRequest(null, requestOrigin, uri);

  // use toRequest() recreate a Request
  Request requestRecreate = ribbonRequest.toRequest();

  // test that requestOrigin and requestRecreate are same except the header 'Content-Length'
  // ps, requestOrigin and requestRecreate won't be null
  assertThat(requestOrigin.toString())
      .contains(String.format("%s %s HTTP/1.1\n", method, urlWithEncodedJson));
  assertThat(requestRecreate.toString())
      .contains(String.format("%s %s HTTP/1.1\nContent-Length: 0\n", method, urlWithEncodedJson));
}
 
示例5
@Test
public void decodesXml() throws Exception {
  MockObject mock = new MockObject();
  mock.value = "Test";

  String mockXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mockObject>"
      + "<value>Test</value></mockObject>";

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

  JAXBDecoder decoder = new JAXBDecoder(new JAXBContextFactory.Builder().build());

  assertEquals(mock, decoder.decode(response, MockObject.class));
}
 
示例6
@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);

}
 
示例7
@Test
public void soapDecoderThrowsSOAPFaultException() throws IOException {

  thrown.expect(SOAPFaultException.class);
  thrown.expectMessage("Processing error");

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

  new SOAPDecoder.Builder().withSOAPProtocol(SOAPConstants.SOAP_1_2_PROTOCOL)
      .withJAXBContextFactory(new JAXBContextFactory.Builder().build()).build()
      .decode(response, Object.class);
}
 
示例8
@Test
public void errorDecoderReturnsFeignExceptionOn503Status() throws IOException {
  Response response = Response.builder()
      .status(503)
      .reason("Service Unavailable")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body("Service Unavailable", UTF_8)
      .build();

  Exception error =
      new SOAPErrorDecoder().decode("Service#foo()", response);

  Assertions.assertThat(error).isInstanceOf(FeignException.class)
      .hasMessage(
          "[503 Service Unavailable] during [GET] to [/api] [Service#foo()]: [Service Unavailable]");
}
 
示例9
@Test
public void errorDecoderReturnsFeignExceptionOnEmptyFault() throws IOException {
  String responseBody = "<?xml version = '1.0' encoding = 'UTF-8'?>\n" +
      "<SOAP-ENV:Envelope\n" +
      "   xmlns:SOAP-ENV = \"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
      "   xmlns:xsi = \"http://www.w3.org/1999/XMLSchema-instance\"\n" +
      "   xmlns:xsd = \"http://www.w3.org/1999/XMLSchema\">\n" +
      "   <SOAP-ENV:Body>\n" +
      "   </SOAP-ENV:Body>\n" +
      "</SOAP-ENV:Envelope>";
  Response response = Response.builder()
      .status(500)
      .reason("Internal Server Error")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(responseBody, UTF_8)
      .build();

  Exception error =
      new SOAPErrorDecoder().decode("Service#foo()", response);

  Assertions.assertThat(error).isInstanceOf(FeignException.class)
      .hasMessage("[500 Internal Server Error] during [GET] to [/api] [Service#foo()]: ["
          + responseBody + "]");
}
 
示例10
@Test
public void throwsOriginalExceptionAfterFailedRetries() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2"));

  final String message = "the innerest";
  thrown.expect(TestInterfaceException.class);
  thrown.expectMessage(message);

  TestInterface api = Feign.builder()
      .exceptionPropagationPolicy(UNWRAP)
      .retryer(new Retryer.Default(1, 1, 2))
      .errorDecoder(new ErrorDecoder() {
        @Override
        public Exception decode(String methodKey, Response response) {
          return new RetryableException(response.status(), "play it again sam!", HttpMethod.POST,
              new TestInterfaceException(message), null, response.request());
        }
      }).target(TestInterface.class, "http://localhost:" + server.getPort());

  api.post();
}
 
示例11
@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);

}
 
示例12
/**
 * when you must parse a 2xx status to determine if the operation succeeded or not.
 */
@Test
public void retryableExceptionInDecoder() throws Exception {
  server.enqueue(new MockResponse().setBody("retry!"));
  server.enqueue(new MockResponse().setBody("success!"));

  TestInterface api = new TestInterfaceBuilder()
      .decoder(new StringDecoder() {
        @Override
        public Object decode(Response response, Type type) throws IOException {
          String string = super.decode(response, type).toString();
          if ("retry!".equals(string)) {
            throw new RetryableException(response.status(), string, HttpMethod.POST, null,
                response.request());
          }
          return string;
        }
      }).target("http://localhost:" + server.getPort());

  assertEquals(api.post(), "success!");
  assertEquals(2, server.getRequestCount());
}
 
示例13
@Test
public void decodes() throws Exception {
  List<Zone> zones = new LinkedList<>();
  zones.add(new Zone("denominator.io."));
  zones.add(new Zone("denominator.io.", "ABCD"));

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(zonesJson, UTF_8)
      .build();
  assertEquals(zones,
      new JacksonDecoder().decode(response, new TypeReference<List<Zone>>() {}.getType()));
}
 
示例14
@Test
public void customDecoder() throws Exception {
  JacksonDecoder decoder = new JacksonDecoder(
      Arrays.asList(
          new SimpleModule().addDeserializer(Zone.class, new ZoneDeserializer())));

  List<Zone> zones = new LinkedList<Zone>();
  zones.add(new Zone("DENOMINATOR.IO."));
  zones.add(new Zone("DENOMINATOR.IO.", "ABCD"));

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(zonesJson, UTF_8)
      .build();
  assertEquals(zones, decoder.decode(response, new TypeReference<List<Zone>>() {}.getType()));
}
 
示例15
@Test
public void decodesIterator() throws Exception {
  List<Zone> zones = new LinkedList<Zone>();
  zones.add(new Zone("denominator.io."));
  zones.add(new Zone("denominator.io.", "ABCD"));

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(zonesJson, UTF_8)
      .build();
  Object decoded = JacksonIteratorDecoder.create().decode(response,
      new TypeReference<Iterator<Zone>>() {}.getType());
  assertTrue(Iterator.class.isAssignableFrom(decoded.getClass()));
  assertTrue(Closeable.class.isAssignableFrom(decoded.getClass()));
  assertEquals(zones, asList((Iterator<?>) decoded));
}
 
示例16
/**
 * Create a new Request Template.
 *
 * @param fragment part of the request uri.
 * @param target for the template.
 * @param uriTemplate for the template.
 * @param bodyTemplate for the template, may be {@literal null}
 * @param method of the request.
 * @param charset for the request.
 * @param body of the request, may be {@literal null}
 * @param decodeSlash if the request uri should encode slash characters.
 * @param collectionFormat when expanding collection based variables.
 * @param feignTarget this template is targeted for.
 * @param methodMetadata containing a reference to the method this template is built from.
 */
private RequestTemplate(String target,
    String fragment,
    UriTemplate uriTemplate,
    BodyTemplate bodyTemplate,
    HttpMethod method,
    Charset charset,
    Request.Body body,
    boolean decodeSlash,
    CollectionFormat collectionFormat,
    MethodMetadata methodMetadata,
    Target<?> feignTarget) {
  this.target = target;
  this.fragment = fragment;
  this.uriTemplate = uriTemplate;
  this.bodyTemplate = bodyTemplate;
  this.method = method;
  this.charset = charset;
  this.body = body;
  this.decodeSlash = decodeSlash;
  this.collectionFormat =
      (collectionFormat != null) ? collectionFormat : CollectionFormat.EXPLODED;
  this.methodMetadata = methodMetadata;
  this.feignTarget = feignTarget;
}
 
示例17
@Test
public void whenReturnTypeIsResponseNoErrorHandling() {
  Map<String, Collection<String>> headers = new LinkedHashMap<>();
  headers.put("Location", Collections.singletonList("http://bar.com"));
  final Response response = Response.builder()
      .status(302)
      .reason("Found")
      .headers(headers)
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0])
      .build();

  // fake client as Client.Default follows redirects.
  TestInterface api = Feign.builder()
      .client((request, options) -> response)
      .target(TestInterface.class, "http://localhost:" + server.getPort());

  assertEquals(api.response().headers().get("Location"),
      Collections.singletonList("http://bar.com"));
}
 
示例18
@SuppressWarnings("deprecation")
@Test
public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable {
  Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>();
  headers.put("Location", Arrays.asList("http://bar.com"));
  final Response response = Response.builder().status(302).reason("Found").headers(headers)
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0]).build();

  ExecutorService execs = Executors.newSingleThreadExecutor();

  // fake client as Client.Default follows redirects.
  TestInterfaceAsync api = AsyncFeign.<Void>asyncBuilder()
      .client(new AsyncClient.Default<>((request, options) -> response, execs))
      .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort());

  assertEquals(Collections.singletonList("http://bar.com"),
      unwrap(api.response()).headers().get("Location"));

  execs.shutdown();
}
 
示例19
@Test
public void shouldCloseIteratorWhenStreamClosed() throws IOException {
  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .headers(Collections.emptyMap())
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .body("", UTF_8)
      .build();

  TestCloseableIterator it = new TestCloseableIterator();
  StreamDecoder decoder = new StreamDecoder((r, t) -> it);

  try (Stream<?> stream =
      (Stream) decoder.decode(response, new TypeReference<Stream<String>>() {}.getType())) {
    assertThat(stream.collect(Collectors.toList())).hasSize(1);
    assertThat(it.called).isTrue();
  } finally {
    assertThat(it.closed).isTrue();
  }
}
 
示例20
@Test
public void throwsFeignExceptionIncludingBody() throws Throwable {
  Response response = Response.builder()
      .status(500)
      .reason("Internal server error")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(headers)
      .body("hello world", UTF_8)
      .build();

  try {
    throw errorDecoder.decode("Service#foo()", response);
  } catch (FeignException e) {
    assertThat(e.getMessage())
        .isEqualTo(
            "[500 Internal server error] during [GET] to [/api] [Service#foo()]: [hello world]");
    assertThat(e.contentUTF8()).isEqualTo("hello world");
  }
}
 
示例21
@Test
public void insertHasQueryParams() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.GET)//
      .uri("/domains/1001/records")//
      .query("name", "denominator.io")//
      .query("type", "CNAME");

  template.target("https://host/v1.0/1234?provider=foo");

  assertThat(template)
      .hasPath("https://host/v1.0/1234/domains/1001/records")
      .hasQueries(
          entry("name", Collections.singletonList("denominator.io")),
          entry("type", Collections.singletonList("CNAME")),
          entry("provider", Collections.singletonList("foo")));
}
 
示例22
@Test
public void resolveTemplateWithBodyTemplateSetsBodyAndContentLength() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.POST)
      .bodyTemplate(
          "%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", " +
              "\"password\": \"{password}\"%7D",
          Util.UTF_8);

  template = template.resolve(
      mapOf(
          "customer_name", "netflix",
          "user_name", "denominator",
          "password", "password"));

  assertThat(template)
      .hasBody(
          "{\"customer_name\": \"netflix\", \"user_name\": \"denominator\", \"password\": \"password\"}")
      .hasHeaders(
          entry("Content-Length",
              Collections.singletonList(String.valueOf(template.body().length))));
}
 
示例23
@Test
public void resolveTemplateWithBodyTemplateDoesNotDoubleDecode() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.POST)
      .bodyTemplate(
          "%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D",
          Util.UTF_8);

  template = template.resolve(
      mapOf(
          "customer_name", "netflix",
          "user_name", "denominator",
          "password", "abc+123%25d8"));

  assertThat(template)
      .hasBody(
          "{\"customer_name\": \"netflix\", \"user_name\": \"denominator\", \"password\": \"abc+123%25d8\"}");
}
 
示例24
@Test
public void throwsRetryableExceptionIfNoUnderlyingCause() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2"));

  String message = "play it again sam!";
  thrown.expect(RetryableException.class);
  thrown.expectMessage(message);

  TestInterface api = Feign.builder()
      .exceptionPropagationPolicy(UNWRAP)
      .retryer(new Retryer.Default(1, 1, 2))
      .errorDecoder(new ErrorDecoder() {
        @Override
        public Exception decode(String methodKey, Response response) {
          return new RetryableException(response.status(), message, HttpMethod.POST, null,
              response.request());
        }
      }).target(TestInterface.class, "http://localhost:" + server.getPort());

  api.post();
}
 
示例25
@Test
public void whenReturnTypeIsResponseNoErrorHandling() {
  Map<String, Collection<String>> headers = new LinkedHashMap<>();
  headers.put("Location", Collections.singletonList("http://bar.com"));
  final Response response = Response.builder()
      .status(302)
      .reason("Found")
      .headers(headers)
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0])
      .build();

  ExecutorService execs = Executors.newSingleThreadExecutor();

  // fake client as Client.Default follows redirects.
  TestInterface api = AsyncFeign.<Void>asyncBuilder()
      .client(new AsyncClient.Default<>((request, options) -> response, execs))
      .target(TestInterface.class, "http://localhost:" + server.getPort());

  assertEquals(api.response().headers().get("Location"),
      Collections.singletonList("http://bar.com"));

  execs.shutdown();
}
 
示例26
@Test
public void headerValuesWithSameNameOnlyVaryingInCaseAreMerged() {
  Map<String, Collection<String>> headersMap = new LinkedHashMap<>();
  headersMap.put("Set-Cookie", Arrays.asList("Cookie-A=Value", "Cookie-B=Value"));
  headersMap.put("set-cookie", Collections.singletonList("Cookie-C=Value"));

  Response response = Response.builder()
      .status(200)
      .headers(headersMap)
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0])
      .build();

  List<String> expectedHeaderValue =
      Arrays.asList("Cookie-A=Value", "Cookie-B=Value", "Cookie-C=Value");
  assertThat(response.headers()).containsOnly(entry(("set-cookie"), expectedHeaderValue));
}
 
示例27
private Response getResponseWithErrorCode(String errorCode, String message)
    throws JsonProcessingException {
  ObjectMapper objectMapper = new ObjectMapper();
  return Response.builder()
      .status(400)
      .reason("")
      .headers(new HashMap<>())
      .body(
          objectMapper.writeValueAsString(
              new ErrorCodeAndMessage().withErrorCode(errorCode).withMessage(message)),
          StandardCharsets.UTF_8)
      .request(Request.create(HttpMethod.GET, "", new HashMap<>(), Body.empty()))
      .build();
}
 
示例28
@Before
public void setUp() {
	oAuth2FeignRequestInterceptor = new OAuth2FeignRequestInterceptor(
			new MockOAuth2ClientContext("Fancy"),
			new BaseOAuth2ProtectedResourceDetails());
	requestTemplate = new RequestTemplate().method(HttpMethod.GET);
}
 
示例29
@SuppressWarnings("deprecation")
@Setup(Level.Invocation)
public void buildResponse() {
  response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(carsJson(Integer.parseInt(size)), Util.UTF_8)
      .build();
}
 
示例30
@Test
public void decodesMapObjectNumericalValuesAsInteger() throws Exception {
  Map<String, Object> map = new LinkedHashMap<>();
  map.put("foo", 1);

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body("{\"foo\": 1}", UTF_8)
      .build();
  assertEquals(
      new GsonDecoder().decode(response, new TypeToken<Map<String, Object>>() {}.getType()), map);
}