Search in sources :

Example 1 with HttpMediaTypeNotSupportedException

use of org.springframework.web.HttpMediaTypeNotSupportedException in project spring-framework by spring-projects.

the class RequestMappingInfoHandlerMapping method handleNoMatch.

/**
	 * Iterate all RequestMappingInfo's once again, look if any match by URL at
	 * least and raise exceptions according to what doesn't match.
	 * @throws HttpRequestMethodNotSupportedException if there are matches by URL
	 * but not by HTTP method
	 * @throws HttpMediaTypeNotAcceptableException if there are matches by URL
	 * but not by consumable/producible media types
	 */
@Override
protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> infos, String lookupPath, HttpServletRequest request) throws ServletException {
    PartialMatchHelper helper = new PartialMatchHelper(infos, request);
    if (helper.isEmpty()) {
        return null;
    }
    if (helper.hasMethodsMismatch()) {
        Set<String> methods = helper.getAllowedMethods();
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            HttpOptionsHandler handler = new HttpOptionsHandler(methods);
            return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
        }
        throw new HttpRequestMethodNotSupportedException(request.getMethod(), methods);
    }
    if (helper.hasConsumesMismatch()) {
        Set<MediaType> mediaTypes = helper.getConsumableMediaTypes();
        MediaType contentType = null;
        if (StringUtils.hasLength(request.getContentType())) {
            try {
                contentType = MediaType.parseMediaType(request.getContentType());
            } catch (InvalidMediaTypeException ex) {
                throw new HttpMediaTypeNotSupportedException(ex.getMessage());
            }
        }
        throw new HttpMediaTypeNotSupportedException(contentType, new ArrayList<>(mediaTypes));
    }
    if (helper.hasProducesMismatch()) {
        Set<MediaType> mediaTypes = helper.getProducibleMediaTypes();
        throw new HttpMediaTypeNotAcceptableException(new ArrayList<>(mediaTypes));
    }
    if (helper.hasParamsMismatch()) {
        List<String[]> conditions = helper.getParamConditions();
        throw new UnsatisfiedServletRequestParameterException(conditions, request.getParameterMap());
    }
    return null;
}
Also used : UnsatisfiedServletRequestParameterException(org.springframework.web.bind.UnsatisfiedServletRequestParameterException) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HandlerMethod(org.springframework.web.method.HandlerMethod) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) MediaType(org.springframework.http.MediaType) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 2 with HttpMediaTypeNotSupportedException

use of org.springframework.web.HttpMediaTypeNotSupportedException in project spring-framework by spring-projects.

the class RequestMappingInfoHandlerMappingTests method testHttpMediaTypeNotSupportedException.

private void testHttpMediaTypeNotSupportedException(String url) throws Exception {
    try {
        MockHttpServletRequest request = new MockHttpServletRequest("PUT", url);
        request.setContentType("application/json");
        this.handlerMapping.getHandler(request);
        fail("HttpMediaTypeNotSupportedException expected");
    } catch (HttpMediaTypeNotSupportedException ex) {
        assertEquals("Invalid supported consumable media types", Collections.singletonList(new MediaType("application", "xml")), ex.getSupportedMediaTypes());
    }
}
Also used : HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) MediaType(org.springframework.http.MediaType)

Example 3 with HttpMediaTypeNotSupportedException

use of org.springframework.web.HttpMediaTypeNotSupportedException in project spring-framework by spring-projects.

the class RequestMappingInfoHandlerMappingTests method getHandlerTestInvalidContentType.

@Test
public void getHandlerTestInvalidContentType() throws Exception {
    try {
        MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/person/1");
        request.setContentType("bogus");
        this.handlerMapping.getHandler(request);
        fail("HttpMediaTypeNotSupportedException expected");
    } catch (HttpMediaTypeNotSupportedException ex) {
        assertEquals("Invalid mime type \"bogus\": does not contain '/'", ex.getMessage());
    }
}
Also used : HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) Test(org.junit.Test)

Example 4 with HttpMediaTypeNotSupportedException

use of org.springframework.web.HttpMediaTypeNotSupportedException in project spring-framework by spring-projects.

the class ResponseEntityExceptionHandlerTests method handleHttpMediaTypeNotSupported.

@Test
public void handleHttpMediaTypeNotSupported() {
    List<MediaType> acceptable = Arrays.asList(MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML);
    Exception ex = new HttpMediaTypeNotSupportedException(MediaType.APPLICATION_JSON, acceptable);
    ResponseEntity<Object> responseEntity = testException(ex);
    assertEquals(acceptable, responseEntity.getHeaders().getAccept());
}
Also used : HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) MediaType(org.springframework.http.MediaType) MissingPathVariableException(org.springframework.web.bind.MissingPathVariableException) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) NoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException) MissingServletRequestPartException(org.springframework.web.multipart.support.MissingServletRequestPartException) BindException(org.springframework.validation.BindException) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException) AsyncRequestTimeoutException(org.springframework.web.context.request.async.AsyncRequestTimeoutException) MissingServletRequestParameterException(org.springframework.web.bind.MissingServletRequestParameterException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ServletRequestBindingException(org.springframework.web.bind.ServletRequestBindingException) TypeMismatchException(org.springframework.beans.TypeMismatchException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) Test(org.junit.Test)

Example 5 with HttpMediaTypeNotSupportedException

use of org.springframework.web.HttpMediaTypeNotSupportedException 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)

Aggregations

HttpMediaTypeNotSupportedException (org.springframework.web.HttpMediaTypeNotSupportedException)6 MediaType (org.springframework.http.MediaType)5 Test (org.junit.Test)3 InvalidMediaTypeException (org.springframework.http.InvalidMediaTypeException)2 HttpMessageNotReadableException (org.springframework.http.converter.HttpMessageNotReadableException)2 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)2 HttpMediaTypeNotAcceptableException (org.springframework.web.HttpMediaTypeNotAcceptableException)2 HttpRequestMethodNotSupportedException (org.springframework.web.HttpRequestMethodNotSupportedException)2 IOException (java.io.IOException)1 ConversionNotSupportedException (org.springframework.beans.ConversionNotSupportedException)1 TypeMismatchException (org.springframework.beans.TypeMismatchException)1 ResolvableType (org.springframework.core.ResolvableType)1 HttpMethod (org.springframework.http.HttpMethod)1 HttpRequest (org.springframework.http.HttpRequest)1 GenericHttpMessageConverter (org.springframework.http.converter.GenericHttpMessageConverter)1 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)1 HttpMessageNotWritableException (org.springframework.http.converter.HttpMessageNotWritableException)1 ServletServerHttpRequest (org.springframework.http.server.ServletServerHttpRequest)1 BindException (org.springframework.validation.BindException)1 MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)1