Search in sources :

Example 1 with EventException

use of org.bukkit.event.EventException in project Bukkit by Bukkit.

the class JavaPluginLoader method createRegisteredListeners.

public Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(Listener listener, final Plugin plugin) {
    Validate.notNull(plugin, "Plugin can not be null");
    Validate.notNull(listener, "Listener can not be null");
    boolean useTimings = server.getPluginManager().useTimings();
    Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<Class<? extends Event>, Set<RegisteredListener>>();
    Set<Method> methods;
    try {
        Method[] publicMethods = listener.getClass().getMethods();
        methods = new HashSet<Method>(publicMethods.length, Float.MAX_VALUE);
        for (Method method : publicMethods) {
            methods.add(method);
        }
        for (Method method : listener.getClass().getDeclaredMethods()) {
            methods.add(method);
        }
    } catch (NoClassDefFoundError e) {
        plugin.getLogger().severe("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist.");
        return ret;
    }
    for (final Method method : methods) {
        final EventHandler eh = method.getAnnotation(EventHandler.class);
        if (eh == null)
            continue;
        final Class<?> checkClass;
        if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) {
            plugin.getLogger().severe(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass());
            continue;
        }
        final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class);
        method.setAccessible(true);
        Set<RegisteredListener> eventSet = ret.get(eventClass);
        if (eventSet == null) {
            eventSet = new HashSet<RegisteredListener>();
            ret.put(eventClass, eventSet);
        }
        for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) {
            // This loop checks for extending deprecated events
            if (clazz.getAnnotation(Deprecated.class) != null) {
                Warning warning = clazz.getAnnotation(Warning.class);
                WarningState warningState = server.getWarningState();
                if (!warningState.printFor(warning)) {
                    break;
                }
                plugin.getLogger().log(Level.WARNING, String.format("\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated." + " \"%s\"; please notify the authors %s.", plugin.getDescription().getFullName(), clazz.getName(), method.toGenericString(), (warning != null && warning.reason().length() != 0) ? warning.reason() : "Server performance will be affected", Arrays.toString(plugin.getDescription().getAuthors().toArray())), warningState == WarningState.ON ? new AuthorNagException(null) : null);
                break;
            }
        }
        EventExecutor executor = new EventExecutor() {

            public void execute(Listener listener, Event event) throws EventException {
                try {
                    if (!eventClass.isAssignableFrom(event.getClass())) {
                        return;
                    }
                    method.invoke(listener, event);
                } catch (InvocationTargetException ex) {
                    throw new EventException(ex.getCause());
                } catch (Throwable t) {
                    throw new EventException(t);
                }
            }
        };
        if (useTimings) {
            eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled()));
        } else {
            eventSet.add(new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled()));
        }
    }
    return ret;
}
Also used : Warning(org.bukkit.Warning) HashSet(java.util.HashSet) Set(java.util.Set) WarningState(org.bukkit.Warning.WarningState) TimedRegisteredListener(org.bukkit.plugin.TimedRegisteredListener) Listener(org.bukkit.event.Listener) RegisteredListener(org.bukkit.plugin.RegisteredListener) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) EventHandler(org.bukkit.event.EventHandler) TimedRegisteredListener(org.bukkit.plugin.TimedRegisteredListener) TimedRegisteredListener(org.bukkit.plugin.TimedRegisteredListener) RegisteredListener(org.bukkit.plugin.RegisteredListener) AuthorNagException(org.bukkit.plugin.AuthorNagException) EventException(org.bukkit.event.EventException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) EventExecutor(org.bukkit.plugin.EventExecutor) Event(org.bukkit.event.Event) PluginEnableEvent(org.bukkit.event.server.PluginEnableEvent) PluginDisableEvent(org.bukkit.event.server.PluginDisableEvent)

Example 2 with EventException

use of org.bukkit.event.EventException in project HawkEye by oliverwoodings.

the class HawkEyeListener method registerEvents.

public final void registerEvents() {
    PluginManager pm = plugin.getServer().getPluginManager();
    Method[] methods = this.getClass().getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        final Method method = methods[i];
        final HawkEvent he = method.getAnnotation(HawkEvent.class);
        if (he == null)
            continue;
        boolean register = false;
        for (DataType dt : he.dataType()) {
            if (Config.isLogged(dt))
                register = true;
        }
        if (!register)
            continue;
        Class<?>[] params = method.getParameterTypes();
        if (!Event.class.isAssignableFrom(params[0]) || params.length != 1) {
            continue;
        }
        final Class<? extends Event> eventClass = params[0].asSubclass(Event.class);
        method.setAccessible(true);
        EventExecutor executor = new EventExecutor() {

            public void execute(Listener listener, Event event) throws EventException {
                try {
                    if (!eventClass.isAssignableFrom(event.getClass())) {
                        return;
                    }
                    Util.debug(DebugLevel.HIGH, "Calling event: " + event.getEventName());
                    method.invoke(listener, event);
                    Util.debug(DebugLevel.HIGH, "Event call complete: " + event.getEventName());
                } catch (Exception ex) {
                    throw new EventException(ex.getCause());
                }
            }
        };
        Util.debug("Registering listener for " + eventClass.getName());
        pm.registerEvent(eventClass, this, he.priority(), executor, plugin, he.ignoreCancelled());
    }
}
Also used : Listener(org.bukkit.event.Listener) EventException(org.bukkit.event.EventException) Method(java.lang.reflect.Method) EventException(org.bukkit.event.EventException) PluginManager(org.bukkit.plugin.PluginManager) EventExecutor(org.bukkit.plugin.EventExecutor) DataType(uk.co.oliwali.HawkEye.DataType) Event(org.bukkit.event.Event) HawkEvent(uk.co.oliwali.HawkEye.HawkEvent) HawkEvent(uk.co.oliwali.HawkEye.HawkEvent)

Example 3 with EventException

use of org.bukkit.event.EventException in project Essentials by drtshock.

the class EssentialsSpawn method onEnable.

@Override
public void onEnable() {
    final PluginManager pluginManager = getServer().getPluginManager();
    ess = (IEssentials) pluginManager.getPlugin("Essentials");
    if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) {
        LOGGER.log(Level.WARNING, tl("versionMismatchAll"));
    }
    if (!ess.isEnabled()) {
        this.setEnabled(false);
        return;
    }
    spawns = new SpawnStorage(ess);
    ess.addReloadListener(spawns);
    final EssentialsSpawnPlayerListener playerListener = new EssentialsSpawnPlayerListener(ess, spawns);
    EventPriority respawnPriority = ess.getSettings().getRespawnPriority();
    if (respawnPriority != null) {
        pluginManager.registerEvent(PlayerRespawnEvent.class, playerListener, respawnPriority, new EventExecutor() {

            @Override
            public void execute(final Listener ll, final Event event) throws EventException {
                ((EssentialsSpawnPlayerListener) ll).onPlayerRespawn((PlayerRespawnEvent) event);
            }
        }, this);
    }
    EventPriority joinPriority = ess.getSettings().getSpawnJoinPriority();
    if (joinPriority != null) {
        pluginManager.registerEvent(PlayerJoinEvent.class, playerListener, joinPriority, new EventExecutor() {

            @Override
            public void execute(final Listener ll, final Event event) throws EventException {
                ((EssentialsSpawnPlayerListener) ll).onPlayerJoin((PlayerJoinEvent) event);
            }
        }, this);
    }
}
Also used : PluginManager(org.bukkit.plugin.PluginManager) PlayerJoinEvent(org.bukkit.event.player.PlayerJoinEvent) EventExecutor(org.bukkit.plugin.EventExecutor) Listener(org.bukkit.event.Listener) EventException(org.bukkit.event.EventException) PlayerRespawnEvent(org.bukkit.event.player.PlayerRespawnEvent) PlayerJoinEvent(org.bukkit.event.player.PlayerJoinEvent) Event(org.bukkit.event.Event) PlayerRespawnEvent(org.bukkit.event.player.PlayerRespawnEvent) EventPriority(org.bukkit.event.EventPriority)

Example 4 with EventException

use of org.bukkit.event.EventException 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 5 with EventException

use of org.bukkit.event.EventException 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)

Aggregations

Event (org.bukkit.event.Event)6 EventException (org.bukkit.event.EventException)6 Listener (org.bukkit.event.Listener)6 EventExecutor (org.bukkit.plugin.EventExecutor)6 EventPriority (org.bukkit.event.EventPriority)4 PluginManager (org.bukkit.plugin.PluginManager)4 Method (java.lang.reflect.Method)3 RegisteredListener (org.bukkit.plugin.RegisteredListener)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Set (java.util.Set)2 EventHandler (org.bukkit.event.EventHandler)2 HandlerList (org.bukkit.event.HandlerList)2 PlayerJoinEvent (org.bukkit.event.player.PlayerJoinEvent)2 PlayerRespawnEvent (org.bukkit.event.player.PlayerRespawnEvent)2 AuthorNagException (org.bukkit.plugin.AuthorNagException)2 TimedRegisteredListener (org.bukkit.plugin.TimedRegisteredListener)2 Lists (com.google.common.collect.Lists)1 ReflectionUtils (com.laytonsmith.PureUtilities.Common.ReflectionUtils)1 EventIdentifier (com.laytonsmith.annotations.EventIdentifier)1 File (java.io.File)1