Search in sources :

Example 16 with Listener

use of org.bukkit.event.Listener in project VoxelGamesLibv2 by VoxelGamesLib.

the class LoggedPluginManager method registerEvents.

/**
 * Registers all the events in the given listener class.
 *
 * @param listener - listener to register
 * @param plugin   - plugin to register
 */
public void registerEvents(Listener listener, Plugin plugin) {
    if (!plugin.isEnabled()) {
        throw new IllegalPluginAccessException("Plugin attempted to register " + listener + " while not enabled");
    }
    // Just in case Bukkit decides to validate the parameters in the future
    EventExecutor nullExecutor = (arg0, arg1) -> {
        throw new IllegalStateException("This method should never be called!");
    };
    for (Entry<Class<? extends Event>, Set<RegisteredListener>> entry : plugin.getPluginLoader().createRegisteredListeners(listener, plugin).entrySet()) {
        Collection<RegisteredListener> listeners = entry.getValue();
        Collection<RegisteredListener> modified = Lists.newArrayList();
        // Use our plugin specific logger instead
        for (final RegisteredListener delegate : listeners) {
            RegisteredListener customListener = new RegisteredListener(delegate.getListener(), nullExecutor, delegate.getPriority(), delegate.getPlugin(), delegate.isIgnoringCancelled()) {

                @Override
                public void callEvent(Event event) throws EventException {
                    try {
                        delegate.callEvent(event);
                    } catch (AuthorNagException e) {
                        // Let Bukkit handle that one
                        throw e;
                    } catch (Throwable e) {
                        customHandler(event, e);
                    }
                }
            };
            modified.add(customListener);
        }
        getEventListeners(getRegistrationClass(entry.getKey())).registerAll(modified);
    }
}
Also used : HandlerList(org.bukkit.event.HandlerList) Plugin(org.bukkit.plugin.Plugin) PluginLoader(org.bukkit.plugin.PluginLoader) Event(org.bukkit.event.Event) Lists(com.google.common.collect.Lists) UnknownDependencyException(org.bukkit.plugin.UnknownDependencyException) EventExecutor(org.bukkit.plugin.EventExecutor) CommandMap(org.bukkit.command.CommandMap) InvalidDescriptionException(org.bukkit.plugin.InvalidDescriptionException) Method(java.lang.reflect.Method) Bukkit(org.bukkit.Bukkit) Listener(org.bukkit.event.Listener) EventException(org.bukkit.event.EventException) Collection(java.util.Collection) Permissible(org.bukkit.permissions.Permissible) IllegalPluginAccessException(org.bukkit.plugin.IllegalPluginAccessException) Set(java.util.Set) Field(java.lang.reflect.Field) File(java.io.File) AuthorNagException(org.bukkit.plugin.AuthorNagException) Permission(org.bukkit.permissions.Permission) RegisteredListener(org.bukkit.plugin.RegisteredListener) EventPriority(org.bukkit.event.EventPriority) Entry(java.util.Map.Entry) InvalidPluginException(org.bukkit.plugin.InvalidPluginException) PluginManager(org.bukkit.plugin.PluginManager) EventExecutor(org.bukkit.plugin.EventExecutor) Set(java.util.Set) AuthorNagException(org.bukkit.plugin.AuthorNagException) IllegalPluginAccessException(org.bukkit.plugin.IllegalPluginAccessException) Event(org.bukkit.event.Event) RegisteredListener(org.bukkit.plugin.RegisteredListener)

Example 17 with Listener

use of org.bukkit.event.Listener in project VoxelGamesLibv2 by VoxelGamesLib.

the class AbstractPhase method disable.

@Override
public void disable() {
    // disable timer
    duration = Duration.between(startTime, LocalDateTime.now());
    log.finer("disable phase " + getName());
    // only disable features that have been started to avoid errors
    for (Feature feature : startedFeatures) {
        log.finer("disable " + feature.getName());
        try {
            feature.disable();
        } catch (Exception ex) {
            log.severe("error while stopping " + feature.getName());
            ex.printStackTrace();
            return;
        }
        if (feature instanceof Listener) {
            eventHandler.unregister((Listener) feature, getGame());
        }
        if (feature instanceof FeatureCommandImplementor) {
            AbstractFeatureCommand cmd = injector.getInstance(((FeatureCommandImplementor) feature).getCommandClass());
            commandHandler.unregister(cmd, this);
        }
    }
    for (VictoryCondition victoryCondition : victoryConditions) {
        if (victoryCondition instanceof Listener) {
            eventHandler.registerEvents((Listener) victoryCondition, getGame());
        }
    }
    phaseTickables.values().forEach(tickable -> {
        tickable.disable();
        if (tickable instanceof Ability) {
            ((Ability) tickable).unregister();
        }
    });
    startedFeatures.clear();
}
Also used : Ability(com.voxelgameslib.voxelgameslib.components.ability.Ability) Listener(org.bukkit.event.Listener) FeatureCommandImplementor(com.voxelgameslib.voxelgameslib.feature.FeatureCommandImplementor) VictoryCondition(com.voxelgameslib.voxelgameslib.condition.VictoryCondition) EmptyVictoryCondition(com.voxelgameslib.voxelgameslib.condition.conditions.EmptyVictoryCondition) Feature(com.voxelgameslib.voxelgameslib.feature.Feature) VoxelGameLibException(com.voxelgameslib.voxelgameslib.exception.VoxelGameLibException) NoSuchFeatureException(com.voxelgameslib.voxelgameslib.exception.NoSuchFeatureException) DependencyGraphException(com.voxelgameslib.voxelgameslib.exception.DependencyGraphException) AbstractFeatureCommand(com.voxelgameslib.voxelgameslib.feature.AbstractFeatureCommand)

Example 18 with Listener

use of org.bukkit.event.Listener in project MagicPlugin by elBukkit.

the class Mage method onPlayerDeath.

public void onPlayerDeath(EntityDeathEvent event) {
    Player player = getPlayer();
    if (!player.hasMetadata("arena")) {
        lastDeathLocation = player.getLocation();
    }
    List<Listener> active = new ArrayList<>(deathListeners);
    for (Listener listener : active) {
        callEvent(listener, event);
    }
}
Also used : Player(org.bukkit.entity.Player) Listener(org.bukkit.event.Listener) ArrayList(java.util.ArrayList)

Example 19 with Listener

use of org.bukkit.event.Listener in project MagicPlugin by elBukkit.

the class Mage method onDamage.

public void onDamage(EntityDamageEvent event) {
    String damageType = currentDamageType;
    currentDamageType = null;
    LivingEntity entity = getLivingEntity();
    if (entity == null) {
        return;
    }
    // Send on to any registered spells
    List<Listener> active = new ArrayList<>(damageListeners);
    for (Listener listener : active) {
        callEvent(listener, event);
        if (event.isCancelled())
            break;
    }
    EntityDamageEvent.DamageCause cause = event.getCause();
    if (cause == EntityDamageEvent.DamageCause.FALL) {
        if (fallProtectionCount > 0 && fallProtection > 0 && fallProtection > System.currentTimeMillis()) {
            event.setCancelled(true);
            fallProtectionCount--;
            if (fallingSpell != null) {
                double scale = 1;
                LivingEntity li = getLivingEntity();
                if (li != null) {
                    scale = event.getDamage() / li.getMaxHealth();
                }
                fallingSpell.playEffects("land", (float) scale, getLocation().getBlock().getRelative(BlockFace.DOWN));
            }
            if (fallProtectionCount <= 0) {
                fallProtection = 0;
                fallingSpell = null;
            }
            return;
        } else {
            fallingSpell = null;
        }
    }
    if (isSuperProtected()) {
        event.setCancelled(true);
        if (entity.getFireTicks() > 0) {
            entity.setFireTicks(0);
        }
        return;
    }
    if (event.isCancelled()) {
        return;
    }
    // First check for damage reduction
    double reduction = 0;
    Double overallProtection = protection.get("overall");
    if (overallProtection != null) {
        reduction = overallProtection * controller.getMaxDamageReduction("overall");
    }
    // Apply weaknesses
    double multiplier = 1;
    Double overallWeakness = weakness.get("overall");
    if (overallWeakness != null && overallWeakness > 0) {
        double defendMultiplier = controller.getMaxDefendMultiplier("overall");
        if (defendMultiplier > 1) {
            defendMultiplier = 1 + (defendMultiplier - 1) * overallWeakness;
            multiplier *= defendMultiplier;
        }
    }
    if (cause == EntityDamageEvent.DamageCause.FIRE_TICK) {
        // Also put out fire if they have maxed out fire protection.
        double damageReductionFire = getProtection("fire");
        if (damageReductionFire >= 1 && entity.getFireTicks() > 0) {
            entity.setFireTicks(0);
        }
    }
    if (damageType == null) {
        switch(cause) {
            case CONTACT:
            case ENTITY_ATTACK:
                damageType = "physical";
                break;
            case FIRE:
            case FIRE_TICK:
            case LAVA:
                damageType = "fire";
                break;
            case BLOCK_EXPLOSION:
            case ENTITY_EXPLOSION:
                damageType = "explosion";
                break;
            default:
                damageType = cause.name().toLowerCase();
                break;
        }
    }
    lastDamageType = damageType;
    double protection = getProtection(damageType);
    double maxReduction = controller.getMaxDamageReduction(damageType);
    reduction += protection * maxReduction;
    if (reduction >= 1) {
        event.setCancelled(true);
        sendDebugMessage(ChatColor.RED + "Damage nullified by " + ChatColor.BLUE + damageType + " (" + cause + ")", 8);
        return;
    }
    double damage = event.getDamage();
    sendDebugMessage(ChatColor.RED + "Damaged by " + ChatColor.BLUE + (damageType == null ? "generic" : damageType) + " (" + cause + ")" + ChatColor.RED + " for " + ChatColor.DARK_RED + damage, 10);
    if (reduction > 0) {
        damage = (1.0 - reduction) * damage;
        sendDebugMessage(ChatColor.DARK_RED + "Damage type " + ChatColor.BLUE + damageType + " reduced by " + ChatColor.AQUA + reduction + ChatColor.DARK_RED + " to " + ChatColor.RED + damage, 9);
        event.setDamage(damage);
    }
    double weakness = getWeakness(damageType);
    double maxMultiplier = controller.getMaxDefendMultiplier(damageType);
    if (maxMultiplier > 1 && weakness > 0) {
        weakness = 1 + (maxMultiplier - 1) * weakness;
        multiplier *= weakness;
    }
    if (multiplier > 1) {
        damage = multiplier * damage;
        sendDebugMessage(ChatColor.DARK_RED + "Damage type " + ChatColor.BLUE + damageType + " multiplied by " + ChatColor.AQUA + multiplier + ChatColor.DARK_RED + " to " + ChatColor.RED + damage, 9);
        event.setDamage(damage);
    }
    if (damage > 0) {
        for (Iterator<Batch> iterator = pendingBatches.iterator(); iterator.hasNext(); ) {
            Batch batch = iterator.next();
            if (!(batch instanceof SpellBatch))
                continue;
            SpellBatch spellBatch = (SpellBatch) batch;
            Spell spell = spellBatch.getSpell();
            double cancelOnDamage = spell.cancelOnDamage();
            if (cancelOnDamage > 0 && cancelOnDamage < damage) {
                spell.cancel();
                batch.finish();
                iterator.remove();
            }
        }
    }
}
Also used : SpellBatch(com.elmakers.mine.bukkit.api.batch.SpellBatch) Listener(org.bukkit.event.Listener) ArrayList(java.util.ArrayList) MageSpell(com.elmakers.mine.bukkit.api.spell.MageSpell) ActionSpell(com.elmakers.mine.bukkit.spell.ActionSpell) Spell(com.elmakers.mine.bukkit.api.spell.Spell) BaseSpell(com.elmakers.mine.bukkit.spell.BaseSpell) LivingEntity(org.bukkit.entity.LivingEntity) Batch(com.elmakers.mine.bukkit.api.batch.Batch) UndoBatch(com.elmakers.mine.bukkit.batch.UndoBatch) SpellBatch(com.elmakers.mine.bukkit.api.batch.SpellBatch) EntityDamageEvent(org.bukkit.event.entity.EntityDamageEvent)

Example 20 with Listener

use of org.bukkit.event.Listener in project MyPet by xXKeyleXx.

the class FactionsHook method onEnable.

@SuppressWarnings("unchecked")
@Override
public boolean onEnable() {
    try {
        Class engineClass = ReflectionUtil.getClass("com.massivecraft.factions.engine.EngineMain");
        Method getMethod = engineClass.getDeclaredMethod("get");
        engine = getMethod.invoke(null);
        engineMethod = engineClass.getDeclaredMethod("canCombatDamageHappen", EntityDamageByEntityEvent.class, boolean.class);
        engineMethod.setAccessible(true);
        apiVersion = ApiVersion.V1;
        return true;
    } catch (Throwable ignored) {
    }
    try {
        Class engineClass = ReflectionUtil.getClass("com.massivecraft.factions.engine.EngineCombat");
        Method getMethod = engineClass.getDeclaredMethod("get");
        engine = getMethod.invoke(null);
        engineMethod = engineClass.getDeclaredMethod("canCombatDamageHappen", EntityDamageByEntityEvent.class, boolean.class);
        engineMethod.setAccessible(true);
        apiVersion = ApiVersion.V2;
        return true;
    } catch (Throwable ignored) {
    }
    try {
        Class engineClass = ReflectionUtil.getClass("com.massivecraft.factions.engine.EngineCanCombatHappen");
        Method getMethod = engineClass.getDeclaredMethod("get");
        engine = getMethod.invoke(null);
        engineMethod = engineClass.getDeclaredMethod("canCombatDamageHappen", EntityDamageByEntityEvent.class, boolean.class);
        engineMethod.setAccessible(true);
        apiVersion = ApiVersion.V3;
        return true;
    } catch (Throwable ignored) {
    }
    try {
        for (RegisteredListener rl : EntityDamageEvent.getHandlerList().getRegisteredListeners()) {
            Listener l = rl.getListener();
            if (l.getClass().getName().equalsIgnoreCase("com.massivecraft.factions.listeners.FactionsEntityListener")) {
                engine = l;
                engineMethod = l.getClass().getDeclaredMethod("canDamagerHurtDamagee", EntityDamageByEntityEvent.class, boolean.class);
                engineMethod.setAccessible(true);
                apiVersion = ApiVersion.Savage;
                return true;
            }
        }
    } catch (Throwable ignored) {
    }
    MyPetApi.getLogger().warning("Factions was found but no suitable MyPet hook was provided. Please report this to the MyPet developer.");
    MyPetApi.getLogger().warning("Factions version: " + MyPetApi.getPluginHookManager().getPluginInstance("Factions").get().getDescription().getVersion());
    return false;
}
Also used : RegisteredListener(org.bukkit.plugin.RegisteredListener) Listener(org.bukkit.event.Listener) EntityDamageByEntityEvent(org.bukkit.event.entity.EntityDamageByEntityEvent) Method(java.lang.reflect.Method) RegisteredListener(org.bukkit.plugin.RegisteredListener)

Aggregations

Listener (org.bukkit.event.Listener)26 EventHandler (org.bukkit.event.EventHandler)10 Event (org.bukkit.event.Event)8 EventExecutor (org.bukkit.plugin.EventExecutor)7 RegisteredListener (org.bukkit.plugin.RegisteredListener)7 Player (org.bukkit.entity.Player)6 EventException (org.bukkit.event.EventException)6 EventPriority (org.bukkit.event.EventPriority)6 PluginManager (org.bukkit.plugin.PluginManager)6 PlayerJoinEvent (org.bukkit.event.player.PlayerJoinEvent)5 Method (java.lang.reflect.Method)4 HandlerList (org.bukkit.event.HandlerList)4 Field (java.lang.reflect.Field)2 ArrayList (java.util.ArrayList)2 PlayerPortalEvent (org.bukkit.event.player.PlayerPortalEvent)2 AuthorNagException (org.bukkit.plugin.AuthorNagException)2 Plugin (org.bukkit.plugin.Plugin)2 PacketReceiveEvent (com.bergerkiller.bukkit.common.events.PacketReceiveEvent)1 PacketSendEvent (com.bergerkiller.bukkit.common.events.PacketSendEvent)1 BukkitWorldSupplier (com.bergerkiller.bukkit.common.offline.OfflineWorld.BukkitWorldSupplier)1