Fix default content-type for ResourceRegion HTTP responses
Prior to this commit, the `ResourceRegionHttpMessageConverter` would rely on the default implementation of `getDefaultContentType` to guess the default Content-Type of the resource region to be written to the HTTP response. That implementation fetches the first media type provided in the HTTP request "Accept" header. This behavior is not correct when converting resources and this commits aligns this converter with the `ResourceHttpMessageConverter` which uses JAF to guess the correct Content-Type of the given resource, or just returns "application/octet-stream" as a default value. Issue: SPR-15041
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -29,7 +29,9 @@ import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpInputMessage;
|
||||
import org.springframework.http.HttpOutputMessage;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.MediaTypeFactory;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.MimeTypeUtils;
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
@@ -42,6 +44,9 @@ import org.springframework.util.StreamUtils;
|
||||
*/
|
||||
public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
|
||||
|
||||
private static final boolean jafPresent = ClassUtils.isPresent(
|
||||
"javax.activation.FileTypeMap", ResourceHttpMessageConverter.class.getClassLoader());
|
||||
|
||||
public ResourceRegionHttpMessageConverter() {
|
||||
super(MediaType.ALL);
|
||||
}
|
||||
@@ -72,6 +77,23 @@ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessa
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected MediaType getDefaultContentType(Object object) {
|
||||
if (jafPresent) {
|
||||
if(object instanceof ResourceRegion) {
|
||||
return MediaTypeFactory.getMediaType(((ResourceRegion) object).getResource());
|
||||
}
|
||||
else {
|
||||
Collection<ResourceRegion> regions = (Collection<ResourceRegion>) object;
|
||||
if(regions.size() > 0) {
|
||||
return MediaTypeFactory.getMediaType(regions.iterator().next().getResource());
|
||||
}
|
||||
}
|
||||
}
|
||||
return MediaType.APPLICATION_OCTET_STREAM;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
|
||||
return canWrite(clazz, null, mediaType);
|
||||
|
||||
Reference in New Issue
Block a user