Search in sources :

Example 11 with HttpMediaTypeNotAcceptableException

use of org.springframework.web.HttpMediaTypeNotAcceptableException in project spring-security by spring-projects.

the class MediaTypeRequestMatcher method matches.

public boolean matches(HttpServletRequest request) {
    List<MediaType> httpRequestMediaTypes;
    try {
        httpRequestMediaTypes = this.contentNegotiationStrategy.resolveMediaTypes(new ServletWebRequest(request));
    } catch (HttpMediaTypeNotAcceptableException e) {
        this.logger.debug("Failed to parse MediaTypes, returning false", e);
        return false;
    }
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("httpRequestMediaTypes=" + httpRequestMediaTypes);
    }
    for (MediaType httpRequestMediaType : httpRequestMediaTypes) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Processing " + httpRequestMediaType);
        }
        if (shouldIgnore(httpRequestMediaType)) {
            this.logger.debug("Ignoring");
            continue;
        }
        if (this.useEquals) {
            boolean isEqualTo = this.matchingMediaTypes.contains(httpRequestMediaType);
            this.logger.debug("isEqualTo " + isEqualTo);
            return isEqualTo;
        }
        for (MediaType matchingMediaType : this.matchingMediaTypes) {
            boolean isCompatibleWith = matchingMediaType.isCompatibleWith(httpRequestMediaType);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug(matchingMediaType + " .isCompatibleWith " + httpRequestMediaType + " = " + isCompatibleWith);
            }
            if (isCompatibleWith) {
                return true;
            }
        }
    }
    this.logger.debug("Did not match any media types");
    return false;
}
Also used : HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) MediaType(org.springframework.http.MediaType) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest)

Example 12 with HttpMediaTypeNotAcceptableException

use of org.springframework.web.HttpMediaTypeNotAcceptableException in project nzbhydra2 by theotherp.

the class ErrorHandler method resolveMediaTypes.

private List<MediaType> resolveMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException {
    Enumeration<String> headerValueArray = request.getHeaders(HttpHeaders.ACCEPT);
    if (headerValueArray == null) {
        return Collections.<MediaType>emptyList();
    }
    List<String> headerValues = Collections.list(headerValueArray);
    try {
        List<MediaType> mediaTypes = MediaType.parseMediaTypes(headerValues);
        MediaType.sortBySpecificityAndQuality(mediaTypes);
        return mediaTypes;
    } catch (InvalidMediaTypeException ex) {
        throw new HttpMediaTypeNotAcceptableException("Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage());
    }
}
Also used : HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException)

Example 13 with HttpMediaTypeNotAcceptableException

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

the class ResponseEntityExceptionHandlerTests method httpMediaTypeNotAcceptable.

@Test
public void httpMediaTypeNotAcceptable() {
    Exception ex = new HttpMediaTypeNotAcceptableException("");
    testException(ex);
}
Also used : HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) MissingPathVariableException(org.springframework.web.bind.MissingPathVariableException) ServletException(jakarta.servlet.ServletException) 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.jupiter.api.Test)

Example 14 with HttpMediaTypeNotAcceptableException

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

the class AbstractMessageConverterMethodProcessor method writeWithMessageConverters.

/**
 * Writes the given return type to the given output message.
 * @param value 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 the {@code Accept} header on the request cannot be met by the message converters
 * @throws HttpMessageNotWritableException thrown if a given message cannot
 * be written by a converter, or if the content-type chosen by the server
 * has no compatible converter.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected <T> void writeWithMessageConverters(@Nullable T value, MethodParameter returnType, ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
    Object body;
    Class<?> valueType;
    Type targetType;
    if (value instanceof CharSequence) {
        body = value.toString();
        valueType = String.class;
        targetType = String.class;
    } else {
        body = value;
        valueType = getReturnValueType(body, returnType);
        targetType = GenericTypeResolver.resolveType(getGenericType(returnType), returnType.getContainingClass());
    }
    if (isResourceType(value, returnType)) {
        outputMessage.getHeaders().set(HttpHeaders.ACCEPT_RANGES, "bytes");
        if (value != null && inputMessage.getHeaders().getFirst(HttpHeaders.RANGE) != null && outputMessage.getServletResponse().getStatus() == 200) {
            Resource resource = (Resource) value;
            try {
                List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
                outputMessage.getServletResponse().setStatus(HttpStatus.PARTIAL_CONTENT.value());
                body = HttpRange.toResourceRegions(httpRanges, resource);
                valueType = body.getClass();
                targetType = RESOURCE_REGION_LIST_TYPE;
            } catch (IllegalArgumentException ex) {
                outputMessage.getHeaders().set(HttpHeaders.CONTENT_RANGE, "bytes */" + resource.contentLength());
                outputMessage.getServletResponse().setStatus(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE.value());
            }
        }
    }
    MediaType selectedMediaType = null;
    MediaType contentType = outputMessage.getHeaders().getContentType();
    boolean isContentTypePreset = contentType != null && contentType.isConcrete();
    if (isContentTypePreset) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found 'Content-Type:" + contentType + "' in response");
        }
        selectedMediaType = contentType;
    } else {
        HttpServletRequest request = inputMessage.getServletRequest();
        List<MediaType> acceptableTypes;
        try {
            acceptableTypes = getAcceptableMediaTypes(request);
        } catch (HttpMediaTypeNotAcceptableException ex) {
            int series = outputMessage.getServletResponse().getStatus() / 100;
            if (body == null || series == 4 || series == 5) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Ignoring error response content (if any). " + ex);
                }
                return;
            }
            throw ex;
        }
        List<MediaType> producibleTypes = getProducibleMediaTypes(request, valueType, targetType);
        if (body != null && producibleTypes.isEmpty()) {
            throw new HttpMessageNotWritableException("No converter found for return value of type: " + valueType);
        }
        List<MediaType> mediaTypesToUse = new ArrayList<>();
        for (MediaType requestedType : acceptableTypes) {
            for (MediaType producibleType : producibleTypes) {
                if (requestedType.isCompatibleWith(producibleType)) {
                    mediaTypesToUse.add(getMostSpecificMediaType(requestedType, producibleType));
                }
            }
        }
        if (mediaTypesToUse.isEmpty()) {
            if (body != null) {
                throw new HttpMediaTypeNotAcceptableException(producibleTypes);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("No match for " + acceptableTypes + ", supported: " + producibleTypes);
            }
            return;
        }
        MimeTypeUtils.sortBySpecificity(mediaTypesToUse);
        for (MediaType mediaType : mediaTypesToUse) {
            if (mediaType.isConcrete()) {
                selectedMediaType = mediaType;
                break;
            } else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) {
                selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
                break;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using '" + selectedMediaType + "', given " + acceptableTypes + " and supported " + producibleTypes);
        }
    }
    if (selectedMediaType != null) {
        selectedMediaType = selectedMediaType.removeQualityValue();
        for (HttpMessageConverter<?> converter : this.messageConverters) {
            GenericHttpMessageConverter genericConverter = (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
            if (genericConverter != null ? ((GenericHttpMessageConverter) converter).canWrite(targetType, valueType, selectedMediaType) : converter.canWrite(valueType, selectedMediaType)) {
                body = getAdvice().beforeBodyWrite(body, returnType, selectedMediaType, (Class<? extends HttpMessageConverter<?>>) converter.getClass(), inputMessage, outputMessage);
                if (body != null) {
                    Object theBody = body;
                    LogFormatUtils.traceDebug(logger, traceOn -> "Writing [" + LogFormatUtils.formatValue(theBody, !traceOn) + "]");
                    addContentDispositionHeader(inputMessage, outputMessage);
                    if (genericConverter != null) {
                        genericConverter.write(body, targetType, selectedMediaType, outputMessage);
                    } else {
                        ((HttpMessageConverter) converter).write(body, selectedMediaType, outputMessage);
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Nothing to write: null body");
                    }
                }
                return;
            }
        }
    }
    if (body != null) {
        Set<MediaType> producibleMediaTypes = (Set<MediaType>) inputMessage.getServletRequest().getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
        if (isContentTypePreset || !CollectionUtils.isEmpty(producibleMediaTypes)) {
            throw new HttpMessageNotWritableException("No converter for [" + valueType + "] with preset Content-Type '" + contentType + "'");
        }
        throw new HttpMediaTypeNotAcceptableException(getSupportedMediaTypes(body.getClass()));
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) InputStreamResource(org.springframework.core.io.InputStreamResource) Resource(org.springframework.core.io.Resource) ArrayList(java.util.ArrayList) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ResolvableType(org.springframework.core.ResolvableType) MediaType(org.springframework.http.MediaType) Type(java.lang.reflect.Type) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter) MediaType(org.springframework.http.MediaType) HttpRange(org.springframework.http.HttpRange) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter)

Example 15 with HttpMediaTypeNotAcceptableException

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

the class HeaderContentNegotiationStrategy method resolveMediaTypes.

/**
 * {@inheritDoc}
 * @throws HttpMediaTypeNotAcceptableException if the 'Accept' header cannot be parsed
 */
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
    String[] headerValueArray = request.getHeaderValues(HttpHeaders.ACCEPT);
    if (headerValueArray == null) {
        return MEDIA_TYPE_ALL_LIST;
    }
    List<String> headerValues = Arrays.asList(headerValueArray);
    try {
        List<MediaType> mediaTypes = MediaType.parseMediaTypes(headerValues);
        MimeTypeUtils.sortBySpecificity(mediaTypes);
        return !CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST;
    } catch (InvalidMediaTypeException ex) {
        throw new HttpMediaTypeNotAcceptableException("Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage());
    }
}
Also used : HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) MediaType(org.springframework.http.MediaType) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Aggregations

HttpMediaTypeNotAcceptableException (org.springframework.web.HttpMediaTypeNotAcceptableException)15 MediaType (org.springframework.http.MediaType)10 ArrayList (java.util.ArrayList)4 LinkedHashSet (java.util.LinkedHashSet)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Test (org.junit.jupiter.api.Test)2 InvalidMediaTypeException (org.springframework.http.InvalidMediaTypeException)2 HttpMessageNotWritableException (org.springframework.http.converter.HttpMessageNotWritableException)2 HttpMediaTypeNotSupportedException (org.springframework.web.HttpMediaTypeNotSupportedException)2 HttpRequestMethodNotSupportedException (org.springframework.web.HttpRequestMethodNotSupportedException)2 ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)2 ServletException (jakarta.servlet.ServletException)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 Type (java.lang.reflect.Type)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 ConversionNotSupportedException (org.springframework.beans.ConversionNotSupportedException)1 TypeMismatchException (org.springframework.beans.TypeMismatchException)1