All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.dataloader.impl.CompletableFutureKit Maven / Gradle / Ivy

There is a newer version: 2022-09-12T23-25-35-08559ba
Show newest version
package org.dataloader.impl;

import org.dataloader.annotations.Internal;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static java.util.stream.Collectors.toList;

/**
 * Some really basic helpers when working with CompletableFutures
 */
@Internal
public class CompletableFutureKit {

    public static  CompletableFuture failedFuture(Exception e) {
        CompletableFuture future = new CompletableFuture<>();
        future.completeExceptionally(e);
        return future;
    }

    public static  Throwable cause(CompletableFuture completableFuture) {
        if (!completableFuture.isCompletedExceptionally()) {
            return null;
        }
        try {
            completableFuture.get();
            return null;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return e;
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause != null) {
                return cause;
            }
            return e;
        }
    }

    public static  boolean succeeded(CompletableFuture future) {
        return future.isDone() && !future.isCompletedExceptionally();
    }

    public static  boolean failed(CompletableFuture future) {
        return future.isDone() && future.isCompletedExceptionally();
    }

    public static  CompletableFuture> allOf(List> cfs) {
        return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0]))
                .thenApply(v -> cfs.stream()
                        .map(CompletableFuture::join)
                        .collect(toList())
                );
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy