Repository navigation
Expand file tree
/
Copy pathWaitAllResponsesFetchBodiesInList.java
More file actions
67 lines (51 loc) · 2.3 KB
/
Copy pathWaitAllResponsesFetchBodiesInList.java
File metadata and controls
67 lines (51 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package modern.challenge;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class WaitAllResponsesFetchBodiesInList {
public void waitAllResponses()
throws URISyntaxException, InterruptedException, ExecutionException {
List<URI> uris = Arrays.asList(
new URI("https://reqres.in/api/users/2"), // one user
new URI("https://reqres.in/api/users?page=2"), // list of users
new URI("https://reqres.in/api/unknown/2"), // list of resources
new URI("https://reqres.in/api/users/23")); // single user not foud
HttpClient client = HttpClient.newHttpClient();
List<HttpRequest> requests = uris.stream()
.map(HttpRequest::newBuilder)
.map(reqBuilder -> reqBuilder.build())
.collect(Collectors.toList());
@SuppressWarnings("unchecked")
CompletableFuture<String>[] arrayResponses = requests.stream()
.map(req -> asyncResponse(client, req))
.toArray(CompletableFuture[]::new);
CompletableFuture<Void> responses = CompletableFuture.allOf(arrayResponses);
while (!responses.isDone()) {
Thread.sleep(50);
System.out.println("Waiting for all responses ...");
}
responses.get(); // eventually, add a timeout
List<String> results = responses.thenApply(e -> {
List<String> bodies = new ArrayList<>();
for (CompletableFuture<String> body : arrayResponses) {
bodies.add(body.join());
}
return bodies;
}).get();
results.forEach(System.out::println);
}
private static CompletableFuture<String> asyncResponse(
HttpClient client, HttpRequest request) {
return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply((res) -> res.uri() + " | " + res.body() + "\n")
.exceptionally(e -> "Exception: " + e);
}
}