Skip to content

Commit

Permalink
Handling stream closing for OkHttp
Browse files Browse the repository at this point in the history
  • Loading branch information
sashirestela committed Jan 16, 2025
1 parent 223233a commit 9854f23
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ protected Object sendAsync(RequestData request) {

@Override
public void shutdown() {
this.httpClient.executor().ifPresent(executor -> {
httpClient.executor().ifPresent(executor -> {
if (executor instanceof ExecutorService) {
((ExecutorService) executor).shutdown();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Spliterator;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class OkHttpClientAdapter extends HttpClientAdapter {

Expand Down Expand Up @@ -187,13 +190,45 @@ private Object getResponseContent(ResponseBody responseBody, ReturnType returnTy
try {
if (returnType.isStream()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody.byteStream()));
return reader.lines().onClose(() -> {
try {
responseBody.close();
} catch (Exception e) {
throw new CleverClientException(e);
return StreamSupport.stream(new Spliterator<String>() {

private final Iterator<String> iterator = reader.lines().iterator();
private boolean closed = false;

@Override
public boolean tryAdvance(java.util.function.Consumer<? super String> action) {
if (iterator.hasNext()) {
action.accept(iterator.next());
return true;
}
if (!closed) {
try {
reader.close();
responseBody.close();
closed = true;
} catch (Exception e) {
throw new CleverClientException(e);
}
}
return false;
}

@Override
public Spliterator<String> trySplit() {
return null;
}
});

@Override
public long estimateSize() {
return Long.MAX_VALUE;
}

@Override
public int characteristics() {
return Spliterator.ORDERED;
}

}, false);
} else if (returnType.isInputStream()) {
return responseBody.byteStream();
} else {
Expand Down

0 comments on commit 9854f23

Please sign in to comment.