org.bukkit.event.Cancellable Java Examples

The following examples show how to use org.bukkit.event.Cancellable. 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: EffCancelEvent.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #2
Source File: FlagBowspleef.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
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);
	}
}
 
Example #3
Source File: EventRuleMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #4
Source File: CommonBlockEventHandler.java    From GriefDefender with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #5
Source File: SpawnEvents.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #6
Source File: PlayerListener.java    From BedWars with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
                }
            }
        }
    }
}
 
Example #7
Source File: ModManager.java    From MineTinker with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source File: ChunkEventHelper.java    From ClaimChunk with MIT License 6 votes vote down vote up
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));
    }
}
 
Example #9
Source File: ChunkEventHelper.java    From ClaimChunk with MIT License 6 votes vote down vote up
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);
}
 
Example #10
Source File: PlayerListener.java    From BedWars with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
                }
            }
        }
    }
}
 
Example #11
Source File: BukkitPlatformListener.java    From LuckPerms with MIT License 6 votes vote down vote up
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()));
    }
}
 
Example #12
Source File: ClickListener.java    From AnimatedFrames with MIT License 6 votes vote down vote up
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);
			}
		}

	}
 
Example #13
Source File: RegionMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example #14
Source File: TownyListener.java    From ShopChest with MIT License 5 votes vote down vote up
private boolean handleForLocation(Player player, Location loc, Cancellable e) {
    TownBlock townBlock = TownyUniverse.getTownBlock(loc);
    if (townBlock == null)
        return false;

    try {
        Town town = townBlock.getTown();
        Optional<Resident> playerResident = town.getResidents().stream()
                .filter(r -> r.getName().equals(player.getName()))
                .findFirst();
                
        if (!playerResident.isPresent()) {
            e.setCancelled(true);
            plugin.debug("Cancel Reason: Towny (no resident)");
            return true;
        }

        Resident resident = playerResident.get();
        String plotType = townBlock.getType().name();
        boolean cancel = (resident.isMayor() && !Config.townyShopPlotsMayor.contains(plotType))
                || (resident.isKing() && !Config.townyShopPlotsKing.contains(plotType))
                || (!resident.isKing() && !resident.isMayor() && !Config.townyShopPlotsResidents.contains(plotType));
        
        if (cancel) {
            e.setCancelled(true);
            plugin.debug("Cancel Reason: Towny (no permission)");
            return true;
        }
    } catch (NotRegisteredException ignored) {
    }
    return false;
}
 
Example #15
Source File: BentoBoxListener.java    From ShopChest with MIT License 5 votes vote down vote up
private boolean handleForLocation(Player player, Location loc, Cancellable e) {
    boolean allowed = checkIsland((Event) e, player, loc, BentoBoxShopFlag.SHOP_FLAG);
    if (!allowed) {
        e.setCancelled(true);
        plugin.debug("Cancel Reason: BentoBox");
        return true;
    }

    return false;
}
 
Example #16
Source File: EventCancelVerifier.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Tests a simple event handler that checks with the {@link ListenerService}
 * if the event should be canceled or not. This method tests that the event is
 * canceled when the service says so and the other way around. Do not use this
 * method if the handler method has additional behavior.
 *
 * @param listenerMethod the listener method to test
 * @param clazz the event class to test the handler method for
 * @param <T> the event type
 * @return the verifier (for chaining of methods)
 */
public <T extends Event & Cancellable> EventCancelVerifier check(Consumer<T> listenerMethod, Class<T> clazz) {
    T event = mock(clazz);
    mockShouldCancel(true, listenerService, event);
    listenerMethod.accept(event);
    verify(event).setCancelled(true);

    event = mock(clazz);
    mockShouldCancel(false, listenerService, event);
    listenerMethod.accept(event);
    verifyNoInteractions(event);

    return this;
}
 
Example #17
Source File: GriefEvents.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
private void handleWitherRampage(Cancellable e, Wither shooter, Location targetLocation) {
    String islandName = getOwningIsland(shooter);
    String targetIsland = WorldGuardHandler.getIslandNameAt(targetLocation);
    if (targetIsland == null || !targetIsland.equals(islandName)) {
        e.setCancelled(true);
        checkWitherLeash(shooter, islandName);
    }
}
 
Example #18
Source File: IslandWorldListener.java    From ShopChest with MIT License 5 votes vote down vote up
private boolean handleForLocation(Player player, Location loc, Cancellable e) {
    if (!loc.getWorld().getName().equals(IslandWorldApi.getIslandWorld().getName())) 
        return false;

    if (!IslandWorldApi.canBuildOnLocation(player, loc, true)) {
        e.setCancelled(true);
        plugin.debug("Cancel Reason: IslandWorld");
        return true;
    }

    return false;
}
 
Example #19
Source File: DWorldListener.java    From DungeonsXL with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param event    the event
 * @param entity   the entity
 * @param interact true = interact; false = break
 */
public void onTouch(Cancellable event, Entity entity, boolean interact) {
    GameWorld gameWorld = plugin.getGameWorld(entity.getWorld());
    if (gameWorld == null) {
        return;
    }
    GameRuleContainer rules = gameWorld.getDungeon().getRules();
    Set<ExMob> prot = interact ? rules.getState(GameRule.INTERACTION_PROTECTED_ENTITIES) : rules.getState(GameRule.DAMAGE_PROTECTED_ENTITIES);
    if (prot.contains(caliburn.getExMob(entity))) {
        event.setCancelled(true);
    }
}
 
Example #20
Source File: WorldGuardListener.java    From ShopChest with MIT License 5 votes vote down vote up
private boolean handleForLocation(Player player, Location loc, Cancellable e, IWrappedFlag<WrappedState> flag) {
    if (flag == null) {
        // Flag may have not been registered successfully, so ignore them.
        return false;
    }

    WrappedState state = wgWrapper.queryFlag(player, loc, flag).orElse(WrappedState.DENY);
    if (state == WrappedState.DENY) {
        e.setCancelled(true);
        plugin.debug("Cancel Reason: WorldGuard");
        return true;
    }
    return false;
}
 
Example #21
Source File: USkyBlockListener.java    From ShopChest with MIT License 5 votes vote down vote up
private boolean handleForLocation(Player player, Location loc, Cancellable e) {
    IslandInfo islandInfo = uSkyBlockAPI.getIslandInfo(loc);
    if (islandInfo == null) 
        return false;

    if (!player.getName().equals(islandInfo.getLeader()) && !islandInfo.getMembers().contains(player.getName())) {
        e.setCancelled(true);
        plugin.debug("Cancel Reason: uSkyBlock");
        return true;
    }
    return false;
}
 
Example #22
Source File: DamageMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source File: ExprEventCancelled.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Nullable
protected Boolean[] get(final Event e) {
	if (!(e instanceof Cancellable))
		return new Boolean[0];
	return new Boolean[] {((Cancellable) e).isCancelled()};
}
 
Example #24
Source File: ClickEventTracker.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes a click event from a player.
 * @param player Player who caused it.
 * @param event The event.
 * @param hand Slot associated with the event.
 * @return If the event should be passed to scripts.
 */
public boolean checkEvent(Player player, Cancellable event, EquipmentSlot hand) {
	UUID uuid = player.getUniqueId();
	TrackedEvent first = firstEvents.get(uuid);
	if (first != null && first.event != event) { // We've checked an event before, and it is not this one
		if (!modifiedEvents.contains(first.event)) {
			// Do not modify cancellation status of event, Skript did not touch it
			// This avoids issues like #2389
			return false;
		}
		
		// Ignore this, but set its cancelled status based on one set to first event
		if (event instanceof PlayerInteractEvent) { // Handle use item/block separately
			// Failing to do so caused issue SkriptLang/Skript#2303
			PlayerInteractEvent firstClick = (PlayerInteractEvent) first.event;
			PlayerInteractEvent click = (PlayerInteractEvent) event;
			click.setUseInteractedBlock(firstClick.useInteractedBlock());
			click.setUseItemInHand(firstClick.useItemInHand());
		} else {
			event.setCancelled(first.event.isCancelled());
		}
		return false;
	} else { // Remember and run this
		firstEvents.put(uuid, new TrackedEvent(event, hand));
		return true;
	}
}
 
Example #25
Source File: PacketAbstract.java    From PacketListenerAPI with MIT License 5 votes vote down vote up
public PacketAbstract(Object packet, Cancellable cancellable, ChannelWrapper channelWrapper) {
	this.channelWrapper = channelWrapper;

	this.packet = packet;
	this.cancellable = cancellable;

	fieldResolver = new FieldResolver(packet.getClass());
}
 
Example #26
Source File: PacketAbstract.java    From PacketListenerAPI with MIT License 5 votes vote down vote up
public PacketAbstract(Object packet, Cancellable cancellable, Player player) {
	this.player = player;

	this.packet = packet;
	this.cancellable = cancellable;

	fieldResolver = new FieldResolver(packet.getClass());
}
 
Example #27
Source File: ChunkEventHelper.java    From ClaimChunk with MIT License 5 votes vote down vote up
private static void handlePistonEvent(@Nonnull Block piston, @Nonnull List<Block> blocks, @Nonnull BlockFace direction, @Nonnull Cancellable e) {
    if (e.isCancelled()) return;

    // If we don't protect against pistons, no work is needed.
    if (!config.getBool("protection", "blockPistonsIntoClaims")) return;

    Chunk pistonChunk = piston.getChunk();
    List<Chunk> blockChunks = new ArrayList<>();
    blockChunks.add(piston.getRelative(direction).getChunk());

    // Add to the list of chunks possible affected by this piston
    // extension. This list should never be >2 in size but the world
    // is a weird place.
    for (Block block : blocks) {
        Chunk to = block.getRelative(direction).getChunk();

        boolean added = false;
        for (Chunk ablockChunk : blockChunks) {
            if (getChunksEqual(ablockChunk, to)) {
                added = true;
                break;
            }
        }
        if (!added) blockChunks.add(to);
    }

    // If the from and to chunks have the same owner or if the to chunk is
    // unclaimed, the piston can extend into the blockChunk.
    final ChunkHandler CHUNK = ClaimChunk.getInstance().getChunkHandler();
    boolean die = false;
    for (Chunk blockChunk : blockChunks) {
        if (!getChunksSameOwner(CHUNK, pistonChunk, blockChunk) && CHUNK.isClaimed(blockChunk)) {
            die = true;
            break;
        }
    }
    if (!die) return;

    e.setCancelled(true);
}
 
Example #28
Source File: ChunkEventHelper.java    From ClaimChunk with MIT License 5 votes vote down vote up
private static void cancelWorldEvent(@Nonnull Chunk chunk, @Nonnull Cancellable e, @SuppressWarnings("SameParameterValue") @Nonnull String config) {
    if (e.isCancelled()) return;

    // If this type of thing isn't protected against, we can skip the
    // checks.
    if (!ChunkEventHelper.config.getBool("protection", config)) return;

    final ChunkHandler CHUNK = ClaimChunk.getInstance().getChunkHandler();

    // If the chunk is claimed, prevent the spreading.
    if (CHUNK.isClaimed(chunk)) {
        e.setCancelled(true);
    }
}
 
Example #29
Source File: ListenerConsistencyTest.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
private static void checkCanceledAttribute(Class<?> listenerClass) {
    final String clazz = listenerClass.getSimpleName();
    Method[] methods = listenerClass.getDeclaredMethods();
    for (Method method : methods) {
        if (isTestableMethod(method) && method.isAnnotationPresent(EventHandler.class)) {
            if (!method.getParameterTypes()[0].isAssignableFrom(Cancellable.class)) {
                continue;
            }

            EventHandler eventHandlerAnnotation = method.getAnnotation(EventHandler.class);
            assertThat("Method " + clazz + "#" + method.getName() + " should have ignoreCancelled = true",
                eventHandlerAnnotation.ignoreCancelled(), equalTo(true));
        }
    }
}
 
Example #30
Source File: GeneralizingEvent.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void setCancelled(boolean cancel) {
    super.setCancelled(cancel);

    if(this.propagateCancel && this.cause instanceof Cancellable) {
        ((Cancellable) this.cause).setCancelled(cancel);
    }
}