@Override // 计算调用次数和花费总时间以及花费最多的时间 public void execute(Listener listener, Event e) throws EventException { if (e.isAsynchronous()) { this.eventExecutor.execute(listener, e); } else { long startTime = System.nanoTime(); try { try{ this.eventExecutor.execute(listener, e); }catch(Throwable ex){ MonitorUtils.AExceptionCatcher(plugin, ex); } } finally { long endTime = System.nanoTime(); long executeTime = endTime - startTime; if(ConfigFunction.MonitorPluginLagWarningenable){ if(executeTime/1000000 > ConfigFunction.MonitorPluginLagWarningPeriod){ AzureAPI.log("警告!服务器主线程陷入停顿超过配置设定值!因为插件" + this.getPlugin().getName() + " 执行了一次耗时 " + executeTime/1000000 + " 毫秒的位于 " + listener.getClass().getName() + " 的监听器 " + e.getEventName() + " 的操作!"); } } this.record(e.getEventName(), executeTime); } } }
@Override protected void onEnable() { EventExecutor.getInstance().register(this); // load config this.config = Moo.getInstance().loadConfig(Lightning.getInstance().getDataFolder()); this.languageManager = new LanguageManager(Lightning.getInstance().getDataFolder(), s -> ChatColor.translateAlternateColorCodes('&', s)); this.languageManager.load("language"); // if disabled stop enabling if(!((boolean) config.get("activated"))) { Lightning.getInstance().getLogs().info("*** Lightning disabled. ***"); return; } // register handler Moo.getInstance().registerHandler(o -> { if(o instanceof Listener) Bukkit.getServer().getPluginManager().registerEvents((Listener) o, Lightning.getInstance()); }, new ChatListener(), new ServerListener()); // connect to cloud if(config.isLoaded()) { Moo.getInstance().connect(config.get("group-id"), ClientType.SERVER, config.get("cloud-ip"), config.get("cloud-port")); } }
public static Class<?> generateClass() throws NotFoundException, CannotCompileException { ClassPool classpath = ClassPool.getDefault(); classpath.insertClassPath(new ClassClassPath(EventCallbackGenerator.class)); CtClass eventClass = classpath.makeClass("online.pizzacrust.lukkitplus" + ".EventCallback"); eventClass.addInterface(classpath.get(Listener.class.getName())); for (Class<? extends Event> event : LukkitPlus.BUKKIT_EVENTS) { if (containsStaticHandlerList(event)) { CtMethod eventMethod = CtNewMethod.make(CtClass.voidType, "on" + event.getSimpleName (), new CtClass[]{classpath.get(event.getName())}, new CtClass[0], "online" + ".pizzacrust.lukkitplus.EventCallbackGenerator.call($1);", eventClass); eventClass.addMethod(eventMethod); AnnotationsAttribute attribute = new AnnotationsAttribute(eventClass.getClassFile() .getConstPool(), AnnotationsAttribute.visibleTag); Annotation eventHandlerAnnt = new Annotation(EventHandler.class.getName(), eventClass .getClassFile().getConstPool()); attribute.addAnnotation(eventHandlerAnnt); eventMethod.getMethodInfo().addAttribute(attribute); } } return eventClass.toClass(LukkitPlus.class.getClassLoader()); }
/** * Registers the given spell */ public void register(Spell spell) { spells.put(spell.getName(), spell); MystiCraft.getCraftingManager().addRecipe(spell.getRecipe()); if (spell instanceof Listener) { MystiCraft.getInstance().getServer().getPluginManager().registerEvents((Listener) spell, MystiCraft.getInstance()); } if (spell instanceof Configurable) { if (!spellConfig.getConfig().has(spell.getName())) { JsonObject obj = new JsonObject(); ((Configurable) spell).setDefaults(obj); spellConfig.getConfig().add(spell.getName(), obj); spellConfig.saveConfig(); ((Configurable) spell).load(obj); } else { ((Configurable) spell).load(spellConfig.getConfig().get(spell.getName()).getAsJsonObject()); } } }
@Override public void callEvent(Event event) throws IllegalStateException { events.add(event); for (Listener listener : eventListeners.values()) { for (Method method : listener.getClass().getMethods()) { if (method.isAnnotationPresent(EventHandler.class) && method.getParameterCount() == 1 && method.getParameters()[0].getType().isInstance(event)) { try { method.invoke(listener, event); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } } } }
@Override // 计算调用次数和花费总时间以及花费最多的时间 public void execute(Listener listener, Event e) throws EventException { if (e.isAsynchronous()) { this.eventExecutor.execute(listener, e); } else { long startTime = System.nanoTime(); try { this.eventExecutor.execute(listener, e); } finally { long endTime = System.nanoTime(); long executeTime = endTime - startTime; this.record(e.getEventName(), executeTime); } } }
public void unregister(@Nonnull Listener listener, @Nonnull Game game) { //noinspection unchecked Arrays.stream(listener.getClass().getMethods()) .filter((method -> method.isAnnotationPresent(GameEvent.class))) .filter(method -> method.getParameterCount() != 1 || method.getParameterCount() != 2) .filter(method -> Event.class.isAssignableFrom(method.getParameterTypes()[0])) .map(method -> (Class<Event>) method.getParameterTypes()[0]).forEach( eventClass -> activeEvents.get(eventClass).removeIf(registeredListener -> registeredListener.getListener().equals(listener))); if (activeListeners.containsKey(game.getUuid())) { activeListeners.get(game.getUuid()).removeIf(registeredListener -> registeredListener.getListener().equals(listener)); if (activeListeners.get(game.getUuid()).size() == 0) { activeListeners.remove(game.getUuid()); } } HandlerList.unregisterAll(listener); }
@Override protected Listener listener(Consumer<Block> callback) { return new Listener() { @EventHandler public void onClick(PlayerInteractEvent event) { Player clicker = event.getPlayer(); EquipmentSlot hand = event.getHand(); Block block = event.getClickedBlock(); if (block != null && clicker.equals(player) && (!MCUtils.isOffHandSupport() || hand == EquipmentSlot.HAND)) { clicker.sendMessage(MCUtils.colorize(messageFunc.apply(block))); callback.accept(block); event.setCancelled(true); } } }; }
public static void init(MCLibrary plugin) { Bukkit.getPluginManager().registerEvents(new Listener() { @EventHandler @SuppressWarnings("deprecation") public void onInteract(PlayerInteractEvent event) { if (MCUtils.isOffHandSupport() && event.getHand() != EquipmentSlot.HAND) return; Player player = event.getPlayer(); Block block = event.getClickedBlock(); if (block == null || !INFO_LISTENERS.contains(player)) return; Location loc = block.getLocation(); CommandSenderWrapper wrapper = new CommandSenderWrapper(player); wrapper.sendMessage("---------------------------------------------"); wrapper.sendMessage("&eworld: &f" + loc.getWorld().getName()); wrapper.sendMessage(String.format("&ex: &f%s (%s)", loc.getBlockX(), loc.getX())); wrapper.sendMessage(String.format("&ey: &f%s (%s)", loc.getBlockY(), loc.getY())); wrapper.sendMessage(String.format("&ez: &f%s (%s)", loc.getBlockZ(), loc.getZ())); wrapper.sendMessage(String.format("&eblock: &f%s:%s (%s)", block.getTypeId(), block.getData(), block.getType().name())); } }, plugin); }
@Override public void registerEvent(Class<? extends Event> event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) { Validate.notNull(listener, "Listener cannot be null"); Validate.notNull(priority, "Priority cannot be null"); Validate.notNull(executor, "Executor cannot be null"); Validate.notNull(plugin, "Plugin cannot be null"); if (!plugin.isEnabled()) { throw new IllegalPluginAccessException("Plugin attempted to register " + event + " while not enabled"); } if (useTimings) { getEventListeners(event).register(new TimedRegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); } else { getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); } }
public Listener interactListener() { return new Listener() { @EventHandler public void onInteract(PlayerInteractEvent e) { if (!(e.getPlayer().getEquipment().getItemInMainHand() == null)) { return; } if (!(e.getItem() == null)) { return; } if (!(e.getItem().getType() == null)) { return; } if (!(e.getItem().getType() == Material.AIR)) { return; } if (!e.getPlayer().getEquipment().getItemInMainHand().getItemMeta().getLore().contains(ChatColor.RED + getName())) { return; } if (!applicableTo().contains(e.getItem().getType())) { return; } if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { getRun().run(e.getPlayer(), e.getClickedBlock()); } else if (e.getAction() == Action.RIGHT_CLICK_AIR) { getRun().run(e.getPlayer(), null); } } }; }
@Override public void register(final Trigger trigger) { // if (types == null) { // final BlockLocation l = new BlockLocation(world, x, y, z); // List<Trigger> ts = blockTriggers.get(l); // if (ts == null) // blockTriggers.put(l, ts = new ArrayList<Trigger>()); // ts.add(trigger); // } else { for (final ItemType t : types) { for (final ItemData d : t) { if (d.getId() > Skript.MAXBLOCKID) continue; List<Trigger> ts = itemTypeTriggers.get(d.getId()); if (ts == null) itemTypeTriggers.put(d.getId(), ts = new ArrayList<Trigger>()); ts.add(trigger); } } // } if (!registeredExecutor) { Bukkit.getPluginManager().registerEvent(PlayerMoveEvent.class, new Listener() {}, SkriptConfig.defaultEventPriority.value(), executor, Skript.getInstance(), true); registeredExecutor = true; } }
public static void init(JavaPlugin plugin) { Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { try { BufferedReader reader = URLs.IP_CHECKER.openBufferedReader(); address = reader.readLine(); } catch (IOException e) { // Ignore } }); Bukkit.getPluginManager().registerEvents(new Listener() { @EventHandler public void onLogin(PlayerLoginEvent event) throws UnknownHostException { String host = event.getHostname(); String addrStr = host.substring(0, host.indexOf(':')); InetAddress addr = InetAddress.getByName(addrStr); if (!addr.isLoopbackAddress() && !addr.isSiteLocalAddress()) { address = addrStr; event.getHandlers().unregister(this); } } }, plugin); }
/** * Registers the given event to the specified listener using a directly * passed EventExecutor * * @param event Event class to register * @param listener PlayerListener to register * @param priority Priority of this event * @param executor EventExecutor to register * @param plugin Plugin to register * @param ignoreCancelled Do not call executor if event was already * cancelled */ public void registerEvent(Class<? extends Event> event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) { Validate.notNull(listener, "Listener cannot be null"); Validate.notNull(priority, "Priority cannot be null"); Validate.notNull(executor, "Executor cannot be null"); Validate.notNull(plugin, "Plugin cannot be null"); if (!plugin.isEnabled()) { throw new IllegalPluginAccessException("Plugin attempted to register " + event + " while not enabled"); } if (useTimings) { getEventListeners(event).register(new TimedRegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); } else { getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); } }
public static void load(CSCoreLib plugin) { if (ReflectionUtils.getVersion().startsWith("v1_9_")) { plugin.getServer().getPluginManager().registerEvents(new CustomBookOverlay1_9(), plugin); } else if (ReflectionUtils.getVersion().startsWith("v1_10_")) { plugin.getServer().getPluginManager().registerEvents(new CustomBookOverlay1_9(), plugin); } else if (ReflectionUtils.getVersion().startsWith("v1_11_")) { plugin.getServer().getPluginManager().registerEvents(new CustomBookOverlay1_9(), plugin); } else if (ReflectionUtils.getVersion().startsWith("v1_12_")) { plugin.getServer().getPluginManager().registerEvents(new CustomBookOverlay1_9(), plugin); } plugin.getServer().getPluginManager().registerEvents(new Listener() { @EventHandler public void onDrop(PlayerDropItemEvent e) { if (opening.contains(e.getPlayer().getUniqueId())) e.setCancelled(true); } }, plugin); }
/** * Called right after the world has loaded. * No players are in the world at this point. */ public void load() { modules.addAll(matchManifest.allocateCoreModules()); modules.addAll(matchManifest.allocateGameModules()); /* * Core managers initialize off of MatchLoadEvent * so we call it first. */ Bukkit.getPluginManager().callEvent(new MatchLoadEvent(this)); //now load all the modules. int listenerCount = 0; for (ModuleLoadTime moduleLoadTime : ModuleLoadTime.values()) { for (MatchModule matchModule : getModules(moduleLoadTime)) { try { matchModule.load(this); } catch (Exception e) { e.printStackTrace(); TGM.get().getPlayerManager().broadcastToAdmins(ChatColor.RED + "[JSON] Failed to parse module: " + matchModule.getClass().getSimpleName()); try { matchModule.unload(); } catch (Exception e2) { e2.printStackTrace(); } } //automatically register modules that implement listener. if (matchModule instanceof Listener) { TGM.registerEvents((Listener) matchModule); listenerCount++; } } } Bukkit.getLogger().info("Loaded " + modules.size() + " modules (" + listenerCount + " listeners)"); Bukkit.getPluginManager().callEvent(new MatchPostLoadEvent(this)); }
/** * Called after all players have left the match. * This is the last call before the world is unloaded. */ public void unload() { for (MatchModule module : modules) { module.unload(); if (module instanceof Listener) { HandlerList.unregisterAll((Listener) module); } } }
@Override public void load(Match match) { if (match.getMapContainer().getMapInfo().getJsonObject().has("filters")) { for (JsonElement filterElement : match.getMapContainer().getMapInfo().getJsonObject().getAsJsonArray("filters")) { JsonObject filterJson = filterElement.getAsJsonObject(); for (FilterType filterType : initFilter(match, filterJson)) { filterTypes.add(filterType); if (filterType instanceof Listener) { TGM.get().registerEvents((Listener) filterType); } } } } }
@Override public void unload() { for (FilterType filterType : filterTypes) { if (filterType instanceof Listener) { HandlerList.unregisterAll((Listener) filterType); } } }
@Nonnull @Override public <T extends Listener> T registerListener(@Nonnull T listener) { Preconditions.checkNotNull(listener, "listener"); getServer().getPluginManager().registerEvents(listener, this); return listener; }
@SuppressWarnings("JavaReflectionMemberAccess") private static void unregisterListener(Class<? extends Event> eventClass, Listener listener) { try { // unfortunately we can't cache this reflect call, as the method is static Method getHandlerListMethod = eventClass.getMethod("getHandlerList"); HandlerList handlerList = (HandlerList) getHandlerListMethod.invoke(null); handlerList.unregister(listener); } catch (Throwable t) { // ignored } }
/** * Register bukkit events. */ private void registerBukkitEvents() { listener = new Listener() { // @EventHandler(priority = EventPriority.LOWEST) // public final void onPlayerLogin(PlayerLoginEvent e) { // if (closed) // return; // // Channel channel = getChannel(e.getPlayer()); // // // Don't inject players that have been explicitly uninjected // if (!uninjectedChannels.contains(channel)) { // injectPlayer(e.getPlayer()); // } // } @EventHandler public final void onPluginDisable(PluginDisableEvent e) { if (e.getPlugin().equals(plugin)) { close(); } } }; plugin.getServer().getPluginManager().registerEvents(listener, plugin); }
@SuppressWarnings({"WeakerAccess", "SameParameterValue"}) public void registerEvent(final Class<? extends Event> event, final EventPriority priority, final IFn method, final boolean ignoreCancelled) { Set<IFn> methods = events.getOrDefault(event, new HashSet<>()); methods.add(method); events.put(event, methods); getServer().getPluginManager().registerEvent(event, new Listener() { }, priority, executor, this, ignoreCancelled); }
@Override public void registerEvents(Listener listener) { if(listeners.add(listener)) { guavaEventBus.register(listener); matchEventRegistry.startListening(this, listener); } }
@Override public void unregisterEvents(Listener listener) { if(listeners.remove(listener)) { matchEventRegistry.stopListening(this, listener); guavaEventBus.unregister(listener); } }
@Override public void registerEventsAndRepeatables(Object thing) { registerRepeatable(thing); if(thing instanceof Listener) { registerEvents((Listener) thing); } }
private Loader createLoader(Class<? extends Listener> listenerType, @Nullable MatchScope scope) { scope = listenerScope(listenerType, scope); if(logger.isLoggable(Level.FINE)) { logger.fine("Registering listener type " + listenerType.getName() + " in scope " + scope); } final ImmutableSet.Builder<Loader> builder = ImmutableSet.builder(); for(EventHandlerInfo<? extends Event> handler : bukkitScanner.findEventHandlers(listenerType).values()) { builder.add(createLoader(handler, listenerScope(handler.method(), scope))); } final ImmutableSet<Loader> loaders = builder.build(); return (match, listener) -> loaders.forEach(loader -> loader.load(match, listener)); }
default <T extends Listener> void matchListener(Key<T> key, @Nullable MatchScope scope) { inSet(MatchListenerMeta.class).addBinding().toInstance( new MatchListenerMeta((Class<T>) key.getTypeLiteral().getRawType(), scope) ); inSet(Key.get(Listener.class, ForMatch.class)) .addBinding().to(key); }
default <T extends Listener> void matchOptionalListener(Key<T> key, @Nullable MatchScope scope) { inSet(MatchListenerMeta.class).addBinding().toInstance( new MatchListenerMeta((Class<T>) key.getTypeLiteral().getRawType(), scope) ); final Key<Optional<T>> optionalKey = Keys.optional(key); inSet(Key.get(new TypeLiteral<Optional<? extends Listener>>(){}, ForMatch.class)) .addBinding().to(optionalKey); }
@Override protected void configure() { super.configure(); // Register the module as a Listener if it is one if(Types.isAssignable(Listener.class, type)) { matchOptionalListener((Class<? extends Listener>) rawType); } }
@Override protected void discover(F facet) { super.discover(facet); if(facet instanceof Listener) { listeners.add((Listener) facet); } }
@Override protected void enableFacet(F facet) throws Exception { super.enableFacet(facet); if(facet instanceof Listener) { eventRegistry.registerListener((Listener) facet); targetedEventBus.registerListener((Listener) facet); } }
@Override protected void disableFacet(F facet) throws Exception { if(facet instanceof Listener) { targetedEventBus.unregisterListener((Listener) facet); eventRegistry.unregisterListener((Listener) facet); } super.disableFacet(facet); }
@Override public void onLoad() { for (Class<?> loaded : findClassesAnnotatedWith(SimpleLoader.class)) { try { Bukkit.getPluginManager().registerEvents((Listener) loaded.getDeclaredConstructors()[0].newInstance(), this); } catch (ReflectiveOperationException ignored) { } } for (AlphaModule module : MODULES) module.load(); }
@Override public void registerEvent(Class<? extends Event> event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin) { // TODO Auto-generated method stub throw new UnimplementedOperationException(); }
@Override public void registerEvent(Class<? extends Event> event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) { // TODO Auto-generated method stub throw new UnimplementedOperationException(); }
public ResourcepackListener(DuctManager ductManager) { this.ductManager = ductManager; if (Bukkit.getPluginManager().isPluginEnabled("AuthMe")) { Bukkit.getPluginManager().registerEvents(new Listener() { @EventHandler public void onAuthMeLogin(fr.xephi.authme.events.LoginEvent e) { initPlayer(e.getPlayer()); } }, TransportPipes.instance); } }
public Intializer() { Listener[] listeners = new Listener[] { new CommandListener(), new CommandOCGlobal(), new JoinAndLeave(), new SQLJoinLeave(), new InventoryClickEvent(), }; for (Listener listener : listeners) Bukkit.getServer().getPluginManager().registerEvents(listener, Core.getInstance()); }
@Override public void onEnable() { Injector injector; log.info("Enabling plugin"); try { RegisteredServiceProvider<Providers> rsp = checkNotNull(getServer().getServicesManager() .getRegistration(Providers.class)); injector = checkNotNull(rsp.getProvider()).getInjector(); } catch (NullPointerException e){ log.error("Failed to get ProvidersLib providers"); getServer().getPluginManager().disablePlugin(this); return; } itemFactory = injector.getInstance(SimpleItemFactory.class); MiniWynnPlugin.injector = injector.createChildInjector(binder -> { binder.bind(Server.class).toInstance(getServer()); binder.bind(Plugin.class).toInstance(this); binder.bind(ItemFactory.class).toInstance(itemFactory); binder.bind(PlayerManager.class).to(SimplePlayerManager.class).asEagerSingleton(); }); listeners.forEach(listener->{ Listener listenerInst = getInjector().getInstance(listener); getServer().getPluginManager().registerEvents(listenerInst, this); }); }