org.bukkit.event.Listener Java Examples

The following examples show how to use org.bukkit.event.Listener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EventHandler.java    From VoxelGamesLibv2 with MIT 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 #2
Source File: GameManager.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
private void registerListeners(){
	// Registers Listeners
	List<Listener> listeners = new ArrayList<Listener>();
	listeners.add(new PlayerConnectionListener());
	listeners.add(new PlayerChatListener());
	listeners.add(new PlayerDamageListener());
	listeners.add(new ItemsListener());
	listeners.add(new TeleportListener());
	listeners.add(new PlayerDeathListener());
	listeners.add(new EntityDeathListener());
	listeners.add(new CraftListener());
	listeners.add(new PingListener());
	listeners.add(new BlockListener());
	listeners.add(new WorldListener());
	listeners.add(new PlayerMovementListener(getPlayersManager()));
	listeners.add(new EntityDamageListener());
	for(Listener listener : listeners){
		Bukkit.getServer().getPluginManager().registerEvents(listener, UhcCore.getPlugin());
	}
}
 
Example #3
Source File: MatchImpl.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
private void startListener(Listener listener) {
  for (Map.Entry<Class<? extends Event>, Set<RegisteredListener>> entry :
      PGM.get().getPluginLoader().createRegisteredListeners(listener, PGM.get()).entrySet()) {
    Class<? extends Event> eventClass = entry.getKey();
    HandlerList handlerList = Events.getEventListeners(eventClass);

    // TODO: expand support to other events, such as player, world, entity -- reduce boilerplate
    if (MatchEvent.class.isAssignableFrom(eventClass)) {
      for (final RegisteredListener registeredListener : entry.getValue()) {
        PGM.get()
            .getServer()
            .getPluginManager()
            .registerEvent(
                eventClass,
                listener,
                registeredListener.getPriority(),
                new EventExecutor(registeredListener),
                PGM.get());
      }
    } else {
      handlerList.registerAll(entry.getValue());
    }
  }
}
 
Example #4
Source File: MatchImpl.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected MatchModule createModule(MatchModuleFactory factory) throws ModuleLoadException {
  final MatchModule module = factory.createMatchModule(MatchImpl.this);
  if (module == null) return null;

  module.load();

  matchModules.put(module.getClass(), module);

  if (module instanceof Listener && getListenerScope((Listener) module) == null) {
    logger.warning(
        module.getClass().getSimpleName()
            + " implements Listener but is not annotated with @ListenerScope");
  }

  if (module instanceof Listener) {
    addListener((Listener) module, getListenerScope((Listener) module, MatchScope.RUNNING));
  }

  if (module instanceof Tickable) {
    addTickable((Tickable) module, MatchScope.LOADED);
  }

  return module;
}
 
Example #5
Source File: TListenerHandler.java    From TabooLib with MIT License 6 votes vote down vote up
/**
 * 注销插件的所有监听器
 * 该操作会执行 TListener 注解中的 cancel() 对应方法
 */
public static void cancelListener(Plugin plugin) {
    Optional.ofNullable(listeners.remove(plugin.getName())).ifPresent(listeners -> {
        for (Listener listener : listeners) {
            HandlerList.unregisterAll(listener);
            TListener tListener = listener.getClass().getAnnotation(TListener.class);
            if (!Strings.isBlank(tListener.cancel())) {
                try {
                    Method method = listener.getClass().getDeclaredMethod(tListener.cancel());
                    method.setAccessible(true);
                    method.invoke(listener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
}
 
Example #6
Source File: SimplePluginManager.java    From Kettle with GNU General Public License v3.0 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 #7
Source File: PlaceholderListener.java    From PlaceholderAPI with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onExpansionUnregister(ExpansionUnregisterEvent event) {
  if (event.getExpansion() instanceof Listener) {
    HandlerList.unregisterAll((Listener) event.getExpansion());
  }

  if (event.getExpansion() instanceof Taskable) {
    ((Taskable) event.getExpansion()).stop();
  }

  if (event.getExpansion() instanceof Cacheable) {
    ((Cacheable) event.getExpansion()).clear();
  }

  if (plugin.getExpansionCloud() != null) {

    CloudExpansion ex = plugin.getExpansionCloud()
        .getCloudExpansion(event.getExpansion().getName());

    if (ex != null) {
      ex.setHasExpansion(false);
      ex.setShouldUpdate(false);
    }
  }
}
 
Example #8
Source File: BukkitFacetContext.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void discover(F facet) {
    super.discover(facet);

    if(facet instanceof Listener) {
        listeners.add((Listener) facet);
    }
}
 
Example #9
Source File: BukkitFacetContext.java    From ProjectAres with GNU Affero General Public License v3.0 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 #10
Source File: SimplePluginManager.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
public void registerEvents(Listener listener, Plugin plugin) {
    if (!plugin.isEnabled()) {
        throw new IllegalPluginAccessException("Plugin attempted to register " + listener + " while not enabled");
    }

    for (Map.Entry<Class<? extends Event>, Set<RegisteredListener>> entry : plugin.getPluginLoader().createRegisteredListeners(listener, plugin).entrySet()) {
        getEventListeners(getRegistrationClass(entry.getKey())).registerAll(entry.getValue());
    }

}
 
Example #11
Source File: EventService.java    From mcspring-boot with MIT License 5 votes vote down vote up
private Stream<Method> getListenerMethods(Listener listener) {
    val target = AopUtils.getTargetClass(listener);
    return Arrays.stream(ReflectionUtils.getAllDeclaredMethods(target))
            .filter(method -> method.isAnnotationPresent(EventHandler.class))
            .filter(method -> method.getParameters().length == 1)
            .filter(method -> Event.class.isAssignableFrom(method.getParameters()[0].getType()));
}
 
Example #12
Source File: StaticMethodHandleEventExecutor.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(Listener listener, Event event) throws EventException {
    if (!eventClass.isInstance(event)) {
        return;
    }
    try {
        handle.invoke(event);
    } catch (Throwable t) {
        throw new EventException(t);
    }
}
 
Example #13
Source File: MethodHandleEventExecutor.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(Listener listener, Event event) throws EventException {
    if (!eventClass.isInstance(event)) {
        return;
    }
    try {
        handle.invoke(listener, event);
    } catch (Throwable t) {
        throw new EventException(t);
    }
}
 
Example #14
Source File: ScopePostProcessorTest.java    From mcspring-boot with MIT License 5 votes vote down vote up
@Before
public void setup() {
    when(factory.getBeanDefinitionNames()).thenReturn(new String[]{"bean1", "bean2", "bean3"});

    when(factory.getBeanDefinition("bean1")).thenReturn(bean1);
    when(factory.getBeanDefinition("bean2")).thenReturn(bean2);
    when(factory.getBeanDefinition("bean3")).thenReturn(bean3);

    when(factory.getType("bean1")).thenReturn((Class) Listener.class);
    when(factory.getType("bean2")).thenReturn((Class) Server.class);
    when(factory.getType("bean3")).thenReturn(null);
}
 
Example #15
Source File: SpringSpigotAutoConfigurationTest.java    From mcspring-boot with MIT License 5 votes vote down vote up
@Before
public void setup() {
    Map<String, Listener> beans = new HashMap<>();
    beans.put("b1", mock(Listener.class));
    beans.put("b2", mock(Listener.class));
    when(context.getBeansOfType(Listener.class)).thenReturn(beans);
    when(context.getBean(EventService.class)).thenReturn(eventService);
}
 
Example #16
Source File: ScopePostProcessor.java    From mcspring-boot with MIT License 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
    factory.registerScope("sender", senderContextScope);
    Arrays.stream(factory.getBeanDefinitionNames()).forEach(beanName -> {
        val beanDef = factory.getBeanDefinition(beanName);
        val beanType = factory.getType(beanName);
        if (beanType != null && beanType.isAssignableFrom(Listener.class)) {
            beanDef.setScope(SCOPE_SINGLETON);
        }
    });
}
 
Example #17
Source File: ModManager.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
/**
 * unregisters the Modifier from the list
 *
 * @param mod the modifier instance
 */
public void unregister(Modifier mod) {
	if (mod == null) return;
	allMods.remove(mod);
	mods.remove(mod);
	incompatibilities.remove(mod);
	if (mod instanceof Listener) { //Disable Events
		HandlerList.unregisterAll((Listener) mod);
	}
	ChatWriter.logColor(LanguageManager.getString("ModManager.UnregisterModifier")
			.replace("%mod", mod.getColor() + mod.getName())
			.replace("%plugin", MineTinker.getPlugin().getName()));
}
 
Example #18
Source File: MobSelector.java    From CloudNet with Apache License 2.0 5 votes vote down vote up
public void init() {
    CloudAPI.getInstance().getNetworkHandlerProvider().registerHandler(new NetworkHandlerAdapterImplx());

    Bukkit.getScheduler().runTask(CloudServer.getInstance().getPlugin(), new Runnable() {
        @Override
        public void run() {
            NetworkUtils.addAll(servers,
                                MapWrapper.collectionCatcherHashMap(CloudAPI.getInstance().getServers(),
                                                                    new Catcher<String, ServerInfo>() {
                                                                        @Override
                                                                        public String doCatch(ServerInfo key) {
                                                                            return key.getServiceId().getServerId();
                                                                        }
                                                                    }));
            Bukkit.getScheduler().runTaskAsynchronously(CloudServer.getInstance().getPlugin(), new Runnable() {
                @Override
                public void run() {
                    for (ServerInfo serverInfo : servers.values()) {
                        handleUpdate(serverInfo);
                    }
                }
            });
        }
    });

    if (ReflectionUtil.forName("org.bukkit.entity.ArmorStand") != null) {
        try {
            Bukkit.getPluginManager().registerEvents((Listener) ReflectionUtil.forName(
                "de.dytanic.cloudnet.bridge.internal.listener.v18_112.ArmorStandListener").newInstance(),
                                                     CloudServer.getInstance().getPlugin());
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    Bukkit.getPluginManager().registerEvents(new ListenrImpl(), CloudServer.getInstance().getPlugin());
}
 
Example #19
Source File: EffectEngine.java    From GlobalWarming with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void unregisterEffect(ClimateEffectType effectType) {
    ClimateEffect effect = effects.get(effectType);
    if (effect instanceof Listener) {
        HandlerList.unregisterAll((ListenerClimateEffect) effect);
    }
    if (effect instanceof ScheduleClimateEffect) {
        Bukkit.getScheduler().cancelTask(((ScheduleClimateEffect) effect).getTaskId());
    }

    effectClasses.remove(effectType);
    effects.remove(effectType);
}
 
Example #20
Source File: ExtendedJavaPlugin.java    From helper with MIT License 5 votes vote down vote up
@Nonnull
@Override
public <T extends Listener> T registerListener(@Nonnull T listener) {
    Objects.requireNonNull(listener, "listener");
    getServer().getPluginManager().registerEvents(listener, this);
    return listener;
}
 
Example #21
Source File: HelperEventListener.java    From helper with MIT 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
Source File: JoinCountStat.java    From VoxelGamesLibv2 with MIT License 5 votes vote down vote up
@Nullable
@Override
public Listener getListener() {
    return new Listener() {
        @EventHandler
        public void onJoin(PlayerJoinEvent e) {
            getInstance(e.getPlayer().getUniqueId()).increment();
        }
    };
}
 
Example #23
Source File: BukkitDB.java    From db with MIT License 5 votes vote down vote up
public static Database createHikariDatabase(Plugin plugin, PooledDatabaseOptions options, boolean setGlobal) {
    HikariPooledDatabase db = new HikariPooledDatabase(options);
    if (setGlobal) {
        DB.setGlobalDatabase(db);
    }
    plugin.getServer().getPluginManager().registerEvents(new Listener() {
        @EventHandler(ignoreCancelled = true)
        public void onPluginDisable(PluginDisableEvent event) {
            if (event.getPlugin() == plugin) {
                db.close();
            }
        }
    }, plugin);
    return db;
}
 
Example #24
Source File: MatchImpl.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void unregisterEvents(Listener listener) {
    if(listeners.remove(listener)) {
        matchEventRegistry.stopListening(this, listener);
        guavaEventBus.unregister(listener);
    }
}
 
Example #25
Source File: MatchImpl.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void registerEventsAndRepeatables(Object thing) {
    registerRepeatable(thing);
    if(thing instanceof Listener) {
        registerEvents((Listener) thing);
    }
}
 
Example #26
Source File: BukkitFacetContext.java    From ProjectAres with GNU Affero General Public License v3.0 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 #27
Source File: MatchBinders.java    From ProjectAres with GNU Affero General Public License v3.0 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 #28
Source File: MatchBinders.java    From ProjectAres with GNU Affero General Public License v3.0 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 #29
Source File: MatchModuleManifest.java    From ProjectAres with GNU Affero General Public License v3.0 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 #30
Source File: RegisteredListener.java    From VoxelGamesLibv2 with MIT License 5 votes vote down vote up
@java.beans.ConstructorProperties({"listener", "game", "eventClass", "method", "filters"})
public RegisteredListener(Listener listener, Game game, Class<Event> eventClass, Method method, List<EventFilter> filters) {
    this.listener = listener;
    this.game = game;
    this.eventClass = eventClass;
    this.method = method;
    this.filters = filters;
}