Search in sources :

Example 11 with Event

use of org.bukkit.event.Event in project CommandHelper by EngineHub.

the class CommandHelperPlugin method registerEventsDynamic.

/*
	 * This method is based on Bukkit's JavaPluginLoader:createRegisteredListeners
	 * Part of this code would be run normally using the other register method
	 */
public void registerEventsDynamic(Listener listener) {
    for (final java.lang.reflect.Method method : listener.getClass().getMethods()) {
        EventIdentifier identifier = method.getAnnotation(EventIdentifier.class);
        EventHandler defaultHandler = method.getAnnotation(EventHandler.class);
        EventPriority priority = EventPriority.LOWEST;
        Class<? extends Event> eventClass;
        if (defaultHandler != null) {
            priority = defaultHandler.priority();
        }
        if (identifier == null) {
            if (defaultHandler != null && method.getParameterTypes().length == 1) {
                try {
                    eventClass = (Class<? extends Event>) method.getParameterTypes()[0];
                } catch (ClassCastException e) {
                    continue;
                }
            } else {
                continue;
            }
        } else {
            if (!identifier.event().existsInCurrent()) {
                continue;
            }
            try {
                eventClass = (Class<? extends Event>) Class.forName(identifier.className());
            } catch (ClassNotFoundException | ClassCastException e) {
                CHLog.GetLogger().e(CHLog.Tags.RUNTIME, "Could not listen for " + identifier.event().name() + " because the class " + identifier.className() + " could not be found." + " This problem is not expected to occur, so please report it on the bug" + " tracker if it does.", Target.UNKNOWN);
                continue;
            }
        }
        HandlerList handler;
        try {
            handler = (HandlerList) ReflectionUtils.invokeMethod(eventClass, null, "getHandlerList");
        } catch (ReflectionUtils.ReflectionException ref) {
            Class eventSuperClass = eventClass.getSuperclass();
            if (eventSuperClass != null) {
                try {
                    handler = (HandlerList) ReflectionUtils.invokeMethod(eventSuperClass, null, "getHandlerList");
                } catch (ReflectionUtils.ReflectionException refInner) {
                    CHLog.GetLogger().e(CHLog.Tags.RUNTIME, "Could not listen for " + identifier.event().name() + " because the handler for class " + identifier.className() + " could not be found. An attempt has already been made to find the" + " correct handler, but" + eventSuperClass.getName() + " did not have it either. Please report this on the bug tracker.", Target.UNKNOWN);
                    continue;
                }
            } else {
                CHLog.GetLogger().e(CHLog.Tags.RUNTIME, "Could not listen for " + identifier.event().name() + " because the handler for class " + identifier.className() + " could not be found. An attempt has already been made to find the" + " correct handler, but no superclass could be found." + " Please report this on the bug tracker.", Target.UNKNOWN);
                continue;
            }
        }
        final Class<? extends Event> finalEventClass = eventClass;
        EventExecutor executor = new EventExecutor() {

            @Override
            public void execute(Listener listener, Event event) throws EventException {
                try {
                    if (!finalEventClass.isAssignableFrom(event.getClass())) {
                        return;
                    }
                    method.invoke(listener, event);
                } catch (InvocationTargetException ex) {
                    throw new EventException(ex.getCause());
                } catch (Throwable t) {
                    throw new EventException(t);
                }
            }
        };
        if (this.getServer().getPluginManager().useTimings()) {
            handler.register(new TimedRegisteredListener(listener, executor, priority, this, false));
        } else {
            handler.register(new RegisteredListener(listener, executor, priority, this, false));
        }
    }
}
Also used : HandlerList(org.bukkit.event.HandlerList) EventIdentifier(com.laytonsmith.annotations.EventIdentifier) TimedRegisteredListener(org.bukkit.plugin.TimedRegisteredListener) Listener(org.bukkit.event.Listener) RegisteredListener(org.bukkit.plugin.RegisteredListener) EventException(org.bukkit.event.EventException) EventHandler(org.bukkit.event.EventHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException) EventExecutor(org.bukkit.plugin.EventExecutor) Event(org.bukkit.event.Event) ServerCommandEvent(org.bukkit.event.server.ServerCommandEvent) PlayerCommandPreprocessEvent(org.bukkit.event.player.PlayerCommandPreprocessEvent) ReflectionUtils(com.laytonsmith.PureUtilities.Common.ReflectionUtils) TimedRegisteredListener(org.bukkit.plugin.TimedRegisteredListener) TimedRegisteredListener(org.bukkit.plugin.TimedRegisteredListener) RegisteredListener(org.bukkit.plugin.RegisteredListener) EventPriority(org.bukkit.event.EventPriority)

Example 12 with Event

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

the class ErrorHandler method injectErrorHandlers.

private void injectErrorHandlers() {
    // plugin manager
    try {
        Field pluginManagerField = Bukkit.getServer().getClass().getDeclaredField("pluginManager");
        pluginManagerField.setAccessible(true);
        if (Modifier.isFinal(pluginManagerField.getModifiers())) {
            Field modifierField = Field.class.getDeclaredField("modifiers");
            modifierField.setAccessible(true);
            modifierField.set(pluginManagerField, pluginManagerField.getModifiers() & ~Modifier.FINAL);
        }
        pluginManagerField.set(Bukkit.getServer(), new LoggedPluginManager(voxelGamesLib) {

            private Object timings;

            private final Map<String, Permission> permissions = new HashMap<>();

            private final Map<Boolean, Set<Permission>> defaultPerms = new LinkedHashMap<>();

            private final Map<String, Map<Permissible, Boolean>> permSubs = new HashMap<>();

            private final Map<Boolean, Map<Permissible, Boolean>> defSubs = new HashMap<>();

            private final CommandMap commandMap;

            {
                Field commandMapField = Bukkit.getServer().getClass().getDeclaredField("commandMap");
                commandMapField.setAccessible(true);
                commandMap = (CommandMap) commandMapField.get(Bukkit.getServer());
            }

            @Override
            protected void customHandler(@Nonnull Throwable e) {
                if (enableBugsnag) {
                    bugsnag.notify(e.getCause(), Severity.ERROR);
                }
                log.info("Caught exception");
                // let bukkit handle it
                ACFUtil.sneaky(e);
            }

            @Override
            protected void customHandler(@Nonnull Event event, @Nonnull Throwable e) {
                if (enableBugsnag) {
                    bugsnag.notify(e.getCause(), Severity.ERROR, (report -> {
                        report.addToTab(EVENT_INFO_TAB, "Event Name", event.getEventName());
                        report.addToTab(EVENT_INFO_TAB, "Is Async", event.isAsynchronous());
                        Map<String, Object> eventData = new HashMap<>();
                        Class eventClass = event.getClass();
                        do {
                            if (eventClass != Event.class) {
                                // Info already provided ^
                                for (Field field : eventClass.getDeclaredFields()) {
                                    if (field.getType() == HandlerList.class) {
                                        // Unneeded Data
                                        continue;
                                    }
                                    field.setAccessible(true);
                                    try {
                                        Object value = field.get(event);
                                        if (value instanceof EntityDamageEvent.DamageModifier) {
                                            value = value.getClass().getCanonicalName() + "." + ((EntityDamageEvent.DamageModifier) value).name();
                                        }
                                        if (value instanceof Enum) {
                                            value = value.getClass().getCanonicalName() + "." + ((Enum) value).name();
                                        }
                                        eventData.put(field.getName(), value);
                                    } catch (IllegalAccessException ignored) {
                                    } catch (Throwable internalE) {
                                        eventData.put(field.getName(), "Error getting field data: " + internalE.getClass().getCanonicalName() + (internalE.getMessage() != null && internalE.getMessage().trim().length() > 0 ? ": " + internalE.getMessage() : ""));
                                    }
                                }
                            }
                            eventClass = eventClass.getSuperclass();
                        } while (eventClass != null);
                        report.addToTab(EVENT_INFO_TAB, "Event Data", eventData);
                    }));
                }
                log.info("Caught exception");
                // let bukkit handle it
                ACFUtil.sneaky(e);
            }
        });
    } catch (Throwable e) {
        log.severe("Could not register proxy plugin manager");
        e.printStackTrace();
    }
// scheduler //TODO figure out how we can better catch those, we dn't want to use nms...
// try {
// Field schedulerField = Bukkit.getServer().getClass().getDeclaredField("scheduler");
// schedulerField.setAccessible(true);
// if (Modifier.isFinal(schedulerField.getModifiers())) {
// Field modifierField = Field.class.getDeclaredField("modifiers");
// modifierField.setAccessible(true);
// modifierField.set(schedulerField, schedulerField.getModifiers() & ~Modifier.FINAL);
// }
// schedulerField.set(Bukkit.getServer(), new LoggedScheduler(voxelGamesLib) {
// @Override
// protected void customHandler(int taskID, Throwable e) {
// if(enableNi)bugsnag.notify(e.getCause(), Severity.ERROR, (report) -> {
// report.addToTab(TASK_INFO_TAB, "Task ID", taskID);
// });
// log.info("Caught exception");
// ACFUtil.sneaky(e); // let bukkit handle it
// }
// });
// } catch (Throwable e) {
// log.severe("Could not register proxy scheduler");
// e.printStackTrace();
// }
}
Also used : Set(java.util.Set) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap) Field(java.lang.reflect.Field) Permission(org.bukkit.permissions.Permission) Event(org.bukkit.event.Event) EntityDamageEvent(org.bukkit.event.entity.EntityDamageEvent) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CommandMap(org.bukkit.command.CommandMap) CommandMap(org.bukkit.command.CommandMap)

Example 13 with Event

use of org.bukkit.event.Event 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 14 with Event

use of org.bukkit.event.Event in project DiscordSRV by Scarsz.

the class PluginUtil method unloadPlugin.

public static void unloadPlugin(Plugin plugin) {
    String name = plugin.getName();
    PluginManager pluginManager = Bukkit.getPluginManager();
    SimpleCommandMap commandMap = null;
    List<Plugin> plugins = null;
    Map<String, Plugin> names = null;
    Map<String, Command> commands = null;
    Map<Event, SortedSet<RegisteredListener>> listeners = null;
    boolean reloadListeners = true;
    pluginManager.disablePlugin(plugin);
    try {
        Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins");
        pluginsField.setAccessible(true);
        plugins = (List<Plugin>) pluginsField.get(pluginManager);
        Field lookupNamesField = Bukkit.getPluginManager().getClass().getDeclaredField("lookupNames");
        lookupNamesField.setAccessible(true);
        names = (Map<String, Plugin>) lookupNamesField.get(pluginManager);
        try {
            Field listenersField = Bukkit.getPluginManager().getClass().getDeclaredField("listeners");
            listenersField.setAccessible(true);
            listeners = (Map<Event, SortedSet<RegisteredListener>>) listenersField.get(pluginManager);
        } catch (Exception e) {
            reloadListeners = false;
        }
        Field commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap");
        commandMapField.setAccessible(true);
        commandMap = (SimpleCommandMap) commandMapField.get(pluginManager);
        Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
        knownCommandsField.setAccessible(true);
        commands = (Map<String, Command>) knownCommandsField.get(commandMap);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        e.printStackTrace();
    }
    pluginManager.disablePlugin(plugin);
    if (plugins != null && plugins.contains(plugin))
        plugins.remove(plugin);
    if (names != null && names.containsKey(name))
        names.remove(name);
    if (listeners != null && reloadListeners) {
        for (SortedSet<RegisteredListener> set : listeners.values()) {
            set.removeIf(value -> value.getPlugin() == plugin);
        }
    }
    if (commandMap != null) {
        for (Iterator<Map.Entry<String, Command>> it = commands.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<String, Command> entry = it.next();
            if (entry.getValue() instanceof PluginCommand) {
                PluginCommand c = (PluginCommand) entry.getValue();
                if (c.getPlugin() == plugin) {
                    c.unregister(commandMap);
                    it.remove();
                }
            }
        }
    }
    ClassLoader cl = plugin.getClass().getClassLoader();
    if (cl instanceof URLClassLoader) {
        try {
            ((URLClassLoader) cl).close();
        } catch (IOException ex) {
            Logger.getLogger(PluginUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    System.gc();
}
Also used : SimpleCommandMap(org.bukkit.command.SimpleCommandMap) SortedSet(java.util.SortedSet) PluginManager(org.bukkit.plugin.PluginManager) Field(java.lang.reflect.Field) URLClassLoader(java.net.URLClassLoader) RegisteredListener(org.bukkit.plugin.RegisteredListener) PluginCommand(org.bukkit.command.PluginCommand) IOException(java.io.IOException) IOException(java.io.IOException) PluginCommand(org.bukkit.command.PluginCommand) Command(org.bukkit.command.Command) URLClassLoader(java.net.URLClassLoader) Event(org.bukkit.event.Event) SimpleCommandMap(org.bukkit.command.SimpleCommandMap) Map(java.util.Map) Plugin(org.bukkit.plugin.Plugin) JavaPlugin(org.bukkit.plugin.java.JavaPlugin)

Example 15 with Event

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

the class MyPetManager method activateMyPet.

// All ----------------------------------------------------------------------
public Optional<MyPet> activateMyPet(StoredMyPet storedMyPet) {
    if (storedMyPet == null) {
        return Optional.empty();
    }
    if (!storedMyPet.getOwner().isOnline()) {
        return Optional.empty();
    }
    if (storedMyPet.getOwner().hasMyPet()) {
        if (!deactivateMyPet(storedMyPet.getOwner(), true)) {
            return Optional.empty();
        }
    }
    Event event = new MyPetLoadEvent(storedMyPet);
    Bukkit.getServer().getPluginManager().callEvent(event);
    MyPet myPet = MyPetClass.getByMyPetType(storedMyPet.getPetType()).getNewMyPetInstance(storedMyPet.getOwner());
    myPet.setUUID(storedMyPet.getUUID());
    myPet.setPetName(storedMyPet.getPetName());
    myPet.setRespawnTime(storedMyPet.getRespawnTime());
    myPet.setWorldGroup(storedMyPet.getWorldGroup());
    myPet.setInfo(storedMyPet.getInfo());
    myPet.setLastUsed(storedMyPet.getLastUsed());
    myPet.setWantsToRespawn(storedMyPet.wantsToRespawn());
    myPet.getExperience().setExp(storedMyPet.getExp());
    myPet.setSkilltree(storedMyPet.getSkilltree());
    Collection<Skill> skills = myPet.getSkills().all();
    if (skills.size() > 0) {
        for (Skill skill : skills) {
            if (skill instanceof NBTStorage) {
                NBTStorage storageSkill = (NBTStorage) skill;
                if (storedMyPet.getSkillInfo().getCompoundData().containsKey(skill.getName())) {
                    storageSkill.load(storedMyPet.getSkillInfo().getAs(skill.getName(), TagCompound.class));
                }
            }
        }
    }
    myPet.setHealth(storedMyPet.getHealth());
    myPet.setSaturation(storedMyPet.getSaturation());
    mActivePetsPlayer.put(myPet, myPet.getOwner());
    event = new MyPetActivatedEvent(myPet);
    Bukkit.getServer().getPluginManager().callEvent(event);
    return Optional.of(myPet);
}
Also used : MyPetLoadEvent(de.Keyle.MyPet.api.event.MyPetLoadEvent) Skill(de.Keyle.MyPet.api.skill.skilltree.Skill) MyPet(de.Keyle.MyPet.api.entity.MyPet) InactiveMyPet(de.Keyle.MyPet.entity.InactiveMyPet) StoredMyPet(de.Keyle.MyPet.api.entity.StoredMyPet) MyPetActivatedEvent(de.Keyle.MyPet.api.event.MyPetActivatedEvent) Event(org.bukkit.event.Event) MyPetLoadEvent(de.Keyle.MyPet.api.event.MyPetLoadEvent) NBTStorage(de.Keyle.MyPet.api.util.NBTStorage) MyPetActivatedEvent(de.Keyle.MyPet.api.event.MyPetActivatedEvent) TagCompound(de.keyle.knbt.TagCompound)

Aggregations

Event (org.bukkit.event.Event)26 Listener (org.bukkit.event.Listener)8 Test (org.junit.Test)7 EventException (org.bukkit.event.EventException)6 EventHandler (org.bukkit.event.EventHandler)6 EventExecutor (org.bukkit.plugin.EventExecutor)6 PluginManager (org.bukkit.plugin.PluginManager)6 RegisteredListener (org.bukkit.plugin.RegisteredListener)5 Cancellable (org.bukkit.event.Cancellable)4 TestEvent (org.bukkit.event.TestEvent)4 Field (java.lang.reflect.Field)3 Map (java.util.Map)3 Set (java.util.Set)3 EventPriority (org.bukkit.event.EventPriority)3 File (java.io.File)2 Method (java.lang.reflect.Method)2 List (java.util.List)2 ConquerFaction (me.andrew28.addons.conquer.api.ConquerFaction)2 ConquerPlayer (me.andrew28.addons.conquer.api.ConquerPlayer)2 ConquerFactionCreateEvent (me.andrew28.addons.conquer.api.events.ConquerFactionCreateEvent)2