List of usage examples for org.springframework.http.converter HttpMessageConverter canRead
boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
From source file:org.springframework.cloud.aws.messaging.endpoint.NotificationMessageHandlerMethodArgumentResolver.java
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object doResolveArgumentFromNotificationMessage(JsonNode content, HttpInputMessage request,
Class<?> parameterType) {
if (!"Notification".equals(content.get("Type").asText())) {
throw new IllegalArgumentException(
"@NotificationMessage annotated parameters are only allowed for method that receive a notification message.");
}/*w w w.j av a 2 s. co m*/
MediaType mediaType = getMediaType(content);
String messageContent = content.findPath("Message").asText();
for (HttpMessageConverter<?> converter : this.messageConverter) {
if (converter.canRead(parameterType, mediaType)) {
try {
return converter.read((Class) parameterType,
new ByteArrayHttpInputMessage(messageContent, mediaType, request));
} catch (Exception e) {
throw new HttpMessageNotReadableException(
"Error converting notification message with payload:" + messageContent, e);
}
}
}
throw new HttpMessageNotReadableException(
"Error converting notification message with payload:" + messageContent);
}
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandler.java
/** * @param messageConverters The list of {@link HttpMessageConverter} that should be used to convert the body of an * error response returned by the API service. All of the supplied converters must be capable of reading an * {@link ApiError} in a media type of application/xml. *///from ww w.j a va2s . c o m public ApiResponseErrorHandler(List<HttpMessageConverter<?>> messageConverters) { Preconditions.checkNotNull(messageConverters, "messageConverters must be non-null."); for (HttpMessageConverter<?> messageConverter : messageConverters) { if (!messageConverter.canRead(ApiError.class, MediaType.APPLICATION_XML)) { throw new IllegalArgumentException("HttpMessageConverter [" + messageConverter + "] must support reading " + "an object of class [" + ApiError.class.toString() + "]."); } } this.errorResponseExtractor = new HttpMessageConverterExtractor<ApiError>(ApiError.class, messageConverters); }
From source file:org.cloudfoundry.identity.uaa.error.ExceptionReportHttpMessageConverter.java
@Override protected ExceptionReport readInternal(Class<? extends ExceptionReport> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { for (HttpMessageConverter<?> converter : messageConverters) { for (MediaType mediaType : converter.getSupportedMediaTypes()) { if (converter.canRead(Map.class, mediaType)) { @SuppressWarnings({ "rawtypes", "unchecked" }) HttpMessageConverter<Map> messageConverter = (HttpMessageConverter<Map>) converter; @SuppressWarnings("unchecked") Map<String, String> map = messageConverter.read(Map.class, inputMessage); return new ExceptionReport(getException(map)); }/*from w w w . j a v a2 s .c o m*/ } } return null; }
From source file:com.expedia.seiso.web.resolver.PEResourceResolver.java
@SuppressWarnings({ "unchecked", "rawtypes" })
private Item toItem(Class<?> itemClass, HttpServletRequest request) throws IOException {
val wrappedRequest = resolverUtils.wrapRequest(request);
val contentType = wrappedRequest.getHeaders().getContentType();
for (HttpMessageConverter messageConverter : messageConverters) {
// This is how we process application/json separately from application/hal+json.
if (messageConverter.canRead(itemClass, contentType)) {
return (Item) messageConverter.read(itemClass, wrappedRequest);
}//from w ww. j a va2 s. c o m
}
throw new RuntimeException(
"No converter for itemClass=" + itemClass.getName() + ", contentType=" + contentType.getType());
}
From source file:org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.java
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
RootResourceInformation resourceInformation = resourceInformationResolver.resolveArgument(parameter,
mavContainer, webRequest, binderFactory);
HttpServletRequest nativeRequest = webRequest.getNativeRequest(HttpServletRequest.class);
ServletServerHttpRequest request = new ServletServerHttpRequest(nativeRequest);
IncomingRequest incoming = new IncomingRequest(request);
Class<?> domainType = resourceInformation.getDomainType();
MediaType contentType = request.getHeaders().getContentType();
for (HttpMessageConverter converter : messageConverters) {
if (!converter.canRead(PersistentEntityResource.class, contentType)) {
continue;
}//from w w w . j av a2 s .co m
Serializable id = idResolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
Object objectToUpdate = getObjectToUpdate(id, resourceInformation);
boolean forUpdate = false;
Object entityIdentifier = null;
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
if (objectToUpdate != null) {
forUpdate = true;
entityIdentifier = entity.getIdentifierAccessor(objectToUpdate).getIdentifier();
}
Object obj = read(resourceInformation, incoming, converter, objectToUpdate);
if (obj == null) {
throw new HttpMessageNotReadableException(String.format(ERROR_MESSAGE, domainType));
}
if (entityIdentifier != null) {
entity.getPropertyAccessor(obj).setProperty(entity.getIdProperty(), entityIdentifier);
}
Builder build = PersistentEntityResource.build(obj, entity);
return forUpdate ? build.build() : build.forCreation();
}
throw new HttpMessageNotReadableException(String.format(NO_CONVERTER_FOUND, domainType, contentType));
}
From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java
private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class paramType) throws Exception { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType())); String paramName = methodParam.getParameterName(); if (paramName != null) { builder.append(' '); builder.append(paramName);/*from w ww .ja va 2 s. c o m*/ } throw new HttpMediaTypeNotSupportedException( "Cannot extract parameter (" + builder.toString() + "): no Content-Type found"); } List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); if (this.messageConverters != null) { for (HttpMessageConverter<?> messageConverter : this.messageConverters) { allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); if (messageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } return messageConverter.read(paramType, inputMessage); } } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); }
From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage,
Class<?> paramType) throws Exception {
MediaType contentType = inputMessage.getHeaders().getContentType();
if (contentType == null) {
StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType()));
String paramName = methodParam.getParameterName();
if (paramName != null) {
builder.append(' ');
builder.append(paramName);/*from www . j ava 2s. c o m*/
}
throw new HttpMediaTypeNotSupportedException(
"Cannot extract parameter (" + builder.toString() + "): no Content-Type found");
}
List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
if (this.messageConverters != null) {
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
if (messageConverter.canRead(paramType, contentType)) {
if (logger.isDebugEnabled()) {
logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using ["
+ messageConverter + "]");
}
return messageConverter.read((Class) paramType, inputMessage);
}
}
}
throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
}
From source file:org.springframework.web.client.HttpMessageConverterExtractor.java
@Override
@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
public T extractData(ClientHttpResponse response) throws IOException {
MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
if (!responseWrapper.hasMessageBody() || responseWrapper.hasEmptyMessageBody()) {
return null;
}//from w w w. j a va 2 s . c o m
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()) {
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);
}
}
}
} 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 + "]");
}
From source file:org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.java
/** * Create the method argument value of the expected parameter type by reading * from the given HttpInputMessage./* w ww . ja v a2 s .co m*/ * @param <T> the expected type of the argument value to be created * @param inputMessage the HTTP input message representing the current request * @param parameter the method parameter descriptor * @param targetType the target type, not necessarily the same as the method * parameter type, e.g. for {@code HttpEntity<String>}. * @return the created method argument value * @throws IOException if the reading from the request fails * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found */ @SuppressWarnings("unchecked") @Nullable protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { MediaType contentType; boolean noContentType = false; try { contentType = inputMessage.getHeaders().getContentType(); } catch (InvalidMediaTypeException ex) { throw new HttpMediaTypeNotSupportedException(ex.getMessage()); } if (contentType == null) { noContentType = true; contentType = MediaType.APPLICATION_OCTET_STREAM; } Class<?> contextClass = parameter.getContainingClass(); Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null); if (targetClass == null) { ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter); targetClass = (Class<T>) resolvableType.resolve(); } HttpMethod httpMethod = (inputMessage instanceof HttpRequest ? ((HttpRequest) inputMessage).getMethod() : null); Object body = NO_VALUE; EmptyBodyCheckingHttpInputMessage message; try { message = new EmptyBodyCheckingHttpInputMessage(inputMessage); for (HttpMessageConverter<?> converter : this.messageConverters) { Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter .getClass(); GenericHttpMessageConverter<?> genericConverter = (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null); if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) : (targetClass != null && converter.canRead(targetClass, contentType))) { if (logger.isDebugEnabled()) { logger.debug( "Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]"); } if (message.hasBody()) { HttpInputMessage msgToUse = getAdvice().beforeBodyRead(message, parameter, targetType, converterType); body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) : ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse)); body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType); } else { body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType); } break; } } } catch (IOException ex) { throw new HttpMessageNotReadableException("I/O error while reading input message", ex); } if (body == NO_VALUE) { if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) || (noContentType && !message.hasBody())) { return null; } throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes); } return body; }
From source file:org.springframework.web.servlet.mvc.method.annotation.support.AbstractMessageConverterMethodArgumentResolver.java
/** * Creates the method argument value of the expected parameter type by reading from the given HttpInputMessage. * //from w ww . ja v a2 s . co m * @param <T> the expected type of the argument value to be created * @param inputMessage the HTTP input message representing the current request * @param methodParam the method argument * @param paramType the type of the argument value to be created * @return the created method argument value * @throws IOException if the reading from the request fails * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found */ @SuppressWarnings("unchecked") protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter methodParam, Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } for (HttpMessageConverter<?> messageConverter : this.messageConverters) { if (messageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } return ((HttpMessageConverter<T>) messageConverter).read(paramType, inputMessage); } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); }