Fix NPE in ResourceHttpMessageConverter
ResourceHttpMessageConverter tries to use the filename to determine the media type, but for Resource implementations such as ByteArrayResource it is null, which causes NullPointerException. The fix checks whether getFilename returns null before attempting to determine the media type by it. Issue: SPR-10848
This commit is contained in:
parent
610e7796d9
commit
a17912d19e
|
@ -138,6 +138,9 @@ public class ResourceHttpMessageConverter extends AbstractHttpMessageConverter<R
|
|||
}
|
||||
|
||||
public static MediaType getMediaType(Resource resource) {
|
||||
if(resource.getFilename() == null) {
|
||||
return null;
|
||||
}
|
||||
String mediaType = fileTypeMap.getContentType(resource.getFilename());
|
||||
return (StringUtils.hasText(mediaType) ? MediaType.parseMediaType(mediaType) : null);
|
||||
}
|
||||
|
|
|
@ -17,11 +17,11 @@
|
|||
package org.springframework.http.converter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.MediaType;
|
||||
|
@ -29,6 +29,8 @@ import org.springframework.http.MockHttpInputMessage;
|
|||
import org.springframework.http.MockHttpOutputMessage;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* @author Arjen Poutsma
|
||||
*/
|
||||
|
@ -70,4 +72,15 @@ public class ResourceHttpMessageConverterTests {
|
|||
assertEquals("Invalid content-length", body.getFile().length(), outputMessage.getHeaders().getContentLength());
|
||||
}
|
||||
|
||||
// SPR-10848
|
||||
|
||||
@Test
|
||||
public void writeByteArrayNullMediaType() throws IOException {
|
||||
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
|
||||
byte[] byteArray = {1, 2, 3};
|
||||
Resource body = new ByteArrayResource(byteArray);
|
||||
converter.write(body, null, outputMessage);
|
||||
assertTrue(Arrays.equals(byteArray, outputMessage.getBodyAsBytes()));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue