Java Code Examples for org.springframework.http.MediaType#sortBySpecificityAndQuality()

The following examples show how to use org.springframework.http.MediaType#sortBySpecificityAndQuality() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HeaderContentNegotiationStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * {@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);
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return !CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST;
	}
	catch (InvalidMediaTypeException ex) {
		throw new HttpMediaTypeNotAcceptableException(
				"Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage());
	}
}
 
Example 2
Source File: ContentTypeNegotiationMessageRenderer.java    From gocd with Apache License 2.0 6 votes vote down vote up
public ContentTypeAwareResponse getResponse(HttpServletRequest request) {
    try {
        List<MediaType> mediaTypes = MediaType.parseMediaTypes(request.getHeader("Accept"));
        MediaType.sortBySpecificityAndQuality(mediaTypes);

        for (MediaType mediaType : mediaTypes) {
            final ContentTypeAwareResponse accessDeniedHandler = ACCESS_DENIED_HANDLER_MAP.get(mediaType.removeQualityValue());
            if (accessDeniedHandler != null) {
                return accessDeniedHandler;
            }
        }
    } catch (Exception ignore) {
    }

    if (request.getRequestURI().endsWith(".xml")) {
        return APPLICATION_XML_REQUEST_HANDLER;
    }
    return JSON_ACCESS_DENIED_HANDLER;
}
 
Example 3
Source File: HeaderContentNegotiationStrategy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws HttpMediaTypeNotAcceptableException if the 'Accept' header
 * cannot be parsed.
 */
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request)
		throws HttpMediaTypeNotAcceptableException {

	String header = request.getHeader(HttpHeaders.ACCEPT);
	if (!StringUtils.hasText(header)) {
		return Collections.emptyList();
	}
	try {
		List<MediaType> mediaTypes = MediaType.parseMediaTypes(header);
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return mediaTypes;
	}
	catch (InvalidMediaTypeException ex) {
		throw new HttpMediaTypeNotAcceptableException(
				"Could not parse 'Accept' header [" + header + "]: " + ex.getMessage());
	}
}
 
Example 4
Source File: HeaderContentNegotiationStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@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 Collections.<MediaType>emptyList();
	}

	List<String> headerValues = Arrays.asList(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());
	}
}
 
Example 5
Source File: HeaderContentNegotiationStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * {@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);
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return !CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST;
	}
	catch (InvalidMediaTypeException ex) {
		throw new HttpMediaTypeNotAcceptableException(
				"Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage());
	}
}
 
Example 6
Source File: DefaultBlockRequestHandler.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Reference from {@code DefaultErrorWebExceptionHandler} of Spring Boot.
 */
private boolean acceptsHtml(ServerWebExchange exchange) {
    try {
        List<MediaType> acceptedMediaTypes = exchange.getRequest().getHeaders().getAccept();
        acceptedMediaTypes.remove(MediaType.ALL);
        MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
        return acceptedMediaTypes.stream()
            .anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
    } catch (InvalidMediaTypeException ex) {
        return false;
    }
}
 
Example 7
Source File: MetricsResponse.java    From timely with Apache License 2.0 5 votes vote down vote up
public FullHttpResponse toHttpResponse(String acceptHeader) throws Exception {
    MediaType negotiatedType = MediaType.TEXT_HTML;
    if (null != acceptHeader) {
        List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
        MediaType.sortBySpecificityAndQuality(requestedTypes);
        LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
        for (MediaType t : requestedTypes) {
            if (t.includes(MediaType.TEXT_HTML)) {
                negotiatedType = MediaType.TEXT_HTML;
                LOG.trace("{} allows HTML", t.toString());
                break;
            }
            if (t.includes(MediaType.APPLICATION_JSON)) {
                negotiatedType = MediaType.APPLICATION_JSON;
                LOG.trace("{} allows JSON", t.toString());
                break;
            }
        }
    }
    byte[] buf = null;
    Object responseType = Constants.HTML_TYPE;
    if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
        buf = this.generateJson(JsonUtil.getObjectMapper()).getBytes(StandardCharsets.UTF_8);
        responseType = Constants.JSON_TYPE;
    } else {
        buf = this.generateHtml().toString().getBytes(StandardCharsets.UTF_8);
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, responseType);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example 8
Source File: MetricsResponse.java    From timely with Apache License 2.0 5 votes vote down vote up
public TextWebSocketFrame toWebSocketResponse(String acceptHeader) throws Exception {
    MediaType negotiatedType = MediaType.TEXT_HTML;
    if (null != acceptHeader) {
        List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
        MediaType.sortBySpecificityAndQuality(requestedTypes);
        LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
        for (MediaType t : requestedTypes) {
            if (t.includes(MediaType.TEXT_HTML)) {
                negotiatedType = MediaType.TEXT_HTML;
                LOG.trace("{} allows HTML", t.toString());
                break;
            }
            if (t.includes(MediaType.APPLICATION_JSON)) {
                negotiatedType = MediaType.APPLICATION_JSON;
                LOG.trace("{} allows JSON", t.toString());
                break;
            }
        }
    }
    String result = null;
    if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
        result = this.generateJson(JsonUtil.getObjectMapper());
    } else {
        result = this.generateHtml().toString();
    }
    return new TextWebSocketFrame(result);
}
 
Example 9
Source File: ContentNegotiatingViewResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the list of {@link MediaType} for the given {@link HttpServletRequest}.
 * @param request the current servlet request
 * @return the list of media types requested, if any
 */
protected List<MediaType> getMediaTypes(HttpServletRequest request) {
	try {
		ServletWebRequest webRequest = new ServletWebRequest(request);

		List<MediaType> acceptableMediaTypes = this.contentNegotiationManager.resolveMediaTypes(webRequest);
		acceptableMediaTypes = (!acceptableMediaTypes.isEmpty() ? acceptableMediaTypes :
				Collections.singletonList(MediaType.ALL));

		List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request);
		Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
		for (MediaType acceptable : acceptableMediaTypes) {
			for (MediaType producible : producibleMediaTypes) {
				if (acceptable.isCompatibleWith(producible)) {
					compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible));
				}
			}
		}
		List<MediaType> selectedMediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
		MediaType.sortBySpecificityAndQuality(selectedMediaTypes);
		if (logger.isDebugEnabled()) {
			logger.debug("Requested media types are " + selectedMediaTypes + " based on Accept header types " +
					"and producible media types " + producibleMediaTypes + ")");
		}
		return selectedMediaTypes;
	}
	catch (HttpMediaTypeNotAcceptableException ex) {
		return null;
	}
}
 
Example 10
Source File: SyncopeSRAWebExceptionHandler.java    From syncope with Apache License 2.0 5 votes vote down vote up
private boolean acceptsTextHtml(final ServerHttpRequest request) {
    try {
        List<MediaType> acceptedMediaTypes = request.getHeaders().getAccept();
        acceptedMediaTypes.remove(MediaType.ALL);
        MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
        return acceptedMediaTypes.stream().anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
    } catch (InvalidMediaTypeException e) {
        LOG.debug("Unexpected exception", e);
        return false;
    }
}
 
Example 11
Source File: DefaultBlockRequestHandler.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Reference from {@code DefaultErrorWebExceptionHandler} of Spring Boot.
 */
private boolean acceptsHtml(ServerWebExchange exchange) {
    try {
        List<MediaType> acceptedMediaTypes = exchange.getRequest().getHeaders().getAccept();
        acceptedMediaTypes.remove(MediaType.ALL);
        MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
        return acceptedMediaTypes.stream()
            .anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
    } catch (InvalidMediaTypeException ex) {
        return false;
    }
}
 
Example 12
Source File: HeaderContentTypeResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	try {
		List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return (!CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST);
	}
	catch (InvalidMediaTypeException ex) {
		String value = exchange.getRequest().getHeaders().getFirst("Accept");
		throw new NotAcceptableStatusException(
				"Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
	}
}
 
Example 13
Source File: ContentNegotiatingViewResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Determines the list of {@link MediaType} for the given {@link HttpServletRequest}.
 * @param request the current servlet request
 * @return the list of media types requested, if any
 */
@Nullable
protected List<MediaType> getMediaTypes(HttpServletRequest request) {
	Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set");
	try {
		ServletWebRequest webRequest = new ServletWebRequest(request);
		List<MediaType> acceptableMediaTypes = this.contentNegotiationManager.resolveMediaTypes(webRequest);
		List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request);
		Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
		for (MediaType acceptable : acceptableMediaTypes) {
			for (MediaType producible : producibleMediaTypes) {
				if (acceptable.isCompatibleWith(producible)) {
					compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible));
				}
			}
		}
		List<MediaType> selectedMediaTypes = new ArrayList<>(compatibleMediaTypes);
		MediaType.sortBySpecificityAndQuality(selectedMediaTypes);
		return selectedMediaTypes;
	}
	catch (HttpMediaTypeNotAcceptableException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug(ex.getMessage());
		}
		return null;
	}
}
 
Example 14
Source File: HeaderContentTypeResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	try {
		List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
		MediaType.sortBySpecificityAndQuality(mediaTypes);
		return (!CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST);
	}
	catch (InvalidMediaTypeException ex) {
		String value = exchange.getRequest().getHeaders().getFirst("Accept");
		throw new NotAcceptableStatusException(
				"Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
	}
}
 
Example 15
Source File: DefaultBlockRequestHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Reference from {@code DefaultErrorWebExceptionHandler} of Spring Boot.
 */
private boolean acceptsHtml(ServerWebExchange exchange) {
    try {
        List<MediaType> acceptedMediaTypes = exchange.getRequest().getHeaders().getAccept();
        acceptedMediaTypes.remove(MediaType.ALL);
        MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
        return acceptedMediaTypes.stream()
            .anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
    } catch (InvalidMediaTypeException ex) {
        return false;
    }
}
 
Example 16
Source File: ContentNegotiatingViewResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Determines the list of {@link MediaType} for the given {@link HttpServletRequest}.
 * @param request the current servlet request
 * @return the list of media types requested, if any
 */
@Nullable
protected List<MediaType> getMediaTypes(HttpServletRequest request) {
	Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set");
	try {
		ServletWebRequest webRequest = new ServletWebRequest(request);
		List<MediaType> acceptableMediaTypes = this.contentNegotiationManager.resolveMediaTypes(webRequest);
		List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request);
		Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
		for (MediaType acceptable : acceptableMediaTypes) {
			for (MediaType producible : producibleMediaTypes) {
				if (acceptable.isCompatibleWith(producible)) {
					compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible));
				}
			}
		}
		List<MediaType> selectedMediaTypes = new ArrayList<>(compatibleMediaTypes);
		MediaType.sortBySpecificityAndQuality(selectedMediaTypes);
		return selectedMediaTypes;
	}
	catch (HttpMediaTypeNotAcceptableException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug(ex.getMessage());
		}
		return null;
	}
}
 
Example 17
Source File: HttpMessageConverterResolver.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
/**
 * Resolve the most match {@link HttpMessageConverter} from {@link RequestMetadata}.
 * @param requestMetadata {@link RequestMetadata}
 * @param restMethodMetadata {@link RestMethodMetadata}
 * @return instance of {@link HttpMessageConverterHolder}
 */
public HttpMessageConverterHolder resolve(RequestMetadata requestMetadata,
		RestMethodMetadata restMethodMetadata) {

	HttpMessageConverterHolder httpMessageConverterHolder = null;

	Class<?> returnValueClass = resolveReturnValueClass(restMethodMetadata);

	/**
	 * @see AbstractMessageConverterMethodProcessor#writeWithMessageConverters(T,
	 * MethodParameter, ServletServerHttpRequest, ServletServerHttpResponse)
	 */
	List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(requestMetadata);
	List<MediaType> producibleMediaTypes = getProducibleMediaTypes(restMethodMetadata,
			returnValueClass);

	Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
	for (MediaType requestedType : requestedMediaTypes) {
		for (MediaType producibleType : producibleMediaTypes) {
			if (requestedType.isCompatibleWith(producibleType)) {
				compatibleMediaTypes
						.add(getMostSpecificMediaType(requestedType, producibleType));
			}
		}
	}

	if (compatibleMediaTypes.isEmpty()) {
		return httpMessageConverterHolder;
	}

	List<MediaType> mediaTypes = new ArrayList<>(compatibleMediaTypes);

	MediaType.sortBySpecificityAndQuality(mediaTypes);

	MediaType selectedMediaType = null;
	for (MediaType mediaType : mediaTypes) {
		if (mediaType.isConcrete()) {
			selectedMediaType = mediaType;
			break;
		}
		else if (mediaType.equals(MediaType.ALL)
				|| mediaType.equals(MEDIA_TYPE_APPLICATION)) {
			selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
			break;
		}
	}

	if (selectedMediaType != null) {
		selectedMediaType = selectedMediaType.removeQualityValue();
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
				httpMessageConverterHolder = new HttpMessageConverterHolder(
						selectedMediaType, messageConverter);
				break;
			}
		}
	}

	return httpMessageConverterHolder;
}
 
Example 18
Source File: HandlerResultHandlerSupport.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Select the best media type for the current request through a content negotiation algorithm.
 * @param exchange the current request
 * @param producibleTypesSupplier the media types that can be produced for the current request
 * @return the selected media type, or {@code null} if none
 */
@Nullable
protected MediaType selectMediaType(ServerWebExchange exchange,
		Supplier<List<MediaType>> producibleTypesSupplier) {

	MediaType contentType = exchange.getResponse().getHeaders().getContentType();
	if (contentType != null && contentType.isConcrete()) {
		if (logger.isDebugEnabled()) {
			logger.debug(exchange.getLogPrefix() + "Found 'Content-Type:" + contentType + "' in response");
		}
		return contentType;
	}

	List<MediaType> acceptableTypes = getAcceptableTypes(exchange);
	List<MediaType> producibleTypes = getProducibleTypes(exchange, producibleTypesSupplier);

	Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
	for (MediaType acceptable : acceptableTypes) {
		for (MediaType producible : producibleTypes) {
			if (acceptable.isCompatibleWith(producible)) {
				compatibleMediaTypes.add(selectMoreSpecificMediaType(acceptable, producible));
			}
		}
	}

	List<MediaType> result = new ArrayList<>(compatibleMediaTypes);
	MediaType.sortBySpecificityAndQuality(result);

	MediaType selected = null;
	for (MediaType mediaType : result) {
		if (mediaType.isConcrete()) {
			selected = mediaType;
			break;
		}
		else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) {
			selected = MediaType.APPLICATION_OCTET_STREAM;
			break;
		}
	}

	if (selected != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Using '" + selected + "' given " +
					acceptableTypes + " and supported " + producibleTypes);
		}
	}
	else if (logger.isDebugEnabled()) {
		logger.debug(exchange.getLogPrefix() +
				"No match for " + acceptableTypes + ", supported: " + producibleTypes);
	}

	return selected;
}
 
Example 19
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Writes the given return type to the given output message.
 * @param returnValue 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 {@code Accept} header on
 * the request cannot be met by the message converters
 */
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType,
		ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	Class<?> returnValueClass = getReturnValueType(returnValue, returnType);
	Type returnValueType = getGenericType(returnType);
	HttpServletRequest servletRequest = inputMessage.getServletRequest();
	List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest);
	List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass, returnValueType);

	if (returnValue != null && producibleMediaTypes.isEmpty()) {
		throw new IllegalArgumentException("No converter found for return value of type: " + returnValueClass);
	}

	Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
	for (MediaType requestedType : requestedMediaTypes) {
		for (MediaType producibleType : producibleMediaTypes) {
			if (requestedType.isCompatibleWith(producibleType)) {
				compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType));
			}
		}
	}
	if (compatibleMediaTypes.isEmpty()) {
		if (returnValue != null) {
			throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
		}
		return;
	}

	List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
	MediaType.sortBySpecificityAndQuality(mediaTypes);

	MediaType selectedMediaType = null;
	for (MediaType mediaType : mediaTypes) {
		if (mediaType.isConcrete()) {
			selectedMediaType = mediaType;
			break;
		}
		else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
			selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
			break;
		}
	}

	if (selectedMediaType != null) {
		selectedMediaType = selectedMediaType.removeQualityValue();
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter instanceof GenericHttpMessageConverter) {
				if (((GenericHttpMessageConverter<T>) messageConverter).canWrite(returnValueType,
						returnValueClass, selectedMediaType)) {
					returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
							(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
							inputMessage, outputMessage);
					if (returnValue != null) {
						addContentDispositionHeader(inputMessage, outputMessage);
						((GenericHttpMessageConverter<T>) messageConverter).write(returnValue,
								returnValueType, selectedMediaType, outputMessage);
						if (logger.isDebugEnabled()) {
							logger.debug("Written [" + returnValue + "] as \"" +
									selectedMediaType + "\" using [" + messageConverter + "]");
						}
					}
					return;
				}
			}
			else if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
				returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
						(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
						inputMessage, outputMessage);
				if (returnValue != null) {
					addContentDispositionHeader(inputMessage, outputMessage);
					((HttpMessageConverter<T>) messageConverter).write(returnValue,
							selectedMediaType, outputMessage);
					if (logger.isDebugEnabled()) {
						logger.debug("Written [" + returnValue + "] as \"" +
								selectedMediaType + "\" using [" + messageConverter + "]");
					}
				}
				return;
			}
		}
	}

	if (returnValue != null) {
		throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
	}
}
 
Example 20
Source File: HandlerResultHandlerSupport.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Select the best media type for the current request through a content negotiation algorithm.
 * @param exchange the current request
 * @param producibleTypesSupplier the media types that can be produced for the current request
 * @return the selected media type, or {@code null} if none
 */
@Nullable
protected MediaType selectMediaType(
		ServerWebExchange exchange, Supplier<List<MediaType>> producibleTypesSupplier) {

	MediaType contentType = exchange.getResponse().getHeaders().getContentType();
	if (contentType != null && contentType.isConcrete()) {
		if (logger.isDebugEnabled()) {
			logger.debug(exchange.getLogPrefix() + "Found 'Content-Type:" + contentType + "' in response");
		}
		return contentType;
	}

	List<MediaType> acceptableTypes = getAcceptableTypes(exchange);
	List<MediaType> producibleTypes = getProducibleTypes(exchange, producibleTypesSupplier);

	Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
	for (MediaType acceptable : acceptableTypes) {
		for (MediaType producible : producibleTypes) {
			if (acceptable.isCompatibleWith(producible)) {
				compatibleMediaTypes.add(selectMoreSpecificMediaType(acceptable, producible));
			}
		}
	}

	List<MediaType> result = new ArrayList<>(compatibleMediaTypes);
	MediaType.sortBySpecificityAndQuality(result);

	MediaType selected = null;
	for (MediaType mediaType : result) {
		if (mediaType.isConcrete()) {
			selected = mediaType;
			break;
		}
		else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) {
			selected = MediaType.APPLICATION_OCTET_STREAM;
			break;
		}
	}

	if (selected != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Using '" + selected + "' given " + acceptableTypes +
					" and supported " + producibleTypes);
		}
	}
	else if (logger.isDebugEnabled()) {
		logger.debug(exchange.getLogPrefix() +
				"No match for " + acceptableTypes + ", supported: " + producibleTypes);
	}

	return selected;
}