Java Code Examples for org.bukkit.event.Listener

The following are top voted examples for showing how to use org.bukkit.event.Listener. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ExilePearl   File: TestPluginManager.java   Source Code and License 7 votes vote down vote up
@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));
       }
}
 
Example 2
Project: EscapeLag   File: EventExecutorInjector.java   Source Code and License 6 votes vote down vote up
@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);
		}
	}
}
 
Example 3
Project: MooProject   File: LightningPluginModule.java   Source Code and License 6 votes vote down vote up
@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"));
    }
}
 
Example 4
Project: Lukkit   File: EventCallbackGenerator.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 5
Project: MystiCraft   File: SpellManager.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
		}
	}
}
 
Example 6
Project: MockBukkit   File: PluginManagerMock.java   Source Code and License 6 votes vote down vote up
@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);
				}
			}
		}
	}
}
 
Example 7
Project: NeverLag   File: EventExecutorInjector.java   Source Code and License 6 votes vote down vote up
@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);
		}
	}
}
 
Example 8
Project: VoxelGamesLibv2   File: EventHandler.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 9
Project: MCLibrary   File: ClickWizard.java   Source Code and License 6 votes vote down vote up
@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);
            }
        }
    };
}
 
Example 10
Project: MCLibrary   File: LibraryCommand.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 11
Project: NationZ   File: Ability.java   Source Code and License 6 votes vote down vote up
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);
			}
		}
	};
}
 
Example 12
Project: Skript   File: EvtMoveOn.java   Source Code and License 6 votes vote down vote up
@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;
		}
	}
 
Example 13
Project: K-Security   File: Static.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 14
Project: Thermos-Bukkit   File: SimplePluginManager.java   Source Code and License 6 votes vote down vote up
/**
 * 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));
    }
}
 
Example 15
Project: CS-CoreLib   File: CustomBookOverlay.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 16
Project: Warzone   File: Match.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
}
 
Example 17
Project: Warzone   File: Match.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 18
Project: Warzone   File: FilterManagerModule.java   Source Code and License 5 votes vote down vote up
@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);
                }
            }
        }
    }
}
 
Example 19
Project: Warzone   File: FilterManagerModule.java   Source Code and License 5 votes vote down vote up
@Override
public void unload() {
    for (FilterType filterType : filterTypes) {
        if (filterType instanceof Listener) {
            HandlerList.unregisterAll((Listener) filterType);
        }
    }
}
 
Example 20
Project: helper   File: ExtendedJavaPlugin.java   Source Code and License 5 votes vote down vote up
@Nonnull
@Override
public <T extends Listener> T registerListener(@Nonnull T listener) {
    Preconditions.checkNotNull(listener, "listener");
    getServer().getPluginManager().registerEvents(listener, this);
    return listener;
}
 
Example 21
Project: helper   File: HelperEventListener.java   Source Code and License 5 votes vote down vote up
@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
    }
}
 
Example 22
Project: helper   File: HelperMergedEventListener.java   Source Code and License 5 votes vote down vote up
@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
    }
}
 
Example 23
Project: ZentrelaRPG   File: TinyProtocol.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 24
Project: Bukkit4Clojure   File: Main.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 25
Project: ProjectAres   File: MatchImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void registerEvents(Listener listener) {
    if(listeners.add(listener)) {
        guavaEventBus.register(listener);
        matchEventRegistry.startListening(this, listener);
    }
}
 
Example 26
Project: ProjectAres   File: MatchImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void unregisterEvents(Listener listener) {
    if(listeners.remove(listener)) {
        matchEventRegistry.stopListening(this, listener);
        guavaEventBus.unregister(listener);
    }
}
 
Example 27
Project: ProjectAres   File: MatchImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void registerEventsAndRepeatables(Object thing) {
    registerRepeatable(thing);
    if(thing instanceof Listener) {
        registerEvents((Listener) thing);
    }
}
 
Example 28
Project: ProjectAres   File: MatchEventRegistry.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 29
Project: ProjectAres   File: MatchBinders.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 30
Project: ProjectAres   File: MatchBinders.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 31
Project: ProjectAres   File: MatchModuleManifest.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 32
Project: ProjectAres   File: BukkitFacetContext.java   Source Code and License 5 votes vote down vote up
@Override
protected void discover(F facet) {
    super.discover(facet);

    if(facet instanceof Listener) {
        listeners.add((Listener) facet);
    }
}
 
Example 33
Project: ProjectAres   File: BukkitFacetContext.java   Source Code and License 5 votes vote down vote up
@Override
protected void enableFacet(F facet) throws Exception {
    super.enableFacet(facet);

    if(facet instanceof Listener) {
        eventRegistry.registerListener((Listener) facet);
        targetedEventBus.registerListener((Listener) facet);
    }
}
 
Example 34
Project: ProjectAres   File: BukkitFacetContext.java   Source Code and License 5 votes vote down vote up
@Override
protected void disableFacet(F facet) throws Exception {
    if(facet instanceof Listener) {
        targetedEventBus.unregisterListener((Listener) facet);
        eventRegistry.unregisterListener((Listener) facet);
    }

    super.disableFacet(facet);
}
 
Example 35
Project: AlphaLibary   File: AlphaLibary.java   Source Code and License 5 votes vote down vote up
@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();
}
 
Example 36
Project: Transport-Pipes   File: RenderSystem.java   Source Code and License 5 votes vote down vote up
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);
	}
}
 
Example 37
Project: OnlineChecker-Spigot-SQL-Support   File: Intializer.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 38
Project: MiniWynn   File: MiniWynnPlugin.java   Source Code and License 5 votes vote down vote up
@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);
    });
}
 
Example 39
Project: Kineticraft   File: Items.java   Source Code and License 5 votes vote down vote up
@Override
public void onEnable() {
    // Register all items that are listeners as listeners.
    for (ItemType type : ItemType.values())
        if (Listener.class.isAssignableFrom(type.getItemClass()))
            Bukkit.getPluginManager().registerEvents((Listener) ReflectionUtil.construct(type.getItemClass(),
                    new Class[] {ItemStack.class}, new ItemStack(Material.AIR)), Core.getInstance());
}
 
Example 40
Project: NeverLag   File: ExplodeDisabler.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(Listener listener, Event event) throws EventException {
	if (cm.disableExplode) {
		((Collection<?>) Reflection.getMethod(event.getClass(), "blockList")
			.invoke(event)).clear();
	}
}