下面列出了怎么用org.bukkit.event.Cancellable的API类实例代码及写法,或者点击链接到github查看源代码。
public static void onItemPickup(Player player, Item item, Cancellable cancel) {
if (cancel.isCancelled()) {
return;
}
if (Main.isPlayerInGame(player)) {
GamePlayer gPlayer = Main.getPlayerGameProfile(player);
Game game = gPlayer.getGame();
if (game.getStatus() == GameStatus.WAITING || gPlayer.isSpectator) {
cancel.setCancelled(true);
} else {
for (ItemSpawner spawner : game.getSpawners()) {
if (spawner.getMaxSpawnedResources() > 0) {
spawner.remove(item);
}
}
}
}
}
public void handleBlockSpread(Event event, Block fromBlock, BlockState newState) {
if (!GDFlags.BLOCK_SPREAD) {
return;
}
final World world = fromBlock.getWorld();
if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(world.getUID())) {
return;
}
final Location sourceLocation = fromBlock != null ? fromBlock.getLocation() : null;
final GDPermissionUser user = CauseContextHelper.getEventUser(sourceLocation, PlayerTracker.Type.NOTIFIER);
Location location = newState.getLocation();
GDClaim targetClaim = this.storage.getClaimAt(location);
final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, targetClaim, Flags.BLOCK_SPREAD, fromBlock, newState.getBlock().isEmpty() ? newState.getType() : newState, user, TrustTypes.BUILDER, true);
if (result == Tristate.FALSE) {
((Cancellable) event).setCancelled(true);
}
}
/**
* Query the RFA's filter with the given objects. If the query is denied, cancel the event and set
* the deny message. If the query is allowed, un-cancel the event. If the query abstains, do
* nothing.
*
* @return false if the query abstained, otherwise true
*/
protected static boolean processQuery(RegionFilterApplication rfa, Query query) {
if (rfa.filter == null) {
return false;
}
switch (rfa.filter.query(query)) {
case ALLOW:
if (query.getEvent() instanceof Cancellable) {
((Cancellable) query.getEvent()).setCancelled(false);
}
return true;
case DENY:
if (query.getEvent() instanceof GeneralizingEvent) {
((GeneralizingEvent) query.getEvent()).setCancelled(true, rfa.message);
} else if (query.getEvent() instanceof Cancellable) {
((Cancellable) query.getEvent()).setCancelled(true);
}
return true;
default:
return false;
}
}
/**
* Checks the durability of the Tool
*
* @param cancellable the Event (implements Cancelable)
* @param player the Player
* @param tool the Tool
* @return false: if broken; true: if enough durability
*/
public boolean durabilityCheck(@NotNull Cancellable cancellable, @NotNull Player player, @NotNull ItemStack tool) {
ItemMeta meta = tool.getItemMeta();
if (meta instanceof Damageable) {
if (config.getBoolean("UnbreakableTools", true)
&& tool.getType().getMaxDurability() - ((Damageable) meta).getDamage() <= 2) {
cancellable.setCancelled(true);
if (config.getBoolean("Sound.OnBreaking", true)) {
player.playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 0.5F, 0.5F);
}
return false;
}
}
return true;
}
public static void onItemPickup(Player player, Item item, Cancellable cancel) {
if (cancel.isCancelled()) {
return;
}
if (Main.isPlayerInGame(player)) {
GamePlayer gPlayer = Main.getPlayerGameProfile(player);
Game game = gPlayer.getGame();
if (game.getStatus() == GameStatus.WAITING || gPlayer.isSpectator) {
cancel.setCancelled(true);
} else {
for (ItemSpawner spawner : game.getSpawners()) {
if (spawner.getMaxSpawnedResources() > 0) {
spawner.remove(item);
}
}
}
}
}
/**
* Query the rule's filter with the given objects.
* If the query is denied, cancel the event and set the deny message.
* If the query is allowed, un-cancel the event.
* If the query abstains, do nothing.
* @return false if the query abstained, otherwise true
*/
protected static boolean processQuery(Event event, EventRule rule, IQuery query) {
if(rule.filter() == null) {
return false;
}
switch(rule.filter().query(query)) {
case ALLOW:
if(event instanceof Cancellable) {
((Cancellable) event).setCancelled(false);
}
return true;
case DENY:
if(event instanceof GeneralizingEvent) {
((GeneralizingEvent) event).setCancelled(true, rule.message());
} else if(event instanceof Cancellable) {
((Cancellable) event).setCancelled(true);
}
return true;
default:
return false;
}
}
private static void handlePlayerEvent(@Nonnull Player ply, @Nonnull Chunk chunk, @Nonnull Cancellable e, @Nonnull String config) {
if (e.isCancelled()) {
return;
}
// Check if this isn't protected within the config.
if (!ChunkEventHelper.config.getBool("protection", config)) {
return;
}
// If the user is permitted to edit here, then they bypass protections.
if (getCanEdit(chunk, ply.getUniqueId())) {
return;
}
// Cancel the event
e.setCancelled(true);
// Display cancellation message;
String username = ClaimChunk.getInstance().getPlayerHandler().getUsername(ClaimChunk.getInstance().getChunkHandler().getOwner(chunk));
// Send the not allowed to edit message
if (username != null) {
Utils.toPlayer(ply, ClaimChunk.getInstance().getMessages().chunkNoEdit.replace("%%PLAYER%%", username));
}
}
public static void handleEntityEvent(@Nonnull Player ply, @Nonnull Entity ent, @Nonnull Cancellable e) {
if (e.isCancelled()) return;
// If entities aren't protected, we don't need to check if this
// one is -_-
// If PvP is disabled, all entities (including players) are protected.
// If PvP is enabled, all entities except players are protected.
boolean protectEntities = config.getBool("protection", "protectEntities");
boolean blockPvp = ent.getType() == EntityType.PLAYER && config.getBool("protection", "blockPvp");
if (!protectEntities && !blockPvp) {
return;
}
// Admins have permission to do anything in claimed chunks.
if (Utils.hasAdmin(ply)) return;
// Check if the player is able to edit in both the chunk they're in as
// well as the chunk the animal is in.
boolean canPlayerEditEntityChunk = getCanEdit(ent.getLocation().getChunk(), ply.getUniqueId());
if (!blockPvp && canPlayerEditEntityChunk) {
return;
}
// Cancel the event
e.setCancelled(true);
}
@SuppressWarnings("null")
@Override
public boolean init(final Expression<?>[] vars, final int matchedPattern, final Kleenean isDelayed, final ParseResult parser) {
if (isDelayed == Kleenean.TRUE) {
Skript.error("Can't cancel an event anymore after it has already passed", ErrorQuality.SEMANTIC_ERROR);
return false;
}
cancel = matchedPattern == 0;
final Class<? extends Event>[] es = ScriptLoader.getCurrentEvents();
if (es == null)
return false;
for (final Class<? extends Event> e : es) {
if (Cancellable.class.isAssignableFrom(e) || BlockCanBuildEvent.class.isAssignableFrom(e))
return true; // TODO warning if some event(s) cannot be cancelled even though some can (needs a way to be suppressed)
}
if (ScriptLoader.isCurrentEvent(PlayerLoginEvent.class))
Skript.error("A connect event cannot be cancelled, but the player may be kicked ('kick player by reason of \"...\"')", ErrorQuality.SEMANTIC_ERROR);
else
Skript.error(Utils.A(ScriptLoader.getCurrentEventName()) + " event cannot be cancelled", ErrorQuality.SEMANTIC_ERROR);
return false;
}
private void handleCommand(CommandSender sender, String s, Cancellable event) {
if (s.isEmpty()) {
return;
}
if (this.plugin.getConfiguration().get(ConfigKeys.OPS_ENABLED)) {
return;
}
if (s.charAt(0) == '/') {
s = s.substring(1);
}
if (s.contains(":")) {
s = s.substring(s.indexOf(':') + 1);
}
if (s.equals("op") || s.startsWith("op ") || s.equals("deop") || s.startsWith("deop ")) {
event.setCancelled(true);
sender.sendMessage(Message.OP_DISABLED.asString(this.plugin.getLocaleManager()));
}
}
void handleInteract(final Player player, Cancellable cancellable, final int action/* 0 = interact (right-click), 1 = attack (left-click) */) {
Block targetBlock = player.getTargetBlock((Set<Material>) null, 16);
if (targetBlock != null && targetBlock.getType() != Material.AIR) {
Set<AnimatedFrame> frames = plugin.frameManager.getFramesInWorld(player.getWorld().getName());
frames.removeIf(f -> !f.isClickable());
final CursorPosition.CursorMapQueryResult queryResult = CursorPosition.findMenuByCursor(player, frames);
if (queryResult != null && queryResult.isFound()) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
queryResult.getClickable().handleClick(player, queryResult.getPosition(), action);
}
});
// cancellable.setCancelled(true);
}
}
}
private void checkLimits(Cancellable event, EntityType entityType, Location location) {
if (entityType == null) {
return; // Only happens on "other-plugins", i.e. EchoPet
}
String islandName = WorldGuardHandler.getIslandNameAt(location);
if (islandName == null) {
event.setCancelled(true); // Only allow spawning on active islands...
return;
}
if (entityType.getEntityClass().isAssignableFrom(Ghast.class) && location.getWorld().getEnvironment() != World.Environment.NETHER) {
// Disallow ghasts for now...
event.setCancelled(true);
return;
}
us.talabrek.ultimateskyblock.api.IslandInfo islandInfo = plugin.getIslandInfo(islandName);
if (islandInfo == null) {
// Disallow spawns on inactive islands
event.setCancelled(true);
return;
}
if (!plugin.getLimitLogic().canSpawn(entityType, islandInfo)) {
event.setCancelled(true);
}
}
private void cancelBowSpleefEntityEvent(Entity entity, Cancellable cancellable) {
boolean isBowspleefEntity = false;
List<MetadataValue> metadatas = entity.getMetadata(BOWSPLEEF_METADATA_KEY);
for (MetadataValue value : metadatas) {
if (value.getOwningPlugin() != getHeavySpleef().getPlugin()) {
continue;
}
isBowspleefEntity = value.asBoolean();
}
if (isBowspleefEntity) {
entity.remove();
cancellable.setCancelled(true);
}
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent unload) {
if (unload instanceof Cancellable) {
Chunk chunk = unload.getChunk();
for (String name : Main.getGameNames()) {
Game game = Main.getGame(name);
if (game.getStatus() != GameStatus.DISABLED && game.getStatus() != GameStatus.WAITING
&& GameCreator.isChunkInArea(chunk, game.getPos1(), game.getPos2())) {
((Cancellable) unload).setCancelled(false);
return;
}
}
}
}
public void handleBlockBreak(Event event, Object source, BlockState blockState) {
if (!GDFlags.BLOCK_BREAK) {
return;
}
// Ignore air blocks
if (blockState.getBlock().isEmpty()) {
return;
}
// Special case
if (source instanceof Block) {
if (NMSUtil.getInstance().isBlockScaffolding(((Block) source))) {
return;
}
}
Player player = source instanceof Player ? (Player) source : null;
final Location location = blockState.getLocation();
if (location == null) {
return;
}
final World world = blockState.getWorld();
if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(world.getUID())) {
return;
}
GDClaim targetClaim = this.storage.getClaimAt(location);
final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, targetClaim, Flags.BLOCK_BREAK, source, blockState, player, TrustTypes.BUILDER, true);
if (result == Tristate.FALSE) {
((Cancellable) event).setCancelled(true);
}
}
private void onInventoryOpen(Event event, Location location, Object target, HumanEntity player) {
GDCauseStackManager.getInstance().pushCause(player);
if (event instanceof InventoryOpenEvent) {
final InventoryOpenEvent inventoryEvent = (InventoryOpenEvent) event;
target = inventoryEvent.getView().getType();
}
if (!GDFlags.INTERACT_INVENTORY || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUID())) {
return;
}
if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.INTERACT_INVENTORY.getName(), target, player.getWorld().getUID())) {
return;
}
String targetId = GDPermissionManager.getInstance().getPermissionIdentifier(target);
GDTimings.PLAYER_INTERACT_INVENTORY_OPEN_EVENT.startTiming();
final GDClaim claim = this.dataStore.getClaimAt(location);
final GDPermissionUser user = PermissionHolderCache.getInstance().getOrCreateUser(player.getUniqueId());
if (user.getInternalPlayerData() != null && user.getInternalPlayerData().eventResultCache != null && user.getInternalPlayerData().eventResultCache.checkEventResultCache(claim, Flags.INTERACT_BLOCK_SECONDARY.getName()) == Tristate.TRUE) {
GDPermissionManager.getInstance().processResult(claim, Flags.INTERACT_INVENTORY.getPermission(), "cache", Tristate.TRUE, user);
GDTimings.PLAYER_INTERACT_INVENTORY_OPEN_EVENT.stopTiming();
return;
}
final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.INTERACT_INVENTORY, player, target, user, TrustTypes.CONTAINER, true);
if (result == Tristate.FALSE) {
final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_INVENTORY_OPEN,
ImmutableMap.of(
"player", claim.getOwnerDisplayName(),
"block", targetId));
GriefDefenderPlugin.sendClaimDenyMessage(claim, player, message);
((Cancellable) event).setCancelled(true);
}
GDTimings.PLAYER_INTERACT_INVENTORY_OPEN_EVENT.stopTiming();
}
boolean cancel(Cancellable event, @Nullable MatchPlayer actor, @Nullable Component message) {
match.getLogger().fine("Cancel " + event + " actor=" + actor);
event.setCancelled(true);
if (actor != null && message != null) {
actor.sendWarning(message);
}
return true;
}
boolean cancelUnlessInteracting(Cancellable event, Entity entity) {
if (!(entity instanceof Player)) {
return false;
}
return cancel(
event,
match.getParticipant(entity) == null,
entity.getWorld(),
match.getPlayer(entity),
null);
}
@Override
public void setCancelled(boolean cancel) {
super.setCancelled(cancel);
if (propagateCancel && getCause() instanceof Cancellable) {
((Cancellable) getCause()).setCancelled(cancel);
}
}
private void sendCancelMessage(RegionFilterApplication rfa, Query query) {
if (rfa.message != null
&& query.getEvent() instanceof Cancellable
&& ((Cancellable) query.getEvent()).isCancelled()
&& query instanceof PlayerQuery) {
MatchPlayer player = match.getPlayer(((PlayerQuery) query).getPlayerId());
if (player != null) player.sendWarning(rfa.message);
}
}
/** Query the custom damage filters with the given damage event */
public Filter.QueryResponse queryRules(
@Nullable Cancellable event, ParticipantState victim, DamageInfo damageInfo) {
Query query = getQuery(event, victim, damageInfo);
for (Filter filter : filters) {
Filter.QueryResponse response = filter.query(query);
if (response != Filter.QueryResponse.ABSTAIN) return response;
}
return Filter.QueryResponse.ABSTAIN;
}
/**
* Query whether the given damage is allowed or not. Both the custom damage filters and the
* friendly fire policy are considered, the former having priority over the latter.
*/
public Filter.QueryResponse queryDamage(
@Nullable Cancellable event, ParticipantState victim, DamageInfo damageInfo) {
Filter.QueryResponse response = queryRules(event, victim, damageInfo);
if (response != Filter.QueryResponse.ABSTAIN) return response;
return queryDefaultRules(victim, damageInfo);
}
/** Query the given damage event and cancel it if the result was denied. */
public Filter.QueryResponse processDamageEvent(
Cancellable event, ParticipantState victim, DamageInfo damageInfo) {
Filter.QueryResponse response = queryDamage(checkNotNull(event), victim, damageInfo);
if (response.isDenied()) {
event.setCancelled(true);
}
return response;
}
/**
* Call a event and check it is cancelled.
*
* @param event The event implement the Cancellable interface.
* @return The event is cancelled.
*/
public static boolean fireCancellableEvent(@NotNull Cancellable event) {
if (!(event instanceof Event)) {
throw new IllegalArgumentException("Cancellable must is event implement");
}
Bukkit.getPluginManager().callEvent((Event) event);
return event.isCancelled();
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent unload) {
if (unload instanceof Cancellable) {
Chunk chunk = unload.getChunk();
for (String name : Main.getGameNames()) {
Game game = Main.getGame(name);
if (game.getStatus() != GameStatus.DISABLED && game.getStatus() != GameStatus.WAITING
&& GameCreator.isChunkInArea(chunk, game.getPos1(), game.getPos2())) {
((Cancellable) unload).setCancelled(false);
return;
}
}
}
}
public boolean processOut(Object packet, Player p) {
org.bukkit.event.Event event = convertPacketOutboundToEvent(packet, p);
if (event == null)
return true;
Bukkit.getServer().getPluginManager().callEvent(event);
if(event instanceof Cancellable) {
return !((Cancellable) event).isCancelled();
}
return true;
}
private void sendCancelMessage(EventRule rule, IEventQuery query) {
if(rule.message() != null &&
query.getEvent() instanceof Cancellable &&
((Cancellable) query.getEvent()).isCancelled() &&
query instanceof IPlayerQuery) {
MatchPlayer player = getMatch().getPlayer(((IPlayerQuery) query).getPlayerId());
if(player != null) player.sendWarning(rule.message(), false);
}
}
boolean cancel(Cancellable event, @Nullable MatchPlayer actor, @Nullable BaseComponent message) {
logger.fine("Cancel " + event + " actor=" + actor);
event.setCancelled(true);
if(actor != null && message != null) {
actor.sendWarning(message, true);
}
return true;
}
/**
* Query the given damage event and cancel it if the result was denied.
*/
public Filter.QueryResponse processDamageEvent(Event event, ParticipantState victim, DamageInfo damageInfo) {
Filter.QueryResponse response = queryDamage(checkNotNull(event), victim, damageInfo);
if(response.isDenied() && event instanceof Cancellable) {
((Cancellable) event).setCancelled(true);
}
return response;
}
@Override
public void setCancelled(boolean cancel) {
super.setCancelled(cancel);
if(this.propagateCancel && this.cause instanceof Cancellable) {
((Cancellable) this.cause).setCancelled(cancel);
}
}