org.springframework.web.HttpMediaTypeNotAcceptableException Java Examples

The following examples show how to use org.springframework.web.HttpMediaTypeNotAcceptableException. 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: AbstractMappingContentNegotiationStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Override to provide handling when a key is not resolved via.
 * {@link #lookupMediaType}. Sub-classes can take further steps to
 * determine the media type(s). If a MediaType is returned from
 * this method it will be added to the cache in the base class.
 */
@Nullable
protected MediaType handleNoMatch(NativeWebRequest request, String key)
		throws HttpMediaTypeNotAcceptableException {

	if (!isUseRegisteredExtensionsOnly()) {
		Optional<MediaType> mediaType = MediaTypeFactory.getMediaType("file." + key);
		if (mediaType.isPresent()) {
			return mediaType.get();
		}
	}
	if (isIgnoreUnknownExtensions()) {
		return null;
	}
	throw new HttpMediaTypeNotAcceptableException(getAllMediaTypes());
}
 
Example #2
Source File: AbstractMessageConverterMethodProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private boolean safeMediaTypesForExtension(String extension) {
	List<MediaType> mediaTypes = null;
	try {
		mediaTypes = this.pathStrategy.resolveMediaTypeKey(null, extension);
	}
	catch (HttpMediaTypeNotAcceptableException ex) {
		// Ignore
	}
	if (CollectionUtils.isEmpty(mediaTypes)) {
		return false;
	}
	for (MediaType mediaType : mediaTypes) {
		if (!safeMediaType(mediaType)) {
			return false;
		}
	}
	return true;
}
 
Example #3
Source File: AbstractMessageConverterMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private boolean safeMediaTypesForExtension(NativeWebRequest request, String extension) {
	List<MediaType> mediaTypes = null;
	try {
		mediaTypes = this.pathStrategy.resolveMediaTypeKey(request, extension);
	}
	catch (HttpMediaTypeNotAcceptableException ex) {
		// Ignore
	}
	if (CollectionUtils.isEmpty(mediaTypes)) {
		return false;
	}
	for (MediaType mediaType : mediaTypes) {
		if (!safeMediaType(mediaType)) {
			return false;
		}
	}
	return true;
}
 
Example #4
Source File: ProducesRequestCondition.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Compares this and another "produces" condition as follows:
 * <ol>
 * <li>Sort 'Accept' header media types by quality value via
 * {@link MediaType#sortByQualityValue(List)} and iterate the list.
 * <li>Get the first index of matching media types in each "produces"
 * condition first matching with {@link MediaType#equals(Object)} and
 * then with {@link MediaType#includes(MediaType)}.
 * <li>If a lower index is found, the condition at that index wins.
 * <li>If both indexes are equal, the media types at the index are
 * compared further with {@link MediaType#SPECIFICITY_COMPARATOR}.
 * </ol>
 * <p>It is assumed that both instances have been obtained via
 * {@link #getMatchingCondition(HttpServletRequest)} and each instance
 * contains the matching producible media type expression only or
 * is otherwise empty.
 */
@Override
public int compareTo(ProducesRequestCondition other, HttpServletRequest request) {
	try {
		List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(request);
		for (MediaType acceptedMediaType : acceptedMediaTypes) {
			int thisIndex = this.indexOfEqualMediaType(acceptedMediaType);
			int otherIndex = other.indexOfEqualMediaType(acceptedMediaType);
			int result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
			if (result != 0) {
				return result;
			}
			thisIndex = this.indexOfIncludedMediaType(acceptedMediaType);
			otherIndex = other.indexOfIncludedMediaType(acceptedMediaType);
			result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
			if (result != 0) {
				return result;
			}
		}
		return 0;
	}
	catch (HttpMediaTypeNotAcceptableException ex) {
		// should never happen
		throw new IllegalStateException("Cannot compare without having any requested media types", ex);
	}
}
 
Example #5
Source File: AbstractMappingContentNegotiationStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * An alternative to {@link #resolveMediaTypes(NativeWebRequest)} that accepts
 * an already extracted key.
 * @since 3.2.16
 */
public List<MediaType> resolveMediaTypeKey(NativeWebRequest webRequest, String key)
		throws HttpMediaTypeNotAcceptableException {

	if (StringUtils.hasText(key)) {
		MediaType mediaType = lookupMediaType(key);
		if (mediaType != null) {
			handleMatch(key, mediaType);
			return Collections.singletonList(mediaType);
		}
		mediaType = handleNoMatch(webRequest, key);
		if (mediaType != null) {
			addMapping(key, mediaType);
			return Collections.singletonList(mediaType);
		}
	}
	return Collections.emptyList();
}
 
Example #6
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 #7
Source File: AbstractMappingContentNegotiationStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * An alternative to {@link #resolveMediaTypes(NativeWebRequest)} that accepts
 * an already extracted key.
 * @since 3.2.16
 */
public List<MediaType> resolveMediaTypeKey(NativeWebRequest webRequest, @Nullable String key)
		throws HttpMediaTypeNotAcceptableException {

	if (StringUtils.hasText(key)) {
		MediaType mediaType = lookupMediaType(key);
		if (mediaType != null) {
			handleMatch(key, mediaType);
			return Collections.singletonList(mediaType);
		}
		mediaType = handleNoMatch(webRequest, key);
		if (mediaType != null) {
			addMapping(key, mediaType);
			return Collections.singletonList(mediaType);
		}
	}
	return MEDIA_TYPE_ALL_LIST;
}
 
Example #8
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 #9
Source File: AbstractMappingContentNegotiationStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * An alternative to {@link #resolveMediaTypes(NativeWebRequest)} that accepts
 * an already extracted key.
 * @since 3.2.16
 */
public List<MediaType> resolveMediaTypeKey(NativeWebRequest webRequest, @Nullable String key)
		throws HttpMediaTypeNotAcceptableException {

	if (StringUtils.hasText(key)) {
		MediaType mediaType = lookupMediaType(key);
		if (mediaType != null) {
			handleMatch(key, mediaType);
			return Collections.singletonList(mediaType);
		}
		mediaType = handleNoMatch(webRequest, key);
		if (mediaType != null) {
			addMapping(key, mediaType);
			return Collections.singletonList(mediaType);
		}
	}
	return MEDIA_TYPE_ALL_LIST;
}
 
Example #10
Source File: AbstractMappingContentNegotiationStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Override to provide handling when a key is not resolved via.
 * {@link #lookupMediaType}. Sub-classes can take further steps to
 * determine the media type(s). If a MediaType is returned from
 * this method it will be added to the cache in the base class.
 */
@Nullable
protected MediaType handleNoMatch(NativeWebRequest request, String key)
		throws HttpMediaTypeNotAcceptableException {

	if (!isUseRegisteredExtensionsOnly()) {
		Optional<MediaType> mediaType = MediaTypeFactory.getMediaType("file." + key);
		if (mediaType.isPresent()) {
			return mediaType.get();
		}
	}
	if (isIgnoreUnknownExtensions()) {
		return null;
	}
	throw new HttpMediaTypeNotAcceptableException(getAllMediaTypes());
}
 
Example #11
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 #12
Source File: ServletPathExtensionContentNegotiationStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Resolve file extension via {@link ServletContext#getMimeType(String)}
 * and also delegate to base class for a potential
 * {@link org.springframework.http.MediaTypeFactory} lookup.
 */
@Override
@Nullable
protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension)
		throws HttpMediaTypeNotAcceptableException {

	MediaType mediaType = null;
	String mimeType = this.servletContext.getMimeType("file." + extension);
	if (StringUtils.hasText(mimeType)) {
		mediaType = MediaType.parseMediaType(mimeType);
	}
	if (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) {
		MediaType superMediaType = super.handleNoMatch(webRequest, extension);
		if (superMediaType != null) {
			mediaType = superMediaType;
		}
	}
	return mediaType;
}
 
Example #13
Source File: ServletPathExtensionContentNegotiationStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Resolve file extension via {@link ServletContext#getMimeType(String)}
 * and also delegate to base class for a potential JAF lookup.
 */
@Override
protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension)
		throws HttpMediaTypeNotAcceptableException {

	MediaType mediaType = null;
	if (this.servletContext != null) {
		String mimeType = this.servletContext.getMimeType("file." + extension);
		if (StringUtils.hasText(mimeType)) {
			mediaType = MediaType.parseMediaType(mimeType);
		}
	}
	if (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) {
		MediaType superMediaType = super.handleNoMatch(webRequest, extension);
		if (superMediaType != null) {
			mediaType = superMediaType;
		}
	}
	return mediaType;
}
 
Example #14
Source File: AbstractMessageConverterMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
private boolean safeMediaTypesForExtension(NativeWebRequest request, String extension) {
	List<MediaType> mediaTypes = null;
	try {
		mediaTypes = this.pathStrategy.resolveMediaTypeKey(request, extension);
	}
	catch (HttpMediaTypeNotAcceptableException ex) {
		// Ignore
	}
	if (CollectionUtils.isEmpty(mediaTypes)) {
		return false;
	}
	for (MediaType mediaType : mediaTypes) {
		if (!safeMediaType(mediaType)) {
			return false;
		}
	}
	return true;
}
 
Example #15
Source File: ProducesRequestCondition.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Compares this and another "produces" condition as follows:
 * <ol>
 * <li>Sort 'Accept' header media types by quality value via
 * {@link MediaType#sortByQualityValue(List)} and iterate the list.
 * <li>Get the first index of matching media types in each "produces"
 * condition first matching with {@link MediaType#equals(Object)} and
 * then with {@link MediaType#includes(MediaType)}.
 * <li>If a lower index is found, the condition at that index wins.
 * <li>If both indexes are equal, the media types at the index are
 * compared further with {@link MediaType#SPECIFICITY_COMPARATOR}.
 * </ol>
 * <p>It is assumed that both instances have been obtained via
 * {@link #getMatchingCondition(HttpServletRequest)} and each instance
 * contains the matching producible media type expression only or
 * is otherwise empty.
 */
@Override
public int compareTo(ProducesRequestCondition other, HttpServletRequest request) {
	try {
		List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(request);
		for (MediaType acceptedMediaType : acceptedMediaTypes) {
			int thisIndex = this.indexOfEqualMediaType(acceptedMediaType);
			int otherIndex = other.indexOfEqualMediaType(acceptedMediaType);
			int result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
			if (result != 0) {
				return result;
			}
			thisIndex = this.indexOfIncludedMediaType(acceptedMediaType);
			otherIndex = other.indexOfIncludedMediaType(acceptedMediaType);
			result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
			if (result != 0) {
				return result;
			}
		}
		return 0;
	}
	catch (HttpMediaTypeNotAcceptableException ex) {
		// should never happen
		throw new IllegalStateException("Cannot compare without having any requested media types", ex);
	}
}
 
Example #16
Source File: ServletWebErrorHandler.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * Only handles {@link ServletException}s and {@link HttpMessageNotReadableException}s.
 *
 * @param exception The exception to examine.
 * @return {@code true} when can handle the {@code exception}, {@code false} otherwise.
 */
@Override
public boolean canHandle(Throwable exception) {
    return exception instanceof HttpMediaTypeNotAcceptableException ||
        exception instanceof HttpMediaTypeNotSupportedException ||
        exception instanceof HttpRequestMethodNotSupportedException ||
        exception instanceof MissingServletRequestParameterException ||
        exception instanceof MissingServletRequestPartException ||
        exception instanceof NoHandlerFoundException ||
        exception instanceof HttpMessageNotReadableException;
}
 
Example #17
Source File: ContentNegotiationManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
	for (ContentNegotiationStrategy strategy : this.strategies) {
		List<MediaType> mediaTypes = strategy.resolveMediaTypes(request);
		if (mediaTypes.equals(MEDIA_TYPE_ALL_LIST)) {
			continue;
		}
		return mediaTypes;
	}
	return MEDIA_TYPE_ALL_LIST;
}
 
Example #18
Source File: ContentNegotiationManagerFactoryBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotAcceptableException.class)  // SPR-10170
public void favorParameterWithUnknownMediaType() throws HttpMediaTypeNotAcceptableException {
	this.factoryBean.setFavorParameter(true);
	this.factoryBean.afterPropertiesSet();
	ContentNegotiationManager manager = this.factoryBean.getObject();

	this.servletRequest.setRequestURI("/flower");
	this.servletRequest.setParameter("format", "invalid");

	manager.resolveMediaTypes(this.webRequest);
}
 
Example #19
Source File: ContentNegotiationManagerFactoryBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotAcceptableException.class)  // SPR-10170
public void favorPathWithIgnoreUnknownPathExtensionTurnedOff() throws Exception {
	this.factoryBean.setFavorPathExtension(true);
	this.factoryBean.setIgnoreUnknownPathExtensions(false);
	this.factoryBean.afterPropertiesSet();
	ContentNegotiationManager manager = this.factoryBean.getObject();

	this.servletRequest.setRequestURI("/flower.foobarbaz");
	this.servletRequest.addParameter("format", "json");

	manager.resolveMediaTypes(this.webRequest);
}
 
Example #20
Source File: PathExtensionContentNegotiationStrategyTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotAcceptableException.class)
public void resolveMediaTypesDoNotIgnoreUnknownExtension() throws Exception {

	this.servletRequest.setRequestURI("test.foobar");

	PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy();
	strategy.setIgnoreUnknownExtensions(false);
	strategy.resolveMediaTypes(this.webRequest);
}
 
Example #21
Source File: HttpEntityMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-9142
public void shouldFailHandlingWhenAcceptHeaderIllegal() throws Exception {
	ResponseEntity<String> returnValue = new ResponseEntity<>("Body", HttpStatus.ACCEPTED);
	servletRequest.addHeader("Accept", "01");

	this.thrown.expect(HttpMediaTypeNotAcceptableException.class);
	processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
}
 
Example #22
Source File: HttpEntityMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void shouldFailHandlingWhenConverterCannotWrite() throws Exception {
	String body = "Foo";
	ResponseEntity<String> returnValue = new ResponseEntity<>(body, HttpStatus.OK);
	MediaType accepted = TEXT_PLAIN;
	servletRequest.addHeader("Accept", accepted.toString());

	given(stringHttpMessageConverter.canWrite(String.class, null)).willReturn(true);
	given(stringHttpMessageConverter.getSupportedMediaTypes())
			.willReturn(Collections.singletonList(TEXT_PLAIN));
	given(stringHttpMessageConverter.canWrite(String.class, accepted)).willReturn(false);

	this.thrown.expect(HttpMediaTypeNotAcceptableException.class);
	processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest);
}
 
Example #23
Source File: HttpEntityMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void shouldFailHandlingWhenContentTypeNotSupported() throws Exception {
	String body = "Foo";
	ResponseEntity<String> returnValue = new ResponseEntity<>(body, HttpStatus.OK);
	MediaType accepted = MediaType.APPLICATION_ATOM_XML;
	servletRequest.addHeader("Accept", accepted.toString());

	given(stringHttpMessageConverter.canWrite(String.class, null)).willReturn(true);
	given(stringHttpMessageConverter.getSupportedMediaTypes())
			.willReturn(Collections.singletonList(TEXT_PLAIN));

	this.thrown.expect(HttpMediaTypeNotAcceptableException.class);
	processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
}
 
Example #24
Source File: RequestResponseBodyMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotAcceptableException.class)
public void handleReturnValueNotAcceptableProduces() throws Exception {
	MediaType accepted = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Accept", accepted.toString());

	given(stringMessageConverter.canWrite(String.class, null)).willReturn(true);
	given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(false);

	processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest);
}
 
Example #25
Source File: RequestResponseBodyMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotAcceptableException.class)
public void handleReturnValueNotAcceptable() throws Exception {
	MediaType accepted = MediaType.APPLICATION_ATOM_XML;
	servletRequest.addHeader("Accept", accepted.toString());

	given(stringMessageConverter.canWrite(String.class, null)).willReturn(true);
	given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(MediaType.TEXT_PLAIN));
	given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(false);

	processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest);
}
 
Example #26
Source File: RequestResponseBodyMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	mavContainer.setRequestHandled(true);
	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	// Try even with null return value. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
 
Example #27
Source File: RequestResponseBodyMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	mavContainer.setRequestHandled(true);
	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	// Try even with null return value. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
 
Example #28
Source File: AbstractMessageConverterMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Writes the given return value to the given web request. Delegates to
 * {@link #writeWithMessageConverters(Object, MethodParameter, ServletServerHttpRequest, ServletServerHttpResponse)}
 */
protected <T> void writeWithMessageConverters(T value, MethodParameter returnType, NativeWebRequest webRequest)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
	writeWithMessageConverters(value, returnType, inputMessage, outputMessage);
}
 
Example #29
Source File: ContentNegotiationManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
	for (ContentNegotiationStrategy strategy : this.strategies) {
		List<MediaType> mediaTypes = strategy.resolveMediaTypes(request);
		if (mediaTypes.isEmpty() || mediaTypes.equals(MEDIA_TYPE_ALL)) {
			continue;
		}
		return mediaTypes;
	}
	return Collections.emptyList();
}
 
Example #30
Source File: ContentNegotiatingViewResolver.java    From lams with GNU General Public License v2.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;
	}
}