下面列出了java.util.concurrent.CompletableFuture#isCancelled ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns the currently retrieved gateway if there is such an object. Otherwise
* it returns an empty optional.
*
* @return Optional object to retrieve
*/
default Optional<T> getNow() {
CompletableFuture<T> leaderFuture = getFuture();
if (leaderFuture != null) {
if (leaderFuture.isCompletedExceptionally() || leaderFuture.isCancelled()) {
return Optional.empty();
} else if (leaderFuture.isDone()) {
try {
return Optional.of(leaderFuture.get());
} catch (Exception e) {
// this should never happen
throw new FlinkRuntimeException("Unexpected error while accessing the retrieved gateway.", e);
}
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
}
public void taskContinueAction(CompletableFuture<TAsyncResult> asyncResult) {
if (asyncResult.isCancelled()) {
asyncResult.exceptionally(ex -> {
logger.error("Task '{}' was cancelled, contextInfo:{}, current retryTimes: {}.",
actionName,
getContextInfo(contextInfoFunc),
currentRetryTimes, ex);
executeFailedAction(ex, String.format("Task '%s' was cancelled.", actionName));
return null;
});
return;
}
asyncResult.thenAccept(result -> {
executeSuccessAction(result);
}).exceptionally(ex -> {
processTaskException(ex);
return null;
});
}
/**
* Returns the currently retrieved gateway if there is such an object. Otherwise
* it returns an empty optional.
*
* @return Optional object to retrieve
*/
default Optional<T> getNow() {
CompletableFuture<T> leaderFuture = getFuture();
if (leaderFuture != null) {
if (leaderFuture.isCompletedExceptionally() || leaderFuture.isCancelled()) {
return Optional.empty();
} else if (leaderFuture.isDone()) {
try {
return Optional.of(leaderFuture.get());
} catch (Exception e) {
// this should never happen
throw new FlinkRuntimeException("Unexpected error while accessing the retrieved gateway.", e);
}
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
}
public static String completableFuture2String(CompletableFuture<?> future, boolean includeDetails) {
if (!future.isDone()) {
return "NOT_DONE";
} else if (future.isCancelled()) {
return "CANCELLED";
} else if (future.isCompletedExceptionally()) {
if (!includeDetails) {
return "EXCEPTION";
}
return future.thenApply(Objects::toString).exceptionally(Throwable::toString).join();
} else {
if (!includeDetails) {
return "COMPLETED";
}
return "" + future.join();
}
}
public static String completableFuture2String(CompletableFuture<?> future, boolean includeDetails) {
if (!future.isDone()) {
return "NOT_DONE";
} else if (future.isCancelled()) {
return "CANCELLED";
} else if (future.isCompletedExceptionally()) {
if (!includeDetails) {
return "EXCEPTION";
}
return future.thenApply(Objects::toString).exceptionally(Throwable::toString).join();
} else {
if (!includeDetails) {
return "COMPLETED";
}
return "" + future.join();
}
}
/**
* Returns the currently retrieved gateway if there is such an object. Otherwise
* it returns an empty optional.
*
* @return Optional object to retrieve
*/
default Optional<T> getNow() {
CompletableFuture<T> leaderFuture = getFuture();
if (leaderFuture != null) {
if (leaderFuture.isCompletedExceptionally() || leaderFuture.isCancelled()) {
return Optional.empty();
} else if (leaderFuture.isDone()) {
try {
return Optional.of(leaderFuture.get());
} catch (Exception e) {
// this should never happen
throw new FlinkRuntimeException("Unexpected error while accessing the retrieved gateway.", e);
}
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
}
@Override
public boolean isCancelled() {
for (final CompletableFuture<V> f : this.futures) {
if (!f.isCancelled()) {
return false;
}
}
return true;
}
private static <R, M> CompletableFuture<R> computeModelAsync(CompletableFuture<M> loadModel,
BiFunction<CancelChecker, M, R> code) {
CompletableFuture<CancelChecker> start = new CompletableFuture<>();
CompletableFuture<R> result = start.thenCombineAsync(loadModel, code);
CancelChecker cancelIndicator = () -> {
if (result.isCancelled())
throw new CancellationException();
};
start.complete(cancelIndicator);
return result;
}
@Override
protected boolean matchesSafely(final CompletionStage<?> stage,
final Description mismatchDescription) {
final CompletableFuture<?> future = stage.toCompletableFuture();
if (future.isDone()) {
if (future.isCancelled()) {
mismatchDescription.appendText("a stage that was cancelled");
return false;
} else if (future.isCompletedExceptionally()) {
try {
future.getNow(null);
throw new AssertionError(
"This should never happen because the stage completed exceptionally.");
} catch (CompletionException e) {
if (matcher.matches(e.getCause())) {
return true;
} else {
mismatchDescription.appendText("a stage completed exceptionally with ");
matcher.describeMismatch(e.getCause(), mismatchDescription);
return false;
}
}
} else {
mismatchDescription
.appendText("a stage that completed to a value that was ")
.appendValue(future.getNow(null));
return false;
}
} else {
mismatchDescription.appendText("a stage that was not completed");
return false;
}
}
@Override
protected boolean matchesSafely(final CompletionStage<? extends T> stage,
final Description mismatchDescription) {
final CompletableFuture<? extends T> future = stage.toCompletableFuture();
if (future.isDone()) {
if (future.isCancelled()) {
mismatchDescription.appendText("a stage that was cancelled");
return false;
} else if (future.isCompletedExceptionally()) {
try {
future.getNow(null);
throw new AssertionError(
"This should never happen because the future has completed exceptionally.");
} catch (CompletionException e) {
mismatchDescription
.appendText("a stage that completed exceptionally with ")
.appendText(getStackTraceAsString(e.getCause()));
}
return false;
} else {
final T item = future.getNow(null);
if (matcher.matches(item)) {
return true;
} else {
mismatchDescription.appendText("a stage that completed to a value that ");
matcher.describeMismatch(item, mismatchDescription);
return false;
}
}
} else {
mismatchDescription.appendText("a stage that was not done");
return false;
}
}
@Override
public void destroyObject(Object key, CompletableFuture<NettyRpcChannel> obj) throws Exception {
if (obj.isDone() && !obj.isCancelled()) {
obj.get().close();
} else {
obj.cancel(false);
}
}
public static boolean isSuccessFuture(CompletableFuture future) {
return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled();
}
public static boolean isSuccessFuture(CompletableFuture future) {
return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled();
}
/**
* Sends a plugin message.
*
* Example usage using the "GetServers" bungee plugin message channel via an overload:
* <code>
* Utils.sendPluginMessage("BungeeCord", r -> "GetServers".equals(r.readUTF()), "GetServers")
* .thenAccept(response -> Bukkit.broadcastMessage(response.readUTF()) // comma delimited server broadcast
* .exceptionally(ex -> {
* Skript.warning("Failed to get servers because there are no players online");
* return null;
* });
* </code>
*
* @param player the player to send the plugin message through
* @param channel the channel for this plugin message
* @param messageVerifier verifies that a plugin message is the response to the sent message
* @param data the data to add to the outgoing message
* @return a completable future for the message of the responding plugin message, if there is one.
* this completable future will complete exceptionally if the player is null.
*/
public static CompletableFuture<ByteArrayDataInput> sendPluginMessage(Player player, String channel,
Predicate<ByteArrayDataInput> messageVerifier, String... data) {
CompletableFuture<ByteArrayDataInput> completableFuture = new CompletableFuture<>();
if (player == null) {
completableFuture.completeExceptionally(new IllegalStateException("Can't send plugin messages from a null player"));
return completableFuture;
}
Skript skript = Skript.getInstance();
Messenger messenger = Bukkit.getMessenger();
messenger.registerOutgoingPluginChannel(skript, channel);
PluginMessageListener listener = (sendingChannel, sendingPlayer, message) -> {
ByteArrayDataInput input = ByteStreams.newDataInput(message);
if (channel.equals(sendingChannel) && sendingPlayer == player && !completableFuture.isDone()
&& !completableFuture.isCancelled() && messageVerifier.test(input)) {
completableFuture.complete(input);
}
};
messenger.registerIncomingPluginChannel(skript, channel, listener);
completableFuture.whenComplete((r, ex) -> messenger.unregisterIncomingPluginChannel(skript, channel, listener));
// if we haven't gotten a response after a minute, let's just assume there wil never be one
Bukkit.getScheduler().scheduleSyncDelayedTask(skript, () -> {
if (!completableFuture.isDone())
completableFuture.cancel(true);
}, 60 * 20);
ByteArrayDataOutput out = ByteStreams.newDataOutput();
Stream.of(data).forEach(out::writeUTF);
player.sendPluginMessage(Skript.getInstance(), channel, out.toByteArray());
return completableFuture;
}
@Override
protected boolean doIsCanceled() {
CompletableFuture<SendMessageResponse> maybeFuture = future;
return maybeFuture != null && maybeFuture.isCancelled();
}
private void checkRandom(CompletableFuture<Location> future) {
if (checks >= maxTries) {
future.completeExceptionally(new NotFoundException("location"));
return;
}
if (future.isCancelled() || future.isDone() || future.isCompletedExceptionally()) {
return;
}
lastCheck = center.getWorld().getTime();
Location randomLoc = center.clone();
randomLoc.setY(0);
int minChunk = minRadius >> 4;
int maxChunk = maxRadius >> 4;
int randChunkX;
int randChunkZ;
Chunk[] loadedChunks = new Chunk[0];
if (loadedOnly) {
loadedChunks = randomLoc.getWorld().getLoadedChunks();
if (loadedChunks.length == 0) {
future.completeExceptionally(new NotFoundException("loaded chunk"));
return;
}
}
do {
checks++;
if (checks >= maxTries) {
future.completeExceptionally(new NotFoundException("location"));
return;
}
if (loadedOnly) {
Chunk chunk = loadedChunks[random.nextInt(loadedChunks.length)];
randChunkX = chunk.getX();
randChunkZ = chunk.getZ();
} else {
randChunkX = (random.nextBoolean() ? 1 : -1) * random.nextInt(maxChunk + 1);
randChunkZ = (random.nextBoolean() ? 1 : -1) * random.nextInt(maxChunk + 1);
}
} while (!checked.put(randChunkX, randChunkZ) || !inRadius(Math.abs(randChunkX), Math.abs(randChunkZ), minChunk, maxChunk));
randomLoc.setX(((center.getBlockX() >> 4) + randChunkX) * 16);
randomLoc.setZ(((center.getBlockZ() >> 4) + randChunkZ) * 16);
PaperLib.getChunkAtAsync(randomLoc, generatedOnly).thenApply(c -> {
checks++;
if (c == null) {
// Chunk not generated, test another one
checkRandom(future);
return false;
}
int indexOffset = random.nextInt(RANDOM_LIST.size());
Location foundLoc = null;
for (int i = 0; i < RANDOM_LIST.size(); i++) {
int index = (i + indexOffset) % RANDOM_LIST.size();
boolean validated = true;
Location loc = randomLoc.clone().add(RANDOM_LIST.get(index)[0], 0, RANDOM_LIST.get(index)[1]);
if (!inRadius(loc)) {
continue;
}
for (LocationValidator validator : getValidators().getAll()) {
if (!validator.validate(this, loc)) {
validated = false;
break;
}
}
if (validated) {
foundLoc = loc;
break;
}
}
if (foundLoc != null) {
// all checks are for the top block, put we want a location above that so add 1 to y
future.complete(foundLoc.add(0, 1, 0));
return true;
}
long diff = center.getWorld().getTime() - lastCheck;
if (diff < checkDelay) {
plugin.getServer().getScheduler().runTaskLater(plugin, () -> checkRandom(future), checkDelay - diff);
} else {
checkRandom(future);
}
return false;
}).exceptionally(future::completeExceptionally);
}
/**
* Returns true if the future is done and successful.
*
* @param f The future to inspect.
* @param <T> The Type of the future's result.
* @return True if the given CompletableFuture has completed successfully.
*/
public static <T> boolean isSuccessful(CompletableFuture<T> f) {
return f.isDone() && !f.isCompletedExceptionally() && !f.isCancelled();
}