Avoid infinite loop in AbstractResource#contentLength

Due to changes made in commit 2fa87a71 for SPR-9118,
AbstractResource#contentLength would fall into an infinite loop unless
the method were overridden by a subclass (which it is in the majority of
use cases).

This commit:

 - fixes the infinite recursion by refactoring to a while loop

 - asserts that the value returned from #getInputStream is not null in
   order to avoid NullPointerException

 - tests both of the above

 - adds Javadoc to the Resource interface to clearly document that the
   contract for any implementation is that #getInputStream must not
   return null

Issue: SPR-9161
This commit is contained in:
Chris Beams
2012-02-24 14:29:28 +01:00
parent f4010f14d1
commit 7ca5fba05f
3 changed files with 44 additions and 9 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2012 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.
@@ -16,9 +16,6 @@
package org.springframework.core.io;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -30,8 +27,12 @@ import org.junit.Ignore;
import org.junit.Test;
import org.springframework.util.FileCopyUtils;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 09.09.2004
*/
public class ResourceTests {
@@ -174,13 +175,11 @@ public class ResourceTests {
assertEquals(new UrlResource("file:dir/subdir"), relative);
}
/*
* @Test
@Ignore @Test // this test is quite slow. TODO: re-enable with JUnit categories
public void testNonFileResourceExists() throws Exception {
Resource resource = new UrlResource("http://www.springframework.org");
assertTrue(resource.exists());
}
*/
@Test
public void testAbstractResourceExceptions() throws Exception {
@@ -220,4 +219,30 @@ public class ResourceTests {
assertThat(resource.getFilename(), nullValue());
}
@Test
public void testContentLength() throws IOException {
AbstractResource resource = new AbstractResource() {
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(new byte[] { 'a', 'b', 'c' });
}
public String getDescription() {
return null;
}
};
assertThat(resource.contentLength(), is(3L));
}
@Test(expected=IllegalStateException.class)
public void testContentLength_withNullInputStream() throws IOException {
AbstractResource resource = new AbstractResource() {
public InputStream getInputStream() throws IOException {
return null;
}
public String getDescription() {
return null;
}
};
resource.contentLength();
}
}