feign.codec.DecodeException Java Examples

The following examples show how to use feign.codec.DecodeException. 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: 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 #2
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 #3
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 #4
Source File: JacksonIteratorDecoder.java    From feign with Apache License 2.0 6 votes vote down vote up
private T readNext() {
  try {
    JsonToken jsonToken = parser.nextToken();
    if (jsonToken == null) {
      return null;
    }

    if (jsonToken == JsonToken.START_ARRAY) {
      jsonToken = parser.nextToken();
    }

    if (jsonToken == JsonToken.END_ARRAY) {
      ensureClosed(this);
      return null;
    }

    return objectReader.readValue(parser);
  } catch (IOException e) {
    // Input Stream closed automatically by parser
    throw new DecodeException(response.status(), e.getMessage(), response.request(), e);
  }
}
 
Example #5
Source File: UltraDNSTest.java    From denominator with Apache License 2.0 5 votes vote down vote up
@Test
public void networkStatusCantParse() throws Exception {
  thrown.expect(DecodeException.class);
  thrown.expectMessage("Content is not allowed in prolog.");

  server.enqueue(new MockResponse().setBody("{\"foo\": \"bar\"}"));

  mockApi().getNeustarNetworkStatus();
}
 
Example #6
Source File: SAXDecoder.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException {
  if (response.body() == null)
    return null;
  ContentHandlerWithResult.Factory<?> handlerFactory = handlerFactories.get(type);
  checkState(handlerFactory != null, "type %s not in configured handlers %s", type,
      handlerFactories.keySet());
  ContentHandlerWithResult<?> handler = handlerFactory.create();
  try {
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
    xmlReader.setFeature("http://xml.org/sax/features/validation", false);
    /* Explicitly control sax configuration to prevent XXE attacks */
    xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
    xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
    xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    xmlReader.setContentHandler(handler);
    InputStream inputStream = response.body().asInputStream();
    try {
      xmlReader.parse(new InputSource(inputStream));
    } finally {
      ensureClosed(inputStream);
    }
    return handler.result();
  } catch (SAXException e) {
    throw new DecodeException(response.status(), e.getMessage(), response.request(), e);
  }
}
 
Example #7
Source File: FeignTest.java    From feign with 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 #8
Source File: FeignUnderAsyncTest.java    From feign with 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 #9
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 #10
Source File: MeteredDecoder.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type)
    throws IOException, DecodeException, FeignException {
  final RequestTemplate template = response.request().requestTemplate();
  final MeteredBody body = response.body() == null
      ? null
      : new MeteredBody(response.body());

  response = response.toBuilder().body(body).build();

  final Object decoded;
  try (final Context classTimer =
      metricRegistry
          .timer(metricName.metricName(template.methodMetadata(), template.feignTarget()),
              metricSuppliers.timers())
          .time()) {
    decoded = decoder.decode(response, type);
  }

  if (body != null) {
    metricRegistry.histogram(
        metricName.metricName(template.methodMetadata(), template.feignTarget(),
            "response_size"),
        metricSuppliers.histograms()).update(body.count());
  }

  return decoded;
}
 
Example #11
Source File: JacksonIteratorTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void responseIsClosedOnParseError() throws IOException {
  final AtomicBoolean closed = new AtomicBoolean();

  byte[] jsonBytes = "[error".getBytes(UTF_8);
  InputStream inputStream = new ByteArrayInputStream(jsonBytes) {
    @Override
    public void close() throws IOException {
      closed.set(true);
      super.close();
    }
  };
  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(inputStream, jsonBytes.length)
      .build();

  try {
    thrown.expect(DecodeException.class);
    assertThat(iterator(Boolean.class, response)).hasSize(1);
  } finally {
    assertThat(closed.get()).isTrue();
  }
}
 
Example #12
Source File: JacksonIteratorTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void malformedObjectThrowsDecodeException() throws IOException {
  thrown.expect(DecodeException.class);
  thrown.expectCause(isA(IOException.class));

  assertThat(iterator(User.class, "[{\"login\":\"bob\"},{\"login\":\"joe..."))
      .containsOnly(new User("bob"));
}
 
Example #13
Source File: MeteredDecoder.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type)
    throws IOException, DecodeException, FeignException {
  final RequestTemplate template = response.request().requestTemplate();
  final MeteredBody body = response.body() == null
      ? null
      : new MeteredBody(response.body());

  response = response.toBuilder().body(body).build();

  final Object decoded;
  try (final Timer.Context classTimer =
      metricRegistry
          .timer(metricName.metricName(template.methodMetadata(), template.feignTarget()),
              metricSuppliers.timers())
          .time()) {
    decoded = decoder.decode(response, type);
  }

  if (body != null) {
    metricRegistry.histogram(
        metricName.metricName(template.methodMetadata(), template.feignTarget(),
            "response_size"),
        metricSuppliers.histograms()).update(body.count());
  }

  return decoded;
}
 
Example #14
Source File: JAXBDecoder.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type) throws IOException {
  if (response.status() == 204)
    return Util.emptyValueOf(type);
  if (response.body() == null)
    return null;
  while (type instanceof ParameterizedType) {
    ParameterizedType ptype = (ParameterizedType) type;
    type = ptype.getRawType();
  }
  if (!(type instanceof Class)) {
    throw new UnsupportedOperationException(
        "JAXB only supports decoding raw types. Found " + type);
  }


  try {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    /* Explicitly control sax configuration to prevent XXE attacks */
    saxParserFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    saxParserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
    saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
        false);
    saxParserFactory.setNamespaceAware(namespaceAware);

    return jaxbContextFactory.createUnmarshaller((Class<?>) type).unmarshal(new SAXSource(
        saxParserFactory.newSAXParser().getXMLReader(),
        new InputSource(response.body().asInputStream())));
  } catch (JAXBException | ParserConfigurationException | SAXException e) {
    throw new DecodeException(response.status(), e.toString(), response.request(), e);
  } finally {
    if (response.body() != null) {
      response.body().close();
    }
  }
}
 
Example #15
Source File: MockClientTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type)
    throws IOException, DecodeException, FeignException {
  assertThat(response.request(), notNullValue());

  return delegate.decode(response, type);
}
 
Example #16
Source File: MockClientSequentialTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type)
    throws IOException, DecodeException, FeignException {
  assertThat(response.request(), notNullValue());

  return delegate.decode(response, type);
}
 
Example #17
Source File: TransactionFeignDecoder.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Object decode(Response resp, Type type) throws IOException, DecodeException, FeignException {
	Request request = resp.request();

	String reqTransactionStr = this.getHeaderValue(request, HEADER_TRANCACTION_KEY);
	String reqPropagationStr = this.getHeaderValue(request, HEADER_PROPAGATION_KEY);

	String respTransactionStr = this.getHeaderValue(resp, HEADER_TRANCACTION_KEY);
	String respPropagationStr = this.getHeaderValue(resp, HEADER_PROPAGATION_KEY);

	if (StringUtils.isBlank(reqTransactionStr)) {
		return this.delegate.decode(resp, type);
	} else if (StringUtils.isBlank(reqPropagationStr)) {
		return this.delegate.decode(resp, type);
	}

	try {
		String transactionStr = StringUtils.isBlank(respTransactionStr) ? reqTransactionStr : respTransactionStr;
		String propagationStr = StringUtils.isBlank(respPropagationStr) ? reqPropagationStr : respPropagationStr;

		byte[] byteArray = Base64.getDecoder().decode(transactionStr); // ByteUtils.stringToByteArray(transactionStr);
		TransactionContext transactionContext = (TransactionContext) SerializeUtils.deserializeObject(byteArray);

		SpringCloudBeanRegistry beanRegistry = SpringCloudBeanRegistry.getInstance();
		RemoteCoordinator remoteCoordinator = beanRegistry.getConsumeCoordinator(propagationStr);

		TransactionResponseImpl response = new TransactionResponseImpl();
		response.setTransactionContext(transactionContext);
		response.setSourceTransactionCoordinator(remoteCoordinator);
	} catch (IOException ex) {
		logger.error("Error occurred while decoding response({})!", resp, ex);
	}

	return this.delegate.decode(resp, type);
}
 
Example #18
Source File: ChronosClient.java    From spring-cloud-deployer-mesos with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
	Collection<String> contentTypes = response.headers().get("Content-Type");
	if (contentTypes.contains(MimeTypeUtils.TEXT_PLAIN.toString())) {
		return defaultDecoder.decode(response, type);
	}
	else {
		return gsonDecoder.decode(response, type);
	}
}
 
Example #19
Source File: SpringDecoder.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(final Response response, Type type)
		throws IOException, FeignException {
	if (type instanceof Class || type instanceof ParameterizedType
			|| type instanceof WildcardType) {
		@SuppressWarnings({ "unchecked", "rawtypes" })
		HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor(
				type, this.messageConverters.getObject().getConverters());

		return extractor.extractData(new FeignResponseAdapter(response));
	}
	throw new DecodeException(response.status(),
			"type is not an instance of Class or ParameterizedType: " + type,
			response.request());
}
 
Example #20
Source File: OpenFeignFieldLevelEncryptionDecoderTest.java    From client-encryption-java with MIT License 5 votes vote down vote up
@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
Source File: SOAPDecoder.java    From feign with Apache License 2.0 4 votes vote down vote up
@Override
public Object decode(Response response, Type type) throws IOException {
  if (response.status() == 404)
    return Util.emptyValueOf(type);
  if (response.body() == null)
    return null;
  while (type instanceof ParameterizedType) {
    ParameterizedType ptype = (ParameterizedType) type;
    type = ptype.getRawType();
  }
  if (!(type instanceof Class)) {
    throw new UnsupportedOperationException(
        "SOAP only supports decoding raw types. Found " + type);
  }

  try {
    SOAPMessage message =
        MessageFactory.newInstance(soapProtocol).createMessage(null,
            response.body().asInputStream());
    if (message.getSOAPBody() != null) {
      if (message.getSOAPBody().hasFault()) {
        throw new SOAPFaultException(message.getSOAPBody().getFault());
      }

      Unmarshaller unmarshaller = jaxbContextFactory.createUnmarshaller((Class<?>) type);

      if (this.useFirstChild) {
        return unmarshaller.unmarshal(message.getSOAPBody().getFirstChild());
      } else {
        return unmarshaller.unmarshal(message.getSOAPBody().extractContentAsDocument());
      }
    }
  } catch (SOAPException | JAXBException e) {
    throw new DecodeException(response.status(), e.toString(), response.request(), e);
  } finally {
    if (response.body() != null) {
      response.body().close();
    }
  }
  return Util.emptyValueOf(type);

}
 
Example #22
Source File: CompensableFeignDecoder.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Object decode(Response resp, Type type) throws IOException, DecodeException, FeignException {
	Request request = resp.request();

	String reqTransactionStr = this.getHeaderValue(request, HEADER_TRANCACTION_KEY);
	String reqPropagationStr = this.getHeaderValue(request, HEADER_PROPAGATION_KEY);

	String respTransactionStr = this.getHeaderValue(resp, HEADER_TRANCACTION_KEY);
	String respPropagationStr = this.getHeaderValue(resp, HEADER_PROPAGATION_KEY);
	String respRecursivelyStr = this.getHeaderValue(resp, HEADER_RECURSIVELY_KEY);

	if (StringUtils.isBlank(reqTransactionStr)) {
		return this.delegate.decode(resp, type);
	} else if (StringUtils.isBlank(reqPropagationStr)) {
		return this.delegate.decode(resp, type);
	}

	boolean participantInvolved = StringUtils.isNotBlank(respTransactionStr) || StringUtils.isNotBlank(respPropagationStr);

	CompensableFeignResult result = new CompensableFeignResult();
	try {
		String transactionStr = StringUtils.isBlank(respTransactionStr) ? reqTransactionStr : respTransactionStr;
		String propagationStr = StringUtils.isBlank(respPropagationStr) ? reqPropagationStr : respPropagationStr;

		byte[] byteArray = Base64.getDecoder().decode(transactionStr); // ByteUtils.stringToByteArray(transactionStr);
		TransactionContext transactionContext = (TransactionContext) SerializeUtils.deserializeObject(byteArray);

		SpringCloudBeanRegistry beanRegistry = SpringCloudBeanRegistry.getInstance();
		RemoteCoordinator remoteCoordinator = beanRegistry.getConsumeCoordinator(propagationStr);

		result.setTransactionContext(transactionContext);
		result.setRemoteParticipant(remoteCoordinator);
		result.setParticipantValidFlag(!participantInvolved || StringUtils.equalsIgnoreCase(respRecursivelyStr, "TRUE"));
	} catch (IOException ex) {
		logger.error("Error occurred while decoding response({})!", resp, ex);
	}

	Object value = this.delegate.decode(resp, type);
	result.setResult(value);

	if (result.isParticipantValidFlag()) {
		throw result;
	} else {
		return (Object) value;
	}
}
 
Example #23
Source File: OpenFeignFieldLevelEncryptionDecoder.java    From client-encryption-java with MIT License 4 votes vote down vote up
@Override
public Object decode(Response response, Type type) throws IOException {
    try {
        // Check response actually has a payload
        Response.Body body = response.body();
        if (body == null || body.length() <= 0) {
            // Nothing to decrypt
            return this.delegate.decode(response, type);
        }

        // Read response payload
        String responsePayload = Util.toString(body.asReader());

        // Decrypt fields & update headers
        String decryptedPayload;
        if (config.useHttpHeaders()) {
            // Read encryption params from HTTP headers and delete headers
            String ivValue = readHeader(response, config.getIvHeaderName());
            response = removeHeader(response, config.getIvHeaderName());
            String oaepPaddingDigestAlgorithmValue = readHeader(response, config.getOaepPaddingDigestAlgorithmHeaderName());
            response = removeHeader(response, config.getOaepPaddingDigestAlgorithmHeaderName());
            String encryptedKeyValue = readHeader(response, config.getEncryptedKeyHeaderName());
            response = removeHeader(response, config.getEncryptedKeyHeaderName());
            response = removeHeader(response, config.getEncryptionCertificateFingerprintHeaderName());
            response = removeHeader(response, config.getEncryptionKeyFingerprintHeaderName());
            FieldLevelEncryptionParams params = new FieldLevelEncryptionParams(ivValue, encryptedKeyValue, oaepPaddingDigestAlgorithmValue, config);
            decryptedPayload = FieldLevelEncryption.decryptPayload(responsePayload, config, params);
        } else {
            // Encryption params are stored in the payload
            decryptedPayload = FieldLevelEncryption.decryptPayload(responsePayload, config);
        }
        response = updateHeader(response, "Content-Length", String.valueOf(decryptedPayload.length()));
        response = response.toBuilder()
                .body(decryptedPayload, StandardCharsets.UTF_8)
                .build();
    } catch (EncryptionException e) {
        throw new DecodeException("Failed to intercept and decrypt response!", e);
    }

    // Call the regular decoder
    return this.delegate.decode(response, type);
}
 
Example #24
Source File: AsynchronousMethodHandler.java    From feign-vertx with Apache License 2.0 3 votes vote down vote up
/**
 * Transforms HTTP response body into object using decoder.
 *
 * @param response  HTTP response
 *
 * @return decoded result
 *
 * @throws IOException IO exception during the reading of InputStream of response
 * @throws DecodeException when decoding failed due to a checked or unchecked exception besides
 *     IOException
 * @throws FeignException when decoding succeeds, but conveys the operation failed
 */
private Object decode(final Response response) throws IOException, FeignException {
  try {
    return decoder.decode(response, metadata.returnType());
  } catch (final FeignException feignException) {
    /* All feign exception including decode exceptions */
    throw feignException;
  } catch (final RuntimeException unexpectedException) {
    /* Any unexpected exception */
    throw new DecodeException(unexpectedException.getMessage(), unexpectedException);
  }
}