org.springframework.http.converter.GenericHttpMessageConverter Java Examples

The following examples show how to use org.springframework.http.converter.GenericHttpMessageConverter. 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: DefaultServerRequestBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T bodyInternal(Type bodyType, Class<?> bodyClass)
		throws ServletException, IOException {

	HttpInputMessage inputMessage = new BuiltInputMessage();
	MediaType contentType = headers().contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);

	for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
		if (messageConverter instanceof GenericHttpMessageConverter) {
			GenericHttpMessageConverter<T> genericMessageConverter =
					(GenericHttpMessageConverter<T>) messageConverter;
			if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) {
				return genericMessageConverter.read(bodyType, bodyClass, inputMessage);
			}
		}
		if (messageConverter.canRead(bodyClass, contentType)) {
			HttpMessageConverter<T> theConverter =
					(HttpMessageConverter<T>) messageConverter;
			Class<? extends T> clazz = (Class<? extends T>) bodyClass;
			return theConverter.read(clazz, inputMessage);
		}
	}
	throw new HttpMediaTypeNotSupportedException(contentType, Collections.emptyList());
}
 
Example #2
Source File: DefaultServerRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T bodyInternal(Type bodyType, Class<?> bodyClass)
		throws ServletException, IOException {

	MediaType contentType =
			this.headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);

	for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
		if (messageConverter instanceof GenericHttpMessageConverter) {
			GenericHttpMessageConverter<T> genericMessageConverter =
					(GenericHttpMessageConverter<T>) messageConverter;
			if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) {
				return genericMessageConverter.read(bodyType, bodyClass, this.serverHttpRequest);
			}
		}
		if (messageConverter.canRead(bodyClass, contentType)) {
			HttpMessageConverter<T> theConverter =
					(HttpMessageConverter<T>) messageConverter;
			Class<? extends T> clazz = (Class<? extends T>) bodyClass;
			return theConverter.read(clazz, this.serverHttpRequest);
		}
	}
	throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
}
 
Example #3
Source File: HttpMessageConverterExtractorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
	GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
	List<HttpMessageConverter<?>> converters = createConverterList(converter);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {};
	Type type = reference.getType();
	extractor = new HttpMessageConverterExtractor<List<String>>(type, converters);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(type, null, contentType)).willReturn(true);
	given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);

	assertEquals(expected, result);
}
 
Example #4
Source File: HttpMessageConverterExtractorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
	GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {};
	Type type = reference.getType();
	extractor = new HttpMessageConverterExtractor<List<String>>(type, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(type, null, contentType)).willReturn(true);
	given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);
	assertEquals(expected, result);
}
 
Example #5
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the media types that can be produced:
 * <ul>
 * <li>The producible media types specified in the request mappings, or
 * <li>Media types of configured converters that can write the specific return value, or
 * <li>{@link MediaType#ALL}
 * </ul>
 * @since 4.2
 */
@SuppressWarnings("unchecked")
protected List<MediaType> getProducibleMediaTypes(HttpServletRequest request, Class<?> returnValueClass, Type returnValueType) {
	Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		return new ArrayList<MediaType>(mediaTypes);
	}
	else if (!this.allSupportedMediaTypes.isEmpty()) {
		List<MediaType> result = new ArrayList<MediaType>();
		for (HttpMessageConverter<?> converter : this.messageConverters) {
			if (converter instanceof GenericHttpMessageConverter && returnValueType != null) {
				if (((GenericHttpMessageConverter<?>) converter).canWrite(returnValueType, returnValueClass, null)) {
					result.addAll(converter.getSupportedMediaTypes());
				}
			}
			else if (converter.canWrite(returnValueClass, null)) {
				result.addAll(converter.getSupportedMediaTypes());
			}
		}
		return result;
	}
	else {
		return Collections.singletonList(MediaType.ALL);
	}
}
 
Example #6
Source File: WxApiMessageConverterExtractor.java    From FastBootWeixin with Apache License 2.0 6 votes vote down vote up
@Override
public T extractData(ResponseEntity<HttpInputMessage> responseEntity) throws IOException {
    MediaType contentType = getContentType(responseEntity);
    for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
        if (messageConverter instanceof GenericHttpMessageConverter) {
            GenericHttpMessageConverter<?> genericMessageConverter =
                    (GenericHttpMessageConverter<?>) messageConverter;
            if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
                return (T) genericMessageConverter.read(this.responseType, null, responseEntity.getBody());
            }
        }
        if (this.responseClass != null) {
            if (messageConverter.canRead(this.responseClass, contentType)) {
                return (T) messageConverter.read((Class) this.responseClass, responseEntity.getBody());
            }
        }
    }

    throw new WxApiResponseException("不能转换相应数据为类型:" + this.responseType, responseEntity);
}
 
Example #7
Source File: HttpMessageConverterExtractorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
	GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {};
	Type type = reference.getType();
	extractor = new HttpMessageConverterExtractor<List<String>>(type, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(type, null, contentType)).willReturn(true);
	given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);
	assertEquals(expected, result);
}
 
Example #8
Source File: AbstractMessageConverterMethodProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the media types that can be produced:
 * <ul>
 * <li>The producible media types specified in the request mappings, or
 * <li>Media types of configured converters that can write the specific return value, or
 * <li>{@link MediaType#ALL}
 * </ul>
 * @since 4.2
 */
@SuppressWarnings("unchecked")
protected List<MediaType> getProducibleMediaTypes(HttpServletRequest request, Class<?> valueClass, Type declaredType) {
	Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		return new ArrayList<MediaType>(mediaTypes);
	}
	else if (!this.allSupportedMediaTypes.isEmpty()) {
		List<MediaType> result = new ArrayList<MediaType>();
		for (HttpMessageConverter<?> converter : this.messageConverters) {
			if (converter instanceof GenericHttpMessageConverter && declaredType != null) {
				if (((GenericHttpMessageConverter<?>) converter).canWrite(declaredType, valueClass, null)) {
					result.addAll(converter.getSupportedMediaTypes());
				}
			}
			else if (converter.canWrite(valueClass, null)) {
				result.addAll(converter.getSupportedMediaTypes());
			}
		}
		return result;
	}
	else {
		return Collections.singletonList(MediaType.ALL);
	}
}
 
Example #9
Source File: SpringConverterFactory.java    From spring-cloud-square with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
	if (type instanceof Class || type instanceof ParameterizedType) {
		//MediaType contentType = getContentType(responseWrapper);
		MediaType contentType = MediaType.APPLICATION_JSON; //TODO: determine dynamically?
		Class<?> responseClass = (type instanceof Class) ? (Class<?>) type : null;


		for (HttpMessageConverter<?> messageConverter : this.messageConverters.getObject().getConverters()) {
			if (messageConverter instanceof GenericHttpMessageConverter) {
				GenericHttpMessageConverter<?> genericMessageConverter = (GenericHttpMessageConverter<?>) messageConverter;
				if (genericMessageConverter.canRead(type, null, contentType)) {
					if (log.isDebugEnabled()) {
						log.debug("Reading [" + type + "] as \"" +
								contentType + "\" using [" + messageConverter + "]");
					}
					return new SpringResponseConverter(genericMessageConverter, type);
				}
			}
			if (responseClass != null) {
				if (messageConverter.canRead(responseClass, contentType)) {
					if (log.isDebugEnabled()) {
						log.debug("Reading [" + responseClass.getName() + "] as \"" +
								contentType + "\" using [" + messageConverter + "]");
					}
					return new SpringResponseConverter(messageConverter, responseClass);
				}
			}
		}
	}
	return null;
}
 
Example #10
Source File: HttpMessageConverterExtractor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public T extractData(ClientHttpResponse response) throws IOException {
	MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
	if (!responseWrapper.hasMessageBody() || responseWrapper.hasEmptyMessageBody()) {
		return null;
	}
	MediaType contentType = getContentType(responseWrapper);

	for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
		if (messageConverter instanceof GenericHttpMessageConverter) {
			GenericHttpMessageConverter<?> genericMessageConverter = (GenericHttpMessageConverter<?>) messageConverter;
			if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Reading [" + this.responseType + "] as \"" +
							contentType + "\" using [" + messageConverter + "]");
				}
				return (T) genericMessageConverter.read(this.responseType, null, responseWrapper);
			}
		}
		if (this.responseClass != null) {
			if (messageConverter.canRead(this.responseClass, contentType)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Reading [" + this.responseClass.getName() + "] as \"" +
							contentType + "\" using [" + messageConverter + "]");
				}
				return (T) messageConverter.read((Class) this.responseClass, responseWrapper);
			}
		}
	}

	throw new RestClientException("Could not extract response: no suitable HttpMessageConverter found " +
			"for response type [" + this.responseType + "] and content type [" + contentType + "]");
}
 
Example #11
Source File: RestTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
	if (this.responseType != null) {
		Class<?> responseClass = null;
		if (this.responseType instanceof Class) {
			responseClass = (Class<?>) this.responseType;
		}
		List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
		for (HttpMessageConverter<?> converter : getMessageConverters()) {
			if (responseClass != null) {
				if (converter.canRead(responseClass, null)) {
					allSupportedMediaTypes.addAll(getSupportedMediaTypes(converter));
				}
			}
			else if (converter instanceof GenericHttpMessageConverter) {
				GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
				if (genericConverter.canRead(this.responseType, null, null)) {
					allSupportedMediaTypes.addAll(getSupportedMediaTypes(converter));
				}
			}
		}
		if (!allSupportedMediaTypes.isEmpty()) {
			MediaType.sortBySpecificity(allSupportedMediaTypes);
			if (logger.isDebugEnabled()) {
				logger.debug("Setting request Accept header to " + allSupportedMediaTypes);
			}
			request.getHeaders().setAccept(allSupportedMediaTypes);
		}
	}
}
 
Example #12
Source File: HttpMessageConverterExtractor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked", "rawtypes", "resource"})
public T extractData(ClientHttpResponse response) throws IOException {
	MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
	if (!responseWrapper.hasMessageBody() || responseWrapper.hasEmptyMessageBody()) {
		return null;
	}
	MediaType contentType = getContentType(responseWrapper);

	for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
		if (messageConverter instanceof GenericHttpMessageConverter) {
			GenericHttpMessageConverter<?> genericMessageConverter =
					(GenericHttpMessageConverter<?>) messageConverter;
			if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Reading [" + this.responseType + "] as \"" +
							contentType + "\" using [" + messageConverter + "]");
				}
				return (T) genericMessageConverter.read(this.responseType, null, responseWrapper);
			}
		}
		if (this.responseClass != null) {
			if (messageConverter.canRead(this.responseClass, contentType)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Reading [" + this.responseClass.getName() + "] as \"" +
							contentType + "\" using [" + messageConverter + "]");
				}
				return (T) messageConverter.read((Class) this.responseClass, responseWrapper);
			}
		}
	}

	throw new RestClientException("Could not extract response: no suitable HttpMessageConverter found " +
			"for response type [" + this.responseType + "] and content type [" + contentType + "]");
}
 
Example #13
Source File: RestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
	if (this.responseType != null) {
		Class<?> responseClass = null;
		if (this.responseType instanceof Class) {
			responseClass = (Class<?>) this.responseType;
		}
		List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
		for (HttpMessageConverter<?> converter : getMessageConverters()) {
			if (responseClass != null) {
				if (converter.canRead(responseClass, null)) {
					allSupportedMediaTypes.addAll(getSupportedMediaTypes(converter));
				}
			}
			else if (converter instanceof GenericHttpMessageConverter) {
				GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
				if (genericConverter.canRead(this.responseType, null, null)) {
					allSupportedMediaTypes.addAll(getSupportedMediaTypes(converter));
				}
			}
		}
		if (!allSupportedMediaTypes.isEmpty()) {
			MediaType.sortBySpecificity(allSupportedMediaTypes);
			if (logger.isDebugEnabled()) {
				logger.debug("Setting request Accept header to " + allSupportedMediaTypes);
			}
			request.getHeaders().setAccept(allSupportedMediaTypes);
		}
	}
}
 
Example #14
Source File: HttpMessageConverterResolver.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public HttpMessageConverterHolder resolve(HttpRequest request,
		Class<?> parameterType) {

	HttpMessageConverterHolder httpMessageConverterHolder = null;

	HttpHeaders httpHeaders = request.getHeaders();

	MediaType contentType = httpHeaders.getContentType();

	if (contentType == null) {
		contentType = MediaType.APPLICATION_OCTET_STREAM;
	}

	for (HttpMessageConverter<?> converter : this.messageConverters) {
		if (converter instanceof GenericHttpMessageConverter) {
			GenericHttpMessageConverter genericConverter = (GenericHttpMessageConverter) converter;
			if (genericConverter.canRead(parameterType, parameterType, contentType)) {
				httpMessageConverterHolder = new HttpMessageConverterHolder(
						contentType, converter);
				break;
			}
		}
		else {
			if (converter.canRead(parameterType, contentType)) {
				httpMessageConverterHolder = new HttpMessageConverterHolder(
						contentType, converter);
				break;
			}
		}

	}

	return httpMessageConverterHolder;
}
 
Example #15
Source File: SpringEncoder.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private FeignOutputMessage checkAndWrite(Object body, Type genericType,
		MediaType contentType, GenericHttpMessageConverter converter,
		RequestTemplate request) throws IOException {
	if (converter.canWrite(genericType, body.getClass(), contentType)) {
		logBeforeWrite(body, contentType, converter);
		FeignOutputMessage outputMessage = new FeignOutputMessage(request);
		converter.write(body, genericType, contentType, outputMessage);
		return outputMessage;
	}
	else {
		return null;
	}
}
 
Example #16
Source File: RestTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
	GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class);
	template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
	ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {};
	given(converter.canRead(intList.getType(), null, null)).willReturn(true);
	given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(converter.canWrite(String.class, String.class, null)).willReturn(true);

	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "http://example.com", requestHeaders);
	List<Integer> expected = Collections.singletonList(42);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.TEXT_PLAIN);
	responseHeaders.setContentLength(10);
	mockResponseStatus(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
	given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
	given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.set("MyHeader", "MyValue");
	HttpEntity<String> requestEntity = new HttpEntity<>("Hello World", entityHeaders);
	ResponseEntity<List<Integer>> result = template.exchange("http://example.com", POST, requestEntity, intList);
	assertEquals("Invalid POST result", expected, result.getBody());
	assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
	assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
	assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
	assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());

	verify(response).close();
}
 
Example #17
Source File: RestTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
private boolean canReadResponse(Type responseType, HttpMessageConverter<?> converter) {
	Class<?> responseClass = (responseType instanceof Class ? (Class<?>) responseType : null);
	if (responseClass != null) {
		return converter.canRead(responseClass, null);
	}
	else if (converter instanceof GenericHttpMessageConverter) {
		GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
		return genericConverter.canRead(responseType, null, null);
	}
	return false;
}
 
Example #18
Source File: AbstractMessageConverterMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Returns the media types that can be produced. The resulting media types are:
 * <ul>
 * <li>The producible media types specified in the request mappings, or
 * <li>Media types of configured converters that can write the specific return value, or
 * <li>{@link MediaType#ALL}
 * </ul>
 * @since 4.2
 */
@SuppressWarnings("unchecked")
protected List<MediaType> getProducibleMediaTypes(
		HttpServletRequest request, Class<?> valueClass, @Nullable Type targetType) {

	Set<MediaType> mediaTypes =
			(Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		return new ArrayList<>(mediaTypes);
	}
	else if (!this.allSupportedMediaTypes.isEmpty()) {
		List<MediaType> result = new ArrayList<>();
		for (HttpMessageConverter<?> converter : this.messageConverters) {
			if (converter instanceof GenericHttpMessageConverter && targetType != null) {
				if (((GenericHttpMessageConverter<?>) converter).canWrite(targetType, valueClass, null)) {
					result.addAll(converter.getSupportedMediaTypes());
				}
			}
			else if (converter.canWrite(valueClass, null)) {
				result.addAll(converter.getSupportedMediaTypes());
			}
		}
		return result;
	}
	else {
		return Collections.singletonList(MediaType.ALL);
	}
}
 
Example #19
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
	GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class);
	template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
	ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {};
	given(converter.canRead(intList.getType(), null, null)).willReturn(true);
	given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(converter.canWrite(String.class, String.class, null)).willReturn(true);

	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "https://example.com", requestHeaders);
	List<Integer> expected = Collections.singletonList(42);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.TEXT_PLAIN);
	responseHeaders.setContentLength(10);
	mockResponseStatus(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
	given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
	given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.set("MyHeader", "MyValue");
	HttpEntity<String> requestEntity = new HttpEntity<>("Hello World", entityHeaders);
	ResponseEntity<List<Integer>> result = template.exchange("https://example.com", POST, requestEntity, intList);
	assertEquals("Invalid POST result", expected, result.getBody());
	assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
	assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
	assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
	assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());

	verify(response).close();
}
 
Example #20
Source File: RestTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private boolean canReadResponse(Type responseType, HttpMessageConverter<?> converter) {
	Class<?> responseClass = (responseType instanceof Class ? (Class<?>) responseType : null);
	if (responseClass != null) {
		return converter.canRead(responseClass, null);
	}
	else if (converter instanceof GenericHttpMessageConverter) {
		GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
		return genericConverter.canRead(responseType, null, null);
	}
	return false;
}
 
Example #21
Source File: AbstractMessageConverterMethodProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Returns the media types that can be produced. The resulting media types are:
 * <ul>
 * <li>The producible media types specified in the request mappings, or
 * <li>Media types of configured converters that can write the specific return value, or
 * <li>{@link MediaType#ALL}
 * </ul>
 * @since 4.2
 */
@SuppressWarnings("unchecked")
protected List<MediaType> getProducibleMediaTypes(
		HttpServletRequest request, Class<?> valueClass, @Nullable Type targetType) {

	Set<MediaType> mediaTypes =
			(Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		return new ArrayList<>(mediaTypes);
	}
	else if (!this.allSupportedMediaTypes.isEmpty()) {
		List<MediaType> result = new ArrayList<>();
		for (HttpMessageConverter<?> converter : this.messageConverters) {
			if (converter instanceof GenericHttpMessageConverter && targetType != null) {
				if (((GenericHttpMessageConverter<?>) converter).canWrite(targetType, valueClass, null)) {
					result.addAll(converter.getSupportedMediaTypes());
				}
			}
			else if (converter.canWrite(valueClass, null)) {
				result.addAll(converter.getSupportedMediaTypes());
			}
		}
		return result;
	}
	else {
		return Collections.singletonList(MediaType.ALL);
	}
}
 
Example #22
Source File: DefaultEntityResponseBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected void writeEntityWithMessageConverters(Object entity, HttpServletRequest request,
		HttpServletResponse response, ServerResponse.Context context)
		throws ServletException, IOException {

	ServletServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
	MediaType contentType = getContentType(response);
	Class<?> entityClass = entity.getClass();

	for (HttpMessageConverter<?> messageConverter : context.messageConverters()) {
		if (messageConverter instanceof GenericHttpMessageConverter<?>) {
			GenericHttpMessageConverter<Object> genericMessageConverter =
					(GenericHttpMessageConverter<Object>) messageConverter;
			if (genericMessageConverter.canWrite(this.entityType, entityClass, contentType)) {
				genericMessageConverter.write(entity, this.entityType, contentType, serverResponse);
				return;
			}
		}
		if (messageConverter.canWrite(entityClass, contentType)) {
			((HttpMessageConverter<Object>)messageConverter).write(entity, contentType, serverResponse);
			return;
		}
	}

	List<MediaType> producibleMediaTypes = producibleMediaTypes(context.messageConverters(), entityClass);
	throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
}
 
Example #23
Source File: SpringEncoderTests.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
@Bean
GenericHttpMessageConverter<?> myGenericHttpMessageConverter() {
	return new MyGenericHttpMessageConverter();
}
 
Example #24
Source File: SpringEncoder.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
@Override
public void encode(Object requestBody, Type bodyType, RequestTemplate request)
		throws EncodeException {
	// template.body(conversionService.convert(object, String.class));
	if (requestBody != null) {
		Collection<String> contentTypes = request.headers()
				.get(HttpEncoding.CONTENT_TYPE);

		MediaType requestContentType = null;
		if (contentTypes != null && !contentTypes.isEmpty()) {
			String type = contentTypes.iterator().next();
			requestContentType = MediaType.valueOf(type);
		}

		if (Objects.equals(requestContentType, MediaType.MULTIPART_FORM_DATA)) {
			this.springFormEncoder.encode(requestBody, bodyType, request);
			return;
		}
		else {
			if (bodyType == MultipartFile.class) {
				log.warn(
						"For MultipartFile to be handled correctly, the 'consumes' parameter of @RequestMapping "
								+ "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE");
			}
		}

		for (HttpMessageConverter messageConverter : this.messageConverters
				.getObject().getConverters()) {
			FeignOutputMessage outputMessage;
			try {
				if (messageConverter instanceof GenericHttpMessageConverter) {
					outputMessage = checkAndWrite(requestBody, bodyType,
							requestContentType,
							(GenericHttpMessageConverter) messageConverter, request);
				}
				else {
					outputMessage = checkAndWrite(requestBody, requestContentType,
							messageConverter, request);
				}
			}
			catch (IOException | HttpMessageConversionException ex) {
				throw new EncodeException("Error converting request body", ex);
			}
			if (outputMessage != null) {
				// clear headers
				request.headers(null);
				// converters can modify headers, so update the request
				// with the modified headers
				request.headers(getHeaders(outputMessage.getHeaders()));

				// do not use charset for binary data and protobuf
				Charset charset;
				if (messageConverter instanceof ByteArrayHttpMessageConverter) {
					charset = null;
				}
				else if (messageConverter instanceof ProtobufHttpMessageConverter
						&& ProtobufHttpMessageConverter.PROTOBUF.isCompatibleWith(
								outputMessage.getHeaders().getContentType())) {
					charset = null;
				}
				else {
					charset = StandardCharsets.UTF_8;
				}
				request.body(Request.Body.encoded(
						outputMessage.getOutputStream().toByteArray(), charset));
				return;
			}
		}
		String message = "Could not write request: no suitable HttpMessageConverter "
				+ "found for request type [" + requestBody.getClass().getName() + "]";
		if (requestContentType != null) {
			message += " and content type [" + requestContentType + "]";
		}
		throw new EncodeException(message);
	}
}
 
Example #25
Source File: HttpMessageConverterExtractor.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@SuppressWarnings({"unchecked", "rawtypes", "resource"})
public T extractData(ClientHttpResponse response) throws IOException {
	MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
	if (!responseWrapper.hasMessageBody() || responseWrapper.hasEmptyMessageBody()) {
		return null;
	}
	MediaType contentType = getContentType(responseWrapper);

	try {
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter instanceof GenericHttpMessageConverter) {
				GenericHttpMessageConverter<?> genericMessageConverter =
						(GenericHttpMessageConverter<?>) messageConverter;
				if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
					if (logger.isDebugEnabled()) {
						ResolvableType resolvableType = ResolvableType.forType(this.responseType);
						logger.debug("Reading to [" + resolvableType + "]");
					}
					return (T) genericMessageConverter.read(this.responseType, null, responseWrapper);
				}
			}
			if (this.responseClass != null) {
				if (messageConverter.canRead(this.responseClass, contentType)) {
					if (logger.isDebugEnabled()) {
						String className = this.responseClass.getName();
						logger.debug("Reading to [" + className + "] as \"" + contentType + "\"");
					}
					return (T) messageConverter.read((Class) this.responseClass, responseWrapper);
				}
			}
		}
	}
	catch (IOException | HttpMessageNotReadableException ex) {
		throw new RestClientException("Error while extracting response for type [" +
				this.responseType + "] and content type [" + contentType + "]", ex);
	}

	throw new RestClientException("Could not extract response: no suitable HttpMessageConverter found " +
			"for response type [" + this.responseType + "] and content type [" + contentType + "]");
}
 
Example #26
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Writes the given return type to the given output message.
 * @param returnValue the value to write to the output message
 * @param returnType the type of the value
 * @param inputMessage the input messages. Used to inspect the {@code Accept} header.
 * @param outputMessage the output message to write to
 * @throws IOException thrown in case of I/O errors
 * @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated by {@code Accept} header on
 * the request cannot be met by the message converters
 */
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType,
		ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	Class<?> returnValueClass = getReturnValueType(returnValue, returnType);
	Type returnValueType = getGenericType(returnType);
	HttpServletRequest servletRequest = inputMessage.getServletRequest();
	List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest);
	List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass, returnValueType);

	if (returnValue != null && producibleMediaTypes.isEmpty()) {
		throw new IllegalArgumentException("No converter found for return value of type: " + returnValueClass);
	}

	Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
	for (MediaType requestedType : requestedMediaTypes) {
		for (MediaType producibleType : producibleMediaTypes) {
			if (requestedType.isCompatibleWith(producibleType)) {
				compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType));
			}
		}
	}
	if (compatibleMediaTypes.isEmpty()) {
		if (returnValue != null) {
			throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
		}
		return;
	}

	List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
	MediaType.sortBySpecificityAndQuality(mediaTypes);

	MediaType selectedMediaType = null;
	for (MediaType mediaType : mediaTypes) {
		if (mediaType.isConcrete()) {
			selectedMediaType = mediaType;
			break;
		}
		else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
			selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
			break;
		}
	}

	if (selectedMediaType != null) {
		selectedMediaType = selectedMediaType.removeQualityValue();
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter instanceof GenericHttpMessageConverter) {
				if (((GenericHttpMessageConverter<T>) messageConverter).canWrite(returnValueType,
						returnValueClass, selectedMediaType)) {
					returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
							(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
							inputMessage, outputMessage);
					if (returnValue != null) {
						addContentDispositionHeader(inputMessage, outputMessage);
						((GenericHttpMessageConverter<T>) messageConverter).write(returnValue,
								returnValueType, selectedMediaType, outputMessage);
						if (logger.isDebugEnabled()) {
							logger.debug("Written [" + returnValue + "] as \"" +
									selectedMediaType + "\" using [" + messageConverter + "]");
						}
					}
					return;
				}
			}
			else if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
				returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
						(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
						inputMessage, outputMessage);
				if (returnValue != null) {
					addContentDispositionHeader(inputMessage, outputMessage);
					((HttpMessageConverter<T>) messageConverter).write(returnValue,
							selectedMediaType, outputMessage);
					if (logger.isDebugEnabled()) {
						logger.debug("Written [" + returnValue + "] as \"" +
								selectedMediaType + "\" using [" + messageConverter + "]");
					}
				}
				return;
			}
		}
	}

	if (returnValue != null) {
		throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
	}
}
 
Example #27
Source File: HttpMessageConverterExtractor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
@SuppressWarnings({"unchecked", "rawtypes", "resource"})
public T extractData(ClientHttpResponse response) throws IOException {
	MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
	if (!responseWrapper.hasMessageBody() || responseWrapper.hasEmptyMessageBody()) {
		return null;
	}
	MediaType contentType = getContentType(responseWrapper);

	try {
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter instanceof GenericHttpMessageConverter) {
				GenericHttpMessageConverter<?> genericMessageConverter =
						(GenericHttpMessageConverter<?>) messageConverter;
				if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
					if (logger.isDebugEnabled()) {
						ResolvableType resolvableType = ResolvableType.forType(this.responseType);
						logger.debug("Reading to [" + resolvableType + "]");
					}
					return (T) genericMessageConverter.read(this.responseType, null, responseWrapper);
				}
			}
			if (this.responseClass != null) {
				if (messageConverter.canRead(this.responseClass, contentType)) {
					if (logger.isDebugEnabled()) {
						String className = this.responseClass.getName();
						logger.debug("Reading to [" + className + "] as \"" + contentType + "\"");
					}
					return (T) messageConverter.read((Class) this.responseClass, responseWrapper);
				}
			}
		}
	}
	catch (IOException | HttpMessageNotReadableException ex) {
		throw new RestClientException("Error while extracting response for type [" +
				this.responseType + "] and content type [" + contentType + "]", ex);
	}

	throw new RestClientException("Could not extract response: no suitable HttpMessageConverter found " +
			"for response type [" + this.responseType + "] and content type [" + contentType + "]");
}
 
Example #28
Source File: RestTemplateTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
	GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class);
	template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));

	ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {};
	given(converter.canRead(intList.getType(), null, null)).willReturn(true);
	given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
	HttpHeaders requestHeaders = new HttpHeaders();
	given(this.request.getHeaders()).willReturn(requestHeaders);
	given(converter.canWrite(String.class, null)).willReturn(true);
	String requestBody = "Hello World";
	converter.write(requestBody, null, this.request);
	given(this.request.execute()).willReturn(response);
	given(errorHandler.hasError(response)).willReturn(false);
	List<Integer> expected = Collections.singletonList(42);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.TEXT_PLAIN);
	responseHeaders.setContentLength(10);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(new Integer(42).toString().getBytes()));
	given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
	given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	HttpStatus status = HttpStatus.OK;
	given(response.getStatusCode()).willReturn(status);
	given(response.getStatusText()).willReturn(status.getReasonPhrase());

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.set("MyHeader", "MyValue");
	HttpEntity<String> requestEntity = new HttpEntity<String>(requestBody, entityHeaders);
	ResponseEntity<List<Integer>> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, intList);
	assertEquals("Invalid POST result", expected, result.getBody());
	assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
	assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
	assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
	assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());

	verify(response).close();
}
 
Example #29
Source File: SpringResponseConverter.java    From spring-cloud-square with Apache License 2.0 4 votes vote down vote up
public SpringResponseConverter(GenericHttpMessageConverter<?> genericMessageConverter, Type type) {
	this.genericMessageConverter = genericMessageConverter;
	this.type = type;
}