Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add additional helper methods to wrap CompletableFutures.successfulAsList #93

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,24 @@ List<CompletableFuture<String>> input = asList(
CompletableFuture<List<String>> joined = CompletableFutures.successfulAsList(input, t -> "default");
```

There are also variants that accept a stream:
```java
Stream<CompletableFuture<String>> input = asList(
completedFuture("a"),
exceptionallyCompletedFuture(new RuntimeException("boom"))).stream();
CompletableFuture<List<String>> joined = CompletableFutures.successfulAsList(input, t -> "default");
```

and a map to allow passing other information about each future into the default object:
```java
Map<Integer, CompletableFuture<String>> input = asMap(
asList(1, 2),
asList(
completedFuture("a"),
exceptionallyCompletedFuture(new RuntimeException("boom"))));
CompletableFuture<List<String>> joined = CompletableFutures.successfulAsList(input, (num, t) -> num + " default");
```

#### joinList

`joinList` is a stream collector that combines multiple futures into a list. This is handy if you
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/spotify/futures/CompletableFutures.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Stream;

/**
* A collection of static utility methods that extend the
Expand Down Expand Up @@ -139,6 +140,34 @@ public static <U, T> CompletableFuture<Map<U, T>> allAsMap(
});
}

/**
* Returns a new {@link CompletableFuture} which completes to a list of values of those input
* stages that succeeded. The list of results is in the same order as the input stages. For failed
* stages, the defaultValueMapper will be called, and the value returned from that function will
* be put in the resulting list.
*
* <p>If no stages are provided in the map, returns a future holding an empty list.
*
* @param stagesMap the stages to combine.
* @param defaultValueMapper a function that will be called when a future completes exceptionally
* to provide a default value to place in the resulting list
* @param <S> the key or reference to each completion stage, used to map on exceptions
* @param <T> the common type of all the input stages, that determines the type of the output
* future
* @return a future that completes to a list of the results of the supplied stages
* @throws NullPointerException if the stages map or any of its values are {@code null}
*/
public static <S, T> CompletableFuture<List<T>> successfulAsList(
Map<S, ? extends CompletionStage<T>> stagesMap,
BiFunction<S, Throwable, ? extends T> defaultValueMapper) {
return stagesMap.entrySet().stream()
.map(
f ->
f.getValue()
.exceptionally(throwable -> defaultValueMapper.apply(f.getKey(), throwable)))
.collect(joinList());
}

/**
* Returns a new {@link CompletableFuture} which completes to a list of values of those input
* stages that succeeded. The list of results is in the same order as the input stages. For failed
Expand All @@ -155,6 +184,13 @@ public static <U, T> CompletableFuture<Map<U, T>> allAsMap(
* @return a future that completes to a list of the results of the supplied stages
* @throws NullPointerException if the stages list or any of its elements are {@code null}
*/
public static <T> CompletableFuture<List<T>> successfulAsList(
Stream<? extends CompletionStage<T>> stages,
Function<Throwable, ? extends T> defaultValueMapper) {
return stages.map(f -> f.exceptionally(defaultValueMapper)).collect(joinList());
}

/** Helper method to allow input of a list instead of a stream. */
public static <T> CompletableFuture<List<T>> successfulAsList(
List<? extends CompletionStage<T>> stages,
Function<Throwable, ? extends T> defaultValueMapper) {
Expand Down
56 changes: 56 additions & 0 deletions src/test/java/com/spotify/futures/CompletableFuturesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.hamcrest.CustomTypeSafeMatcher;
Expand Down Expand Up @@ -223,6 +224,61 @@ public void successfulAsList_exceptionalAndNull() {
assertThat(successfulAsList(input, t -> "default"), completesTo(expected));
}

@Test
public void successfulAsListFromMap_whenMixOfFailureAndSuccess() {
Map<String, CompletionStage<Boolean>> map = new HashMap<>();
map.put("hello2", completedFuture(true));
map.put("hello", exceptionallyCompletedFuture(new RuntimeException("I failed")));
BiFunction<String, Throwable, Boolean> resultsMapper = (s, t) -> s.length() < 3;

final List<Boolean> expected = asList(true, false);
final CompletableFuture<List<Boolean>> actual = successfulAsList(map, resultsMapper);
assertThat(actual, completesTo(expected));
}

@Test
public void successfulAsListFromMap_throwWhenMapIsNull() {
Map<String, CompletionStage<Boolean>> map = null;
BiFunction<String, Throwable, Boolean> resultsMapper = (s, t) -> true;

assertThrows(NullPointerException.class, () -> successfulAsList(map, resultsMapper));
}

@Test
public void successfulAsListFromMap_throwWhenOneValueIsNull() {
Map<String, CompletionStage<Boolean>> map =
asMap(asList("hello", "hello"), asList(completedFuture(true), null));
BiFunction<String, Throwable, Boolean> resultsMapper = (s, t) -> s.length() < 3;

assertThrows(NullPointerException.class, () -> successfulAsList(map, resultsMapper));
}

@Test
public void successfulAsListFromMap_exceptionalAndNull() {
Map<String, CompletionStage<String>> map =
asMap(
asList("1", "2", "3", "4"),
asList(
completedFuture("a"),
exceptionallyCompletedFuture(new RuntimeException("boom")),
completedFuture(null),
completedFuture("d")));
final List<String> expected = asList("a", "2 default", null, "d");
assertThat(successfulAsList(map, (s, t) -> s + " default"), completesTo(expected));
}

@Test
public void successfulAsListFromStream_exceptionalAndNull() {
final List<CompletableFuture<String>> input =
asList(
completedFuture("a"),
exceptionallyCompletedFuture(new RuntimeException("boom")),
completedFuture(null),
completedFuture("d"));
final List<String> expected = asList("a", "default", null, "d");
assertThat(successfulAsList(input.stream(), t -> "default"), completesTo(expected));
}

@Test
public void getCompleted_done() {
final CompletionStage<String> future = completedFuture("hello");
Expand Down