I am trying to return a image with ServletContext but I get a 500 error and the console says:
java.lang.NullPointerException: null at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2146) at org.apache.commons.io.IOUtils.copy(IOUtils.java:2102) at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2123) at org.apache.commons.io.IOUtils.copy(IOUtils.java:2078) at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:721)
Configuration:
@Configuration
public class ImageConfiguration {
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
}
Service:
@Service
public class ImageService {
@Autowired
ServletContext servletContext;
public byte[] getRankImage (String id) throws IOException {
byte[] b;
InputStream in;
if (id.equals("0")) {
in = servletContext.getResourceAsStream("images/level-0.png");
return IOUtils.toByteArray(in);
restful service:
@RequestMapping(value = "/level/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage(@PathVariable("id") String id) {
byte[] imageBytes;
try {
imageBytes = imageService.getRankImage(id);
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(imageBytes);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The images are located in resources -> images -> {image_name}
when I look in the war file I confirm that they are in there. I am not sure if I am doing this wrong or I need to handle the path differently.
---------Update 1-------
I took the war file and deployed it manually in apache and this is the output: