ContentLengthFilter implements ClientRequestFilter { @Override public void filter(ClientRequestContext requestContext) { final MultivaluedMap<String, Object> headers = requestContext.getHeaders(); final String method = requestContext.getMethod(); final String uri = requestContext.getUri().toString(); if (headers == null) { LOG.debug( "Headers from request context is null for Method [{}], URI [{}]", method, uri); return; } String contentLengthHeader = null; for (String key : headers.keySet()) { if (StringUtils.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH, key)) { contentLengthHeader = key; } } if (contentLengthHeader == null) { LOG.debug("content-length not found for Method [{}], URI [{}]", method, uri); return; } Object contentLengthValue = headers.getFirst(contentLengthHeader); if (!removeZeroLengthHeader && "0".equals(contentLengthValue)) { LOG.debug("Not removing zero content-length for Mehtod [{}], URI [{}]", method, uri); return; } final Object existingContentLengthValue = headers.remove(contentLengthHeader); if (existingContentLengthValue != null) { LOG.debug( "Removed existing content-length header for Method [{}], URI [{}], Existing Value [{}]", method, uri, existingContentLengthValue); } else { LOG.debug("content-length not found for Method [{}], URI [{}]", method, uri); } } ContentLengthFilter();  ContentLengthFilter(boolean removeZeroLengthHeader); @Override void filter(ClientRequestContext requestContext);  }
@Test public void filter_withNullHeaders_shouldNotThrowException() { when(mockContext.getHeaders()).thenReturn(null); filterUnderTest.filter(mockContext); }
@Test public void filter_withNoContentLengthKey_shouldNotThrowException() { final Set<String> headersKeySetWithNoContentLength = Sets.newHashSet(); headersKeySetWithNoContentLength.add("some-header"); when(mockHeaders.keySet()).thenReturn(headersKeySetWithNoContentLength); filterUnderTest.filter(mockContext); }
@Test public void filter_withContentLengthHeader_shouldRemoveContentLength() { filterUnderTest.filter(mockContext); verify(mockHeaders).remove(eq("content-length")); }
@Test public void filter_withNoContentLengthHeaderRemoved_shouldNotThrowException() { doReturn(null).when(mockHeaders).remove(eq("content-length")); filterUnderTest.filter(mockContext); verify(mockHeaders).remove(eq("content-length")); }