From 78fc5bbecc17aa743f66b329e867362647786a8e Mon Sep 17 00:00:00 2001 From: Brian Clozel Date: Thu, 29 Oct 2015 16:10:27 +0100 Subject: [PATCH] Don't throw NPE when serving webjar directories Prior to this change, serving resources with ResourceHttpRequestHandler could result in NPE when requesting an existing folder located in a JAR. This commit swallows those exceptions, as it is not possible to foresee those cases without reading the actual resource. This result in a HTTP 200 response with a zero Content-Length instead of a HTTP 500 internal exception. Issue: SPR-13620 --- .../resource/ResourceHttpRequestHandler.java | 3 +++ .../resource/ResourceHttpRequestHandlerTests.java | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java index a102d543b42..d36c6d3fad6 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java @@ -410,6 +410,9 @@ public class ResourceHttpRequestHandler extends WebContentGenerator implements H try { StreamUtils.copy(in, response.getOutputStream()); } + catch (NullPointerException ex) { + // ignore, see SPR-13620 + } finally { try { in.close(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java index a8fee143760..f42abe952b2 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java @@ -310,6 +310,20 @@ public class ResourceHttpRequestHandlerTests { assertEquals(0, this.response.getContentLength()); } + // SPR-13620 + @Test + public void writeContentInputStreamThrowingNullPointerException() throws Exception { + Resource resource = mock(Resource.class); + InputStream in = mock(InputStream.class); + given(resource.getInputStream()).willReturn(in); + given(in.read(any())).willThrow(NullPointerException.class); + + this.handler.writeContent(this.response, resource); + + assertEquals(200, this.response.getStatus()); + assertEquals(0, this.response.getContentLength()); + } + private long headerAsLong(String responseHeaderName) { return Long.valueOf(this.response.getHeader(responseHeaderName));