I found what I believe could be a bug in the Spring classes HttpHeaders and ReadOnlyHttpHeaders. I want to confirm this before raising a Jira defect with Spring. Here is a snippet of the code I use to create an empty HttpHeaders object:
HttpHeaders myHeaders = HttpHeaders.writableHttpHeaders(HttpHeaders.EMPTY);
I then add headers to my new object using:
myHeaders.add(HttpHeaders.ACCEPT_ENCODING, "gzip")
After this HttpHeaders.EMPTY is not empty anymore
HttpHeaders.EMPTY.size() == 1
The javadoc for HttpHeaders.EMPTY states:
/**
* The empty {@code HttpHeaders} instance (immutable).
*/
public static final HttpHeaders EMPTY
The problem here is that when 'HttpHeaders.EMPTY' is used elsewhere, it introduces unexpected headers.
Consider the following unit test:
@Test
public void testUpdateEmptyHeaders() {
assertEquals(0, HttpHeaders.EMPTY.size()); // **Success**
HttpHeaders myHeaders = HttpHeaders.writableHttpHeaders(HttpHeaders.EMPTY);
myHeaders.add(HttpHeaders.ACCEPT_ENCODING, "gzip");
assertEquals(0, HttpHeaders.EMPTY.size()); // **Assert Fails**
}
@Test
// This test will fail if run after the test above, but will be successful if run by itself
public void testEmptyHeaders() {
assertEquals(0, HttpHeaders.EMPTY.size());
}
Here is the result of the unit tests:
// testUpdateEmptyHeaders
08:39:28.450 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@2e222612, testMethod = testUpdateEmptyHeaders@AuditContextTest, testException = java.lang.AssertionError: expected:<0> but was:<1>
java.lang.AssertionError:
Expected :0
Actual :1
// testEmptyHeaders
08:39:28.482 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@2e222612, testMethod = testEmptyHeaders@AuditContextTest, testException = java.lang.AssertionError: expected:<0> but was:<1>
java.lang.AssertionError:
Expected :0
Actual :1
I feel that this is a bug since HttpHeaders.EMPTY should be immutable.
I have also been able to fix this by making two changes in Spring HttpHeaders.java and ReadOnlyHttpHeaders.java