org.springframework.http.MediaType#sortBySpecificityAndQuality ( )源码实例Demo

下面列出了org.springframework.http.MediaType#sortBySpecificityAndQuality ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * {@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());
	}
}
 
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;
}
 
/**
 * {@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());
	}
}
 
源代码4 项目: lams   文件: HeaderContentNegotiationStrategy.java
/**
 * {@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());
	}
}
 
/**
 * {@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());
	}
}
 
@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());
	}
}
 
/**
 * 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;
	}
}
 
/**
 * 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;
    }
}
 
@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());
	}
}
 
/**
 * 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;
	}
}
 
源代码11 项目: Sentinel   文件: DefaultBlockRequestHandler.java
/**
 * 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;
    }
}
 
源代码12 项目: Sentinel   文件: DefaultBlockRequestHandler.java
/**
 * 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;
    }
}
 
源代码13 项目: syncope   文件: SyncopeSRAWebExceptionHandler.java
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;
    }
}
 
/**
 * 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;
	}
}
 
源代码15 项目: timely   文件: MetricsResponse.java
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);
}
 
源代码16 项目: timely   文件: MetricsResponse.java
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;
}
 
/**
 * 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;
}
 
/**
 * 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;
}
 
/**
 * 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;
}
 
/**
 * 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);
	}
}