Search in sources :

Example 6 with InvalidMediaTypeException

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

the class ServletServerHttpRequest method getHeaders.

@Override
public HttpHeaders getHeaders() {
    if (this.headers == null) {
        this.headers = new HttpHeaders();
        for (Enumeration<?> headerNames = this.servletRequest.getHeaderNames(); headerNames.hasMoreElements(); ) {
            String headerName = (String) headerNames.nextElement();
            for (Enumeration<?> headerValues = this.servletRequest.getHeaders(headerName); headerValues.hasMoreElements(); ) {
                String headerValue = (String) headerValues.nextElement();
                this.headers.add(headerName, headerValue);
            }
        }
        // HttpServletRequest exposes some headers as properties: we should include those if not already present
        try {
            MediaType contentType = this.headers.getContentType();
            if (contentType == null) {
                String requestContentType = this.servletRequest.getContentType();
                if (StringUtils.hasLength(requestContentType)) {
                    contentType = MediaType.parseMediaType(requestContentType);
                    this.headers.setContentType(contentType);
                }
            }
            if (contentType != null && contentType.getCharset() == null) {
                String requestEncoding = this.servletRequest.getCharacterEncoding();
                if (StringUtils.hasLength(requestEncoding)) {
                    Charset charSet = Charset.forName(requestEncoding);
                    Map<String, String> params = new LinkedCaseInsensitiveMap<>();
                    params.putAll(contentType.getParameters());
                    params.put("charset", charSet.toString());
                    MediaType newContentType = new MediaType(contentType.getType(), contentType.getSubtype(), params);
                    this.headers.setContentType(newContentType);
                }
            }
        } catch (InvalidMediaTypeException ex) {
        // Ignore: simply not exposing an invalid content type in HttpHeaders...
        }
        if (this.headers.getContentLength() < 0) {
            int requestContentLength = this.servletRequest.getContentLength();
            if (requestContentLength != -1) {
                this.headers.setContentLength(requestContentLength);
            }
        }
    }
    return this.headers;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) LinkedCaseInsensitiveMap(org.springframework.util.LinkedCaseInsensitiveMap) MediaType(org.springframework.http.MediaType) Charset(java.nio.charset.Charset) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 7 with InvalidMediaTypeException

use of org.springframework.http.InvalidMediaTypeException in project spring-cloud-netflix by spring-cloud.

the class FormBodyWrapperFilter method shouldFilter.

@Override
public boolean shouldFilter() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    String contentType = request.getContentType();
    // Don't use this filter on GET method
    if (contentType == null) {
        return false;
    }
    // DispatcherServlet handler
    try {
        MediaType mediaType = MediaType.valueOf(contentType);
        return MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType) || (isDispatcherServletRequest(request) && MediaType.MULTIPART_FORM_DATA.includes(mediaType));
    } catch (InvalidMediaTypeException ex) {
        return false;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(org.springframework.http.MediaType) RequestContext(com.netflix.zuul.context.RequestContext) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 8 with InvalidMediaTypeException

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

the class AbstractSockJsService method handleRequest.

/**
 * This method determines the SockJS path and handles SockJS static URLs.
 * Session URLs and raw WebSocket requests are delegated to abstract methods.
 */
@Override
public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, @Nullable String sockJsPath, WebSocketHandler wsHandler) throws SockJsException {
    if (sockJsPath == null) {
        if (logger.isWarnEnabled()) {
            logger.warn(LogFormatUtils.formatValue("Expected SockJS path. Failing request: " + request.getURI(), -1, true));
        }
        response.setStatusCode(HttpStatus.NOT_FOUND);
        return;
    }
    try {
        request.getHeaders();
    } catch (InvalidMediaTypeException ex) {
    // As per SockJS protocol content-type can be ignored (it's always json)
    }
    String requestInfo = (logger.isDebugEnabled() ? request.getMethod() + " " + request.getURI() : null);
    try {
        if (sockJsPath.isEmpty() || sockJsPath.equals("/")) {
            if (requestInfo != null) {
                logger.debug("Processing transport request: " + requestInfo);
            }
            if ("websocket".equalsIgnoreCase(request.getHeaders().getUpgrade())) {
                response.setStatusCode(HttpStatus.BAD_REQUEST);
                return;
            }
            response.getHeaders().setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
            response.getBody().write("Welcome to SockJS!\n".getBytes(StandardCharsets.UTF_8));
        } else if (sockJsPath.equals("/info")) {
            if (requestInfo != null) {
                logger.debug("Processing transport request: " + requestInfo);
            }
            this.infoHandler.handle(request, response);
        } else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) {
            if (!getAllowedOrigins().isEmpty() && !getAllowedOrigins().contains("*") || !getAllowedOriginPatterns().isEmpty()) {
                if (requestInfo != null) {
                    logger.debug("Iframe support is disabled when an origin check is required. " + "Ignoring transport request: " + requestInfo);
                }
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            }
            if (getAllowedOrigins().isEmpty()) {
                response.getHeaders().add(XFRAME_OPTIONS_HEADER, "SAMEORIGIN");
            }
            if (requestInfo != null) {
                logger.debug("Processing transport request: " + requestInfo);
            }
            this.iframeHandler.handle(request, response);
        } else if (sockJsPath.equals("/websocket")) {
            if (isWebSocketEnabled()) {
                if (requestInfo != null) {
                    logger.debug("Processing transport request: " + requestInfo);
                }
                handleRawWebSocketRequest(request, response, wsHandler);
            } else if (requestInfo != null) {
                logger.debug("WebSocket disabled. Ignoring transport request: " + requestInfo);
            }
        } else {
            String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/");
            if (pathSegments.length != 3) {
                if (logger.isWarnEnabled()) {
                    logger.warn(LogFormatUtils.formatValue("Invalid SockJS path '" + sockJsPath + "' - " + "required to have 3 path segments", -1, true));
                }
                if (requestInfo != null) {
                    logger.debug("Ignoring transport request: " + requestInfo);
                }
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            }
            String serverId = pathSegments[0];
            String sessionId = pathSegments[1];
            String transport = pathSegments[2];
            if (!isWebSocketEnabled() && transport.equals("websocket")) {
                if (requestInfo != null) {
                    logger.debug("WebSocket disabled. Ignoring transport request: " + requestInfo);
                }
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            } else if (!validateRequest(serverId, sessionId, transport) || !validatePath(request)) {
                if (requestInfo != null) {
                    logger.debug("Ignoring transport request: " + requestInfo);
                }
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            }
            if (requestInfo != null) {
                logger.debug("Processing transport request: " + requestInfo);
            }
            handleTransportRequest(request, response, wsHandler, sessionId, transport);
        }
        response.close();
    } catch (IOException ex) {
        throw new SockJsException("Failed to write to the response", null, ex);
    }
}
Also used : SockJsException(org.springframework.web.socket.sockjs.SockJsException) MediaType(org.springframework.http.MediaType) IOException(java.io.IOException) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 9 with InvalidMediaTypeException

use of org.springframework.http.InvalidMediaTypeException 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
 * @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 = null;
    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 (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, inputMessage);
    } finally {
        if (message != null && message.hasBody()) {
            closeStreamIfNecessary(message.getBody());
        }
    }
    if (body == NO_VALUE) {
        if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) || (noContentType && !message.hasBody())) {
            return null;
        }
        throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes(targetClass != null ? targetClass : Object.class));
    }
    MediaType selectedContentType = contentType;
    Object theBody = body;
    LogFormatUtils.traceDebug(logger, traceOn -> {
        String formatted = LogFormatUtils.formatValue(theBody, !traceOn);
        return "Read \"" + selectedContentType + "\" to [" + formatted + "]";
    });
    return body;
}
Also used : HttpRequest(org.springframework.http.HttpRequest) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) HttpInputMessage(org.springframework.http.HttpInputMessage) 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) Nullable(org.springframework.lang.Nullable)

Example 10 with InvalidMediaTypeException

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

the class ConsumesRequestCondition method getMatchingCondition.

/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#includes(MediaType)}.
 * @param request the current request
 * @return the same instance if the condition contains no expressions;
 * or a new condition with matching expressions only;
 * or {@code null} if no expressions match
 */
@Override
@Nullable
public ConsumesRequestCondition getMatchingCondition(HttpServletRequest request) {
    if (CorsUtils.isPreFlightRequest(request)) {
        return EMPTY_CONDITION;
    }
    if (isEmpty()) {
        return this;
    }
    if (!hasBody(request) && !this.bodyRequired) {
        return EMPTY_CONDITION;
    }
    // Common media types are cached at the level of MimeTypeUtils
    MediaType contentType;
    try {
        contentType = StringUtils.hasLength(request.getContentType()) ? MediaType.parseMediaType(request.getContentType()) : MediaType.APPLICATION_OCTET_STREAM;
    } catch (InvalidMediaTypeException ex) {
        return null;
    }
    List<ConsumeMediaTypeExpression> result = getMatchingExpressions(contentType);
    return !CollectionUtils.isEmpty(result) ? new ConsumesRequestCondition(result) : null;
}
Also used : MediaType(org.springframework.http.MediaType) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException) Nullable(org.springframework.lang.Nullable)

Aggregations

InvalidMediaTypeException (org.springframework.http.InvalidMediaTypeException)12 MediaType (org.springframework.http.MediaType)12 NotAcceptableStatusException (org.springframework.web.server.NotAcceptableStatusException)4 HttpMethod (org.springframework.http.HttpMethod)3 HandlerMethod (org.springframework.web.method.HandlerMethod)3 IOException (java.io.IOException)2 HttpHeaders (org.springframework.http.HttpHeaders)2 ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)2 Nullable (org.springframework.lang.Nullable)2 HttpMediaTypeNotAcceptableException (org.springframework.web.HttpMediaTypeNotAcceptableException)2 HttpMediaTypeNotSupportedException (org.springframework.web.HttpMediaTypeNotSupportedException)2 MethodNotAllowedException (org.springframework.web.server.MethodNotAllowedException)2 ServerWebInputException (org.springframework.web.server.ServerWebInputException)2 UnsupportedMediaTypeStatusException (org.springframework.web.server.UnsupportedMediaTypeStatusException)2 RequestContext (com.netflix.zuul.context.RequestContext)1 Charset (java.nio.charset.Charset)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 ResolvableType (org.springframework.core.ResolvableType)1 FileSystemResource (org.springframework.core.io.FileSystemResource)1 HttpInputMessage (org.springframework.http.HttpInputMessage)1