Search in sources :

Example 11 with HttpMessageNotReadableException

use of org.springframework.http.converter.HttpMessageNotReadableException in project spring-security-oauth by spring-projects.

the class SparklrController method photo.

@RequestMapping("/sparklr/photos/{id}")
public ResponseEntity<BufferedImage> photo(@PathVariable String id) throws Exception {
    InputStream photo = sparklrService.loadSparklrPhoto(id);
    if (photo == null) {
        throw new UnavailableException("The requested photo does not exist");
    }
    BufferedImage body;
    MediaType contentType = MediaType.IMAGE_JPEG;
    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
    if (imageReaders.hasNext()) {
        ImageReader imageReader = imageReaders.next();
        ImageReadParam irp = imageReader.getDefaultReadParam();
        imageReader.setInput(new MemoryCacheImageInputStream(photo), true);
        body = imageReader.read(0, irp);
    } else {
        throw new HttpMessageNotReadableException("Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<BufferedImage>(body, headers, HttpStatus.OK);
}
Also used : ImageReadParam(javax.imageio.ImageReadParam) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) InputStream(java.io.InputStream) UnavailableException(javax.servlet.UnavailableException) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) MediaType(org.springframework.http.MediaType) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 12 with HttpMessageNotReadableException

use of org.springframework.http.converter.HttpMessageNotReadableException in project spring-framework by spring-projects.

the class AbstractMessageConverterMethodArgumentResolver method readWithMessageConverters.

/**
	 * Create the method argument value of the expected parameter type by reading
	 * from the given HttpInputMessage.
	 * @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 (may be {@code null})
	 * @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")
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 != null ? parameter.getContainingClass() : null);
    Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null);
    if (targetClass == null) {
        ResolvableType resolvableType = (parameter != null ? ResolvableType.forMethodParameter(parameter) : ResolvableType.forType(targetType));
        targetClass = (Class<T>) resolvableType.resolve();
    }
    HttpMethod httpMethod = ((HttpRequest) inputMessage).getMethod();
    Object body = NO_VALUE;
    try {
        inputMessage = new EmptyBodyCheckingHttpInputMessage(inputMessage);
        for (HttpMessageConverter<?> converter : this.messageConverters) {
            Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
            if (converter instanceof GenericHttpMessageConverter) {
                GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
                if (genericConverter.canRead(targetType, contextClass, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
                    }
                    if (inputMessage.getBody() != null) {
                        inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
                        body = genericConverter.read(targetType, contextClass, inputMessage);
                        body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
                    } else {
                        body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
                    }
                    break;
                }
            } else if (targetClass != null) {
                if (converter.canRead(targetClass, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
                    }
                    if (inputMessage.getBody() != null) {
                        inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
                        body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage);
                        body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
                    } else {
                        body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
                    }
                    break;
                }
            }
        }
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read document: " + ex.getMessage(), ex);
    }
    if (body == NO_VALUE) {
        if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) || (noContentType && inputMessage.getBody() == null)) {
            return null;
        }
        throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
    }
    return body;
}
Also used : HttpRequest(org.springframework.http.HttpRequest) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) IOException(java.io.IOException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) HttpMethod(org.springframework.http.HttpMethod) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter)

Example 13 with HttpMessageNotReadableException

use of org.springframework.http.converter.HttpMessageNotReadableException in project spring-framework by spring-projects.

the class DefaultHandlerExceptionResolverTests method handleHttpMessageNotReadable.

@Test
public void handleHttpMessageNotReadable() {
    HttpMessageNotReadableException ex = new HttpMessageNotReadableException("foo");
    ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
    assertNotNull("No ModelAndView returned", mav);
    assertTrue("No Empty ModelAndView returned", mav.isEmpty());
    assertEquals("Invalid status code", 400, response.getStatus());
}
Also used : HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) ModelAndView(org.springframework.web.servlet.ModelAndView) Test(org.junit.Test)

Example 14 with HttpMessageNotReadableException

use of org.springframework.http.converter.HttpMessageNotReadableException in project spring-framework by spring-projects.

the class ProtobufHttpMessageConverter method readInternal.

@Override
protected Message readInternal(Class<? extends Message> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MediaType contentType = inputMessage.getHeaders().getContentType();
    if (contentType == null) {
        contentType = PROTOBUF;
    }
    Charset charset = contentType.getCharset();
    if (charset == null) {
        charset = DEFAULT_CHARSET;
    }
    try {
        Message.Builder builder = getMessageBuilder(clazz);
        if (PROTOBUF.isCompatibleWith(contentType)) {
            builder.mergeFrom(inputMessage.getBody(), this.extensionRegistry);
        } else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) {
            InputStreamReader reader = new InputStreamReader(inputMessage.getBody(), charset);
            TextFormat.merge(reader, this.extensionRegistry, builder);
        } else if (isProtobufJavaUtilPresent || isProtobufJavaFormatPresent) {
            this.protobufFormatsSupport.merge(inputMessage.getBody(), charset, contentType, this.extensionRegistry, builder);
        }
        return builder.build();
    } catch (Exception ex) {
        throw new HttpMessageNotReadableException("Could not read Protobuf message: " + ex.getMessage(), ex);
    }
}
Also used : HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpInputMessage(org.springframework.http.HttpInputMessage) Message(com.google.protobuf.Message) HttpOutputMessage(org.springframework.http.HttpOutputMessage) InputStreamReader(java.io.InputStreamReader) MediaType(org.springframework.http.MediaType) Charset(java.nio.charset.Charset) IOException(java.io.IOException) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException)

Example 15 with HttpMessageNotReadableException

use of org.springframework.http.converter.HttpMessageNotReadableException in project spring-framework by spring-projects.

the class Jaxb2RootElementHttpMessageConverter method readFromSource.

@Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
    try {
        source = processSource(source);
        Unmarshaller unmarshaller = createUnmarshaller(clazz);
        if (clazz.isAnnotationPresent(XmlRootElement.class)) {
            return unmarshaller.unmarshal(source);
        } else {
            JAXBElement<?> jaxbElement = unmarshaller.unmarshal(source, clazz);
            return jaxbElement.getValue();
        }
    } catch (NullPointerException ex) {
        if (!isSupportDtd()) {
            throw new HttpMessageNotReadableException("NPE while unmarshalling. " + "This can happen on JDK 1.6 due to the presence of DTD " + "declarations, which are disabled.", ex);
        }
        throw ex;
    } catch (UnmarshalException ex) {
        throw new HttpMessageNotReadableException("Could not unmarshal to [" + clazz + "]: " + ex.getMessage(), ex);
    } catch (JAXBException ex) {
        throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
    }
}
Also used : HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) UnmarshalException(javax.xml.bind.UnmarshalException) JAXBException(javax.xml.bind.JAXBException) HttpMessageConversionException(org.springframework.http.converter.HttpMessageConversionException) Unmarshaller(javax.xml.bind.Unmarshaller)

Aggregations

HttpMessageNotReadableException (org.springframework.http.converter.HttpMessageNotReadableException)19 MediaType (org.springframework.http.MediaType)7 Test (org.junit.Test)5 IOException (java.io.IOException)4 BufferedImage (java.awt.image.BufferedImage)3 InputStream (java.io.InputStream)3 ImageReadParam (javax.imageio.ImageReadParam)3 ImageReader (javax.imageio.ImageReader)3 MemoryCacheImageInputStream (javax.imageio.stream.MemoryCacheImageInputStream)3 UnavailableException (javax.servlet.UnavailableException)3 HttpHeaders (org.springframework.http.HttpHeaders)3 ResponseEntity (org.springframework.http.ResponseEntity)3 HttpMessageNotWritableException (org.springframework.http.converter.HttpMessageNotWritableException)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 InputStreamReader (java.io.InputStreamReader)2 Charset (java.nio.charset.Charset)2 JAXBException (javax.xml.bind.JAXBException)2 UnmarshalException (javax.xml.bind.UnmarshalException)2 Unmarshaller (javax.xml.bind.Unmarshaller)2 XMLInputFactory (javax.xml.stream.XMLInputFactory)2