Affects: spring-web-5.2.3
Dear all
I could see that the treatment of subclasses of InputStreamResource is not really good in some converters or codecs for Resource instances. Exactly, I could see that there are some classes that they don't take into account that InputStreamResource could have subclasses (as my case). These examples classes are org.springframework.http.codec.ResourceHttpMessageWriter (method lengthOf(Resource) line if (InputStreamResource.class != resource.getClass()) {) or org.springframework.http.converter.ResourceHttpMessageConverter (method getContentLength and line if (InputStreamResource.class == resource.getClass()) {
I could see another opened issue about it (#20990) and in it, you talk about the possibility to override the contentLength method for all subclasses, but in my opinion, this is a workaround because the right fix should be changing the above lines for something like this: if (!(resource instanceof InputStreamResource)) {. In that way, all of subclasses of InputStreamResource will have the same treatment, because by definition, all of these subclasses are based on an opened InputStream so the treatment should be the same for all cases.
I'm open to collaborate and send you a PR to fix both cases.
I await your reply!
Comment From: poutsma
The current behavior you are seeing (i.e. not checking against subclasses with instanceof) is by design. As @jhoeller states in said issue, the alternative would be for InputStreamResource and all subclasses to fail, because of the way AbstractResource::contentLength() is implemented and because an input stream can only be read once.
@jhoeller also writes:
Unfortunately there is no sensible way to determine the content length for a plain InputStreamResource. And for custom subclasses thereof, we expect contentLength() to be overridden.
The current behavior enables users to override contentLength in subclasses; it would not work otherwise.