EmptyContainerDecoder implements Decoder { @Override public Object decode(Response response, Type type) throws IOException { Object delegateResult = delegate.decode(response, type); if (response.status() == 204 || (response.status() == 200 && delegateResult == null)) { @Nullable Object object = blankInstanceCache.get(type); return Preconditions.checkNotNull( object, "Received HTTP 204 but unable to construct an empty instance for return type", SafeArg.of("type", type)); } else { return delegateResult; } } EmptyContainerDecoder(ObjectMapper mapper, Decoder delegate); @Override Object decode(Response response, Type type);  }
@Test public void http_200_uses_delegate_decoder() throws IOException { when(delegate.decode(any(), eq(String.class))).thenReturn("text response"); Response http200 = Response.create( 200, "OK", ImmutableMap.of(HttpHeaders.CONTENT_TYPE, ImmutableSet.of(MediaType.TEXT_PLAIN)), "text response", StandardCharsets.UTF_8); emptyContainerDecoder.decode(http200, String.class); verify(delegate, times(1)).decode(any(), any()); }
@Test public void http_204_turns_empty_body_into_alias_of_OptionalEmpty() throws IOException { assertThat(emptyContainerDecoder.decode(HTTP_204, Alias1.class)).isEqualTo(Alias1.of(Optional.empty())); }
@Test public void http_204_turns_empty_body_into_alias_of_OptionalInt() throws IOException { assertThat(emptyContainerDecoder.decode(HTTP_204, Alias2.class)).isEqualTo(Alias2.of(OptionalInt.empty())); }
@Test public void http_204_turns_empty_body_into_alias_of_OptionalDouble() throws IOException { assertThat(emptyContainerDecoder.decode(HTTP_204, Alias3.class)).isEqualTo(Alias3.of(OptionalDouble.empty())); }
@Test public void http_204_can_handle_alias_of_alias_of_optional_string() throws IOException { assertThat(emptyContainerDecoder.decode(HTTP_204, AliasAlias1.class)) .isEqualTo(AliasAlias1.of(Alias1.of(Optional.empty()))); }
@Test public void http_204_reuses_the_same_instance_each_time() throws IOException { Object first = emptyContainerDecoder.decode(HTTP_204, Alias1.class); Object second = emptyContainerDecoder.decode(HTTP_204, Alias1.class); assertThat(first).isSameAs(second); }