Java Code Examples for java.util.concurrent.CompletableFuture#isCancelled()

The following examples show how to use java.util.concurrent.CompletableFuture#isCancelled() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GatewayRetriever.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 2
Source File: IOHelper.java    From enode with MIT License 6 votes vote down vote up
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;
    });
}
 
Example 3
Source File: GatewayRetriever.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 4
Source File: GatewayRetriever.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 5
Source File: StringUtils.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 6
Source File: StringUtils.java    From ratis with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 7
Source File: FutureGroup.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isCancelled() {
    for (final CompletableFuture<V> f : this.futures) {
        if (!f.isCancelled()) {
            return false;
        }
    }
    return true;
}
 
Example 8
Source File: RpcChannelFactory.java    From barge with Apache License 2.0 5 votes vote down vote up
@Override
public void destroyObject(Object key, CompletableFuture<NettyRpcChannel> obj) throws Exception {
  if (obj.isDone() && !obj.isCancelled()) {
    obj.get().close();
  } else {
    obj.cancel(false);
  }
}
 
Example 9
Source File: SuccessfullyCompletedCompletionStage.java    From java-hamcrest with Apache License 2.0 5 votes vote down vote up
@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;
  }
}
 
Example 10
Source File: ExceptionallyCompletedCompletionStage.java    From java-hamcrest with Apache License 2.0 5 votes vote down vote up
@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;
  }
}
 
Example 11
Source File: XMLTextDocumentService.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: SQSAsyncSender.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean doIsCanceled() {
  CompletableFuture<SendMessageResponse> maybeFuture = future;
  return maybeFuture != null && maybeFuture.isCancelled();
}
 
Example 13
Source File: Utils.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: AsyncUtils.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
public static boolean isSuccessFuture(CompletableFuture future) {
    return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled();
}
 
Example 15
Source File: RandomSearcher.java    From RandomTeleport with GNU General Public License v3.0 4 votes vote down vote up
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);
}
 
Example 16
Source File: AsyncUtils.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
public static boolean isSuccessFuture(CompletableFuture future) {
    return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled();
}
 
Example 17
Source File: Futures.java    From pravega with Apache License 2.0 2 votes vote down vote up
/**
 * 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();
}