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));
}
}
}
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();
// }
}
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);
}
}
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();
}
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);
}
Aggregations