Skip to content

Commit

Permalink
fix!: Use byte arrays instead of InputStream for JSON subscribers.
Browse files Browse the repository at this point in the history
  • Loading branch information
nstdio committed Mar 26, 2022
1 parent b07693b commit 6eeeda6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/main/java/io/github/nstdio/http/ext/BodySubscribers.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@

package io.github.nstdio.http.ext;

import static java.net.http.HttpResponse.BodySubscribers.ofInputStream;
import static java.net.http.HttpResponse.BodySubscribers.mapping;
import static java.net.http.HttpResponse.BodySubscribers.ofByteArray;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
Expand Down Expand Up @@ -55,9 +56,9 @@ private static <T> BodySubscriber<T> ofJson(JavaType targetType) {
}

private static <T> BodySubscriber<T> ofJson(ObjectMapper objectMapper, JavaType targetType) {
return new AsyncMappingSubscriber<>(ofInputStream(), is -> {
try (var stream = is) {
return objectMapper.readValue(stream, targetType);
return mapping(ofByteArray(), bytes -> {
try {
return objectMapper.readValue(bytes, targetType);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
Expand Down
13 changes: 13 additions & 0 deletions src/test/java/io/github/nstdio/http/ext/BodyHandlersTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
package io.github.nstdio.http.ext;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -53,5 +55,16 @@ void shouldProperlyReadJson() {
assertThat(body1).isNotEmpty();
assertThat(body2).isNotNull();
}

@Test
void shouldThrowUncheckedExceptionIfCannotRead() {
//given
var request = HttpRequest.newBuilder(URI.create("https://httpbin.org/html")).build();

//when
assertThatIOException()
.isThrownBy(() -> client.send(request, BodyHandlers.ofJson(Object.class)))
.withRootCauseExactlyInstanceOf(JsonParseException.class);
}
}
}

0 comments on commit 6eeeda6

Please sign in to comment.