feign.codec.EncodeException Java Examples
The following examples show how to use
feign.codec.EncodeException.
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: OpenFeignFieldLevelEncryptionEncoderTest.java From client-encryption-java with MIT License | 7 votes |
@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 #2
Source File: UrlencodedFormContentProcessor.java From feign-form with Apache License 2.0 | 6 votes |
@Override public void process (RequestTemplate template, Charset charset, Map<String, Object> data) throws EncodeException { val bodyData = new StringBuilder(); for (Entry<String, Object> entry : data.entrySet()) { if (entry == null || entry.getKey() == null) { continue; } if (bodyData.length() > 0) { bodyData.append(QUERY_DELIMITER); } bodyData.append(createKeyValuePair(entry, charset)); } val contentTypeValue = new StringBuilder() .append(getSupportedContentType().getHeader()) .append("; charset=").append(charset.name()) .toString(); val bytes = bodyData.toString().getBytes(charset); val body = Request.Body.encoded(bytes, charset); template.header(CONTENT_TYPE_HEADER, Collections.<String>emptyList()); // reset header template.header(CONTENT_TYPE_HEADER, contentTypeValue); template.body(body); }
Example #3
Source File: BuildTemplateByResolvingArgs.java From feign-vertx with Apache License 2.0 | 6 votes |
@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 #4
Source File: BuildTemplateByResolvingArgs.java From feign-vertx with Apache License 2.0 | 6 votes |
@Override protected RequestTemplate resolve( final Object[] argv, final RequestTemplate mutable, final Map<String, Object> variables) { final Object body = argv[metadata.bodyIndex()]; checkNotNull(body, "Body parameter %s was null", metadata.bodyIndex()); try { encoder.encode(body, metadata.bodyType(), mutable); } catch (final EncodeException encodeException) { throw encodeException; } catch (final RuntimeException unexpectedException) { throw new EncodeException(unexpectedException.getMessage(), unexpectedException); } return super.resolve(argv, mutable, variables); }
Example #5
Source File: FeignMultipartEncoder.java From hawkbit-examples with Eclipse Public License 1.0 | 6 votes |
@SuppressWarnings("unchecked") private void encodeRequest(final Object value, final HttpHeaders requestHeaders, final RequestTemplate template) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final HttpOutputMessage dummyRequest = new HttpOutputMessageImpl(outputStream, requestHeaders); try { final Class<?> requestType = value.getClass(); final MediaType requestContentType = requestHeaders.getContentType(); for (final HttpMessageConverter<?> messageConverter : converters) { if (messageConverter.canWrite(requestType, requestContentType)) { ((HttpMessageConverter<Object>) messageConverter).write(value, requestContentType, dummyRequest); break; } } } catch (final IOException ex) { throw new EncodeException("Cannot encode request.", ex); } final HttpHeaders headers = dummyRequest.getHeaders(); for (final Entry<String, List<String>> entry : headers.entrySet()) { template.header(entry.getKey(), entry.getValue()); } /* * we should use a template output stream... this will cause issues if * files are too big, since the whole request will be in memory. */ template.body(outputStream.toByteArray(), UTF_8); }
Example #6
Source File: FormEncoder.java From feign-form with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public void encode (Object object, Type bodyType, RequestTemplate template) throws EncodeException { String contentTypeValue = getContentTypeValue(template.headers()); val contentType = ContentType.of(contentTypeValue); if (!processors.containsKey(contentType)) { delegate.encode(object, bodyType, template); return; } Map<String, Object> data; if (MAP_STRING_WILDCARD.equals(bodyType)) { data = (Map<String, Object>) object; } else if (isUserPojo(bodyType)) { data = toMap(object); } else { delegate.encode(object, bodyType, template); return; } val charset = getCharset(contentTypeValue); processors.get(contentType).process(template, charset, data); }
Example #7
Source File: FeignSpringFormEncoder.java From feign-client-test with MIT License | 6 votes |
/** * Encodes the request as a multipart form. It can detect a single {@link MultipartFile}, an * array of {@link MultipartFile}s, or POJOs (that are converted to JSON). * * @param formMap * @param template * @throws EncodeException */ private void encodeMultipartFormRequest(Map<String, ?> formMap, HttpHeaders multipartHeaders, RequestTemplate template) throws EncodeException { if (formMap == null) { throw new EncodeException("Cannot encode request with null form."); } LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); for (Entry<String, ?> entry : formMap.entrySet()) { Object value = entry.getValue(); if (isMultipartFile(value)) { map.add(entry.getKey(), encodeMultipartFile((MultipartFile) value)); } else if (isMultipartFileArray(value)) { encodeMultipartFiles(map, entry.getKey(), Arrays.asList((MultipartFile[]) value)); } else { map.add(entry.getKey(), encodeJsonObject(value)); } } encodeRequest(map, multipartHeaders, template); }
Example #8
Source File: MeteredEncoder.java From feign with Apache License 2.0 | 6 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { try (final Timer.Context classTimer = metricRegistry.timer( metricName.metricName(template.methodMetadata(), template.feignTarget()), metricSuppliers.timers()).time()) { encoder.encode(object, bodyType, template); } if (template.body() != null) { metricRegistry.histogram( metricName.metricName(template.methodMetadata(), template.feignTarget(), "request_size"), metricSuppliers.histograms()).update(template.body().length); } }
Example #9
Source File: FieldQueryMapEncoder.java From feign with Apache License 2.0 | 6 votes |
@Override public Map<String, Object> encode(Object object) throws EncodeException { try { ObjectParamMetadata metadata = getMetadata(object.getClass()); Map<String, Object> fieldNameToValue = new HashMap<String, Object>(); for (Field field : metadata.objectFields) { Object value = field.get(object); if (value != null && value != object) { Param alias = field.getAnnotation(Param.class); String name = alias != null ? alias.value() : field.getName(); fieldNameToValue.put(name, value); } } return fieldNameToValue; } catch (IllegalAccessException e) { throw new EncodeException("Failure encoding object into query map", e); } }
Example #10
Source File: BeanQueryMapEncoder.java From feign with Apache License 2.0 | 6 votes |
@Override public Map<String, Object> encode(Object object) throws EncodeException { try { ObjectParamMetadata metadata = getMetadata(object.getClass()); Map<String, Object> propertyNameToValue = new HashMap<String, Object>(); for (PropertyDescriptor pd : metadata.objectProperties) { Method method = pd.getReadMethod(); Object value = method.invoke(object); if (value != null && value != object) { Param alias = method.getAnnotation(Param.class); String name = alias != null ? alias.value() : pd.getName(); propertyNameToValue.put(name, value); } } return propertyNameToValue; } catch (IllegalAccessException | IntrospectionException | InvocationTargetException e) { throw new EncodeException("Failure encoding object into query map", e); } }
Example #11
Source File: AbstractFormWriter.java From spring-cloud-openfeign with Apache License 2.0 | 6 votes |
@Override public void write(Output output, String key, Object object) throws EncodeException { try { String string = new StringBuilder() .append("Content-Disposition: form-data; name=\"").append(key) .append('"').append(CRLF).append("Content-Type: ") .append(getContentType()).append("; charset=") .append(output.getCharset().name()).append(CRLF).append(CRLF) .append(writeAsString(object)).toString(); output.write(string); } catch (IOException e) { throw new EncodeException(e.getMessage()); } }
Example #12
Source File: MeteredEncoder.java From feign with Apache License 2.0 | 6 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { try (final Context classTimer = metricRegistry.timer( metricName.metricName(template.methodMetadata(), template.feignTarget()), metricSuppliers.timers()).time()) { encoder.encode(object, bodyType, template); } if (template.body() != null) { metricRegistry.histogram( metricName.metricName(template.methodMetadata(), template.feignTarget(), "request_size"), metricSuppliers.histograms()).update(template.body().length); } }
Example #13
Source File: FormEncoder.java From carbon-apimgt with Apache License 2.0 | 5 votes |
@Override public void encode(Object o, Type type, RequestTemplate requestTemplate) throws EncodeException { Map<String, Object> params = (Map<String, Object>) o; String paramString = params.entrySet().stream() .map(this::urlEncodeKeyValuePair) .collect(Collectors.joining("&")); requestTemplate.body(paramString); }
Example #14
Source File: FeignTest.java From feign with Apache License 2.0 | 5 votes |
@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 #15
Source File: CustomClientTest.java From feign-form with Apache License 2.0 | 5 votes |
@Override protected void write (Output output, String key, Object value) throws EncodeException { writeFileMetadata(output, key, "popa.txt", null); val bytes = (byte[]) value; output.write(bytes); }
Example #16
Source File: OpenFeignFieldLevelEncryptionEncoder.java From client-encryption-java with MIT License | 5 votes |
@Override public void encode(Object object, Type type, RequestTemplate requestTemplate) { // Call the regular encoder delegate.encode(object, type, requestTemplate); try { // Check request actually has a payload byte[] bodyBytes = requestTemplate.body(); if (null == bodyBytes || bodyBytes.length <= 0) { // Nothing to encrypt return ; } // Read request payload String payload = new String(bodyBytes, StandardCharsets.UTF_8); // Encrypt fields & update headers String encryptedPayload; if (config.useHttpHeaders()) { // Generate encryption params and add them as HTTP headers FieldLevelEncryptionParams params = FieldLevelEncryptionParams.generate(config); updateHeader(requestTemplate, config.getIvHeaderName(), params.getIvValue()); updateHeader(requestTemplate, config.getEncryptedKeyHeaderName(), params.getEncryptedKeyValue()); updateHeader(requestTemplate, config.getEncryptionCertificateFingerprintHeaderName(), config.getEncryptionCertificateFingerprint()); updateHeader(requestTemplate, config.getEncryptionKeyFingerprintHeaderName(), config.getEncryptionKeyFingerprint()); updateHeader(requestTemplate, config.getOaepPaddingDigestAlgorithmHeaderName(), params.getOaepPaddingDigestAlgorithmValue()); encryptedPayload = FieldLevelEncryption.encryptPayload(payload, config, params); } else { // Encryption params will be stored in the payload encryptedPayload = FieldLevelEncryption.encryptPayload(payload, config); } requestTemplate.body(encryptedPayload); updateHeader(requestTemplate, "Content-Length", String.valueOf(encryptedPayload.length())); } catch (EncryptionException e) { throw new EncodeException("Failed to intercept and encrypt request!", e); } }
Example #17
Source File: FeignMultipartEncoder.java From hawkbit-examples with Eclipse Public License 1.0 | 5 votes |
private void encodeMultipartFormRequest(final Object value, final RequestTemplate template) { if (value == null) { throw new EncodeException("Cannot encode request with null value."); } if (!isMultipartFile(value)) { throw new EncodeException("Only multipart can be handled by this encoder"); } encodeRequest(encodeMultipartFile((MultipartFile) value), multipartHeaders, template); }
Example #18
Source File: FeignUnderAsyncTest.java From feign with Apache License 2.0 | 5 votes |
@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 #19
Source File: FeignMultipartEncoder.java From hawkbit-examples with Eclipse Public License 1.0 | 5 votes |
private MultiValueMap<String, Object> encodeMultipartFile(final MultipartFile file) { try { final MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>(); multiValueMap.add("file", new MultipartFileResource(file.getName(), file.getSize(), file.getInputStream())); return multiValueMap; } catch (final IOException ex) { throw new EncodeException("Cannot encode request.", ex); } }
Example #20
Source File: ExtSpringEncoder.java From onetwo with Apache License 2.0 | 5 votes |
@Override public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException { if(requestBody==null){ super.encode(requestBody, bodyType, request); return ; } if(GET_METHOD.equalsIgnoreCase(request.method()) && requestBody!=null){ // Map<String, Object> map = beanToMapConvertor.toFlatMap(requestBody); // MultiValueMap<String, String> map = RestUtils.toMultiValueStringMap(requestBody); MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); // 使用ConsumableValuePutter增强对注解处理 /*getParamsConvertor.flatObject("", requestBody, (k, v, ctx)->{ map.add(k, v); });*/ getParamsConvertor.flatObject("", requestBody, new ConsumableValuePutter((k, v) -> { map.add(k, v); })); map.forEach((name, value)->{ if(value!=null){ request.query(name, value.toArray(new String[0])); } }); return ; } Object convertedRequestBody = convertRequestBodyIfNecessary(requestBody, request); super.encode(convertedRequestBody, bodyType, request); }
Example #21
Source File: AsyncFeignTest.java From feign with Apache License 2.0 | 5 votes |
@Test public void okIfEncodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); thrown.expect(EncodeException.class); TestInterfaceAsync api = new TestInterfaceAsyncBuilder().encoder(new Encoder() { @Override public void encode(Object object, Type bodyType, RequestTemplate template) { throw new RuntimeException(); } }).target("http://localhost:" + server.getPort()); unwrap(api.body(Arrays.asList("foo"))); }
Example #22
Source File: FormEncoder.java From carbon-apimgt with Apache License 2.0 | 5 votes |
private String urlEncodeKeyValuePair(Map.Entry<String, Object> entry) { try { return URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()) + '=' + URLEncoder.encode(String.valueOf(entry.getValue()), StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException ex) { throw new EncodeException("Error occurred while URL encoding message", ex); } }
Example #23
Source File: MeteredEncoder.java From feign with Apache License 2.0 | 5 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { meterRegistry.timer( metricName.name(), metricName.tag(template.methodMetadata(), template.feignTarget())) .record(() -> encoder.encode(object, bodyType, template)); if (template.body() != null) { meterRegistry.summary( metricName.name("request_size"), metricName.tag(template.methodMetadata(), template.feignTarget())) .record(template.body().length); } }
Example #24
Source File: JacksonJaxbJsonEncoder.java From feign with Apache License 2.0 | 5 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { jacksonJaxbJsonProvider.writeTo(object, bodyType.getClass(), null, null, APPLICATION_JSON_TYPE, null, outputStream); template.body(outputStream.toByteArray(), Charset.defaultCharset()); } catch (IOException e) { throw new EncodeException(e.getMessage(), e); } }
Example #25
Source File: JAXBEncoder.java From feign with Apache License 2.0 | 5 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) { if (!(bodyType instanceof Class)) { throw new UnsupportedOperationException( "JAXB only supports encoding raw types. Found " + bodyType); } try { Marshaller marshaller = jaxbContextFactory.createMarshaller((Class<?>) bodyType); StringWriter stringWriter = new StringWriter(); marshaller.marshal(object, stringWriter); template.body(stringWriter.toString()); } catch (JAXBException e) { throw new EncodeException(e.toString(), e); } }
Example #26
Source File: SOAPEncoder.java From feign with Apache License 2.0 | 5 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) { if (!(bodyType instanceof Class)) { throw new UnsupportedOperationException( "SOAP only supports encoding raw types. Found " + bodyType); } try { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Marshaller marshaller = jaxbContextFactory.createMarshaller((Class<?>) bodyType); marshaller.marshal(object, document); SOAPMessage soapMessage = MessageFactory.newInstance(soapProtocol).createMessage(); soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, Boolean.toString(writeXmlDeclaration)); soapMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, charsetEncoding.displayName()); soapMessage.getSOAPBody().addDocument(document); ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (formattedOutput) { Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); t.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(bos)); } else { soapMessage.writeTo(bos); } template.body(new String(bos.toByteArray())); } catch (SOAPException | JAXBException | ParserConfigurationException | IOException | TransformerFactoryConfigurationError | TransformerException e) { throw new EncodeException(e.toString(), e); } }
Example #27
Source File: JacksonEncoder.java From feign with Apache License 2.0 | 5 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) { try { JavaType javaType = mapper.getTypeFactory().constructType(bodyType); template.body(mapper.writerFor(javaType).writeValueAsBytes(object), Util.UTF_8); } catch (JsonProcessingException e) { throw new EncodeException(e.getMessage(), e); } }
Example #28
Source File: FeignSpringFormEncoder.java From feign-client-test with MIT License | 5 votes |
/** * Calls the conversion chain actually used by * {@link org.springframework.web.client.RestTemplate}, filling the body of the request * template. * * @param value * @param requestHeaders * @param template * @throws EncodeException */ private void encodeRequest(Object value, HttpHeaders requestHeaders, RequestTemplate template) throws EncodeException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); HttpOutputMessage dummyRequest = new HttpOutputMessageImpl(outputStream, requestHeaders); try { Class<?> requestType = value.getClass(); MediaType requestContentType = requestHeaders.getContentType(); for (HttpMessageConverter<?> messageConverter : converters) { if (messageConverter.canWrite(requestType, requestContentType)) { ((HttpMessageConverter<Object>) messageConverter).write( value, requestContentType, dummyRequest); break; } } } catch (IOException ex) { throw new EncodeException("Cannot encode request.", ex); } HttpHeaders headers = dummyRequest.getHeaders(); if (headers != null) { for (Entry<String, List<String>> entry : headers.entrySet()) { template.header(entry.getKey(), entry.getValue()); } } /* we should use a template output stream... this will cause issues if files are too big, since the whole request will be in memory. */ template.body(outputStream.toByteArray(), UTF_8); }
Example #29
Source File: FeignSpringFormEncoder.java From open-cloud with MIT License | 5 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { if (bodyType != null && bodyType.equals(MultipartFile[].class) && object != null) { MultipartFile[] file = (MultipartFile[]) object; if (file.length == 0) { return; } Map data = Collections.singletonMap(file.length == 0 ? "" : file[0].getName(), object); super.encode(data, MAP_STRING_WILDCARD, template); return; } super.encode(object, bodyType, template); }
Example #30
Source File: PageableSpringEncoder.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Override public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { if (supports(object)) { if (object instanceof Pageable) { Pageable pageable = (Pageable) object; if (pageable.isPaged()) { template.query(pageParameter, pageable.getPageNumber() + ""); template.query(sizeParameter, pageable.getPageSize() + ""); } if (pageable.getSort() != null) { applySort(template, pageable.getSort()); } } else if (object instanceof Sort) { Sort sort = (Sort) object; applySort(template, sort); } } else { if (delegate != null) { delegate.encode(object, bodyType, template); } else { throw new EncodeException( "PageableSpringEncoder does not support the given object " + object.getClass() + " and no delegate was provided for fallback!"); } } }