Search in sources :

Example 11 with Listener

use of org.bukkit.event.Listener in project BKCommonLib by bergerhealer.

the class OfflineWorldLoadedChangeListener method enable.

@Override
public void enable() throws Throwable {
    OfflineWorld.setLoadedWorldSupplier(this);
    // Listen for when worlds load and unload
    Bukkit.getPluginManager().registerEvents(new Listener() {

        @EventHandler(priority = EventPriority.LOWEST)
        public void onWorldInit(WorldInitEvent event) {
            OfflineWorld.BukkitWorldSupplier supplier = OfflineWorld.of(event.getWorld()).loadedWorldSupplier;
            if (supplier instanceof WorldSupplier) {
                ((WorldSupplier) supplier).update(event.getWorld());
            }
        }

        @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
        public void onWorldUnload(WorldUnloadEvent event) {
            OfflineWorld.BukkitWorldSupplier supplier = OfflineWorld.of(event.getWorld()).loadedWorldSupplier;
            if (supplier instanceof WorldSupplier) {
                ((WorldSupplier) supplier).update(null);
            }
            // Just in case!
            OfflineWorld.clearByBukkitWorldCache();
        }
    }, plugin);
    // Periodically clear the by-Bukkit world mapping to avoid memory leaks - just in case!
    // No need to run this on the main thread as it's all synchronized anyway
    // 10 minutes
    final int clearInterval = 1200;
    this.asyncClearTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, OfflineWorld::clearByBukkitWorldCache, clearInterval, clearInterval);
}
Also used : BukkitWorldSupplier(com.bergerkiller.bukkit.common.offline.OfflineWorld.BukkitWorldSupplier) WorldUnloadEvent(org.bukkit.event.world.WorldUnloadEvent) Listener(org.bukkit.event.Listener) WorldInitEvent(org.bukkit.event.world.WorldInitEvent) EventHandler(org.bukkit.event.EventHandler) BukkitWorldSupplier(com.bergerkiller.bukkit.common.offline.OfflineWorld.BukkitWorldSupplier)

Example 12 with Listener

use of org.bukkit.event.Listener in project BKCommonLib by bergerhealer.

the class EntityAddRemoveHandler_1_8_to_1_13_2 method onEnabled.

@Override
public void onEnabled(CommonPlugin plugin) {
    super.onEnabled(plugin);
    plugin.register(new Listener() {

        @EventHandler(priority = EventPriority.LOWEST)
        public void onChunkLoad(ChunkLoadEvent event) {
            notifyChunkEntitiesLoaded(event.getChunk());
        }

        @EventHandler(priority = EventPriority.LOWEST)
        public void onChunkUnload(ChunkUnloadEvent event) {
            notifyChunkEntitiesUnloaded(event.getChunk());
        }
    });
}
Also used : ChunkUnloadEvent(org.bukkit.event.world.ChunkUnloadEvent) ChunkLoadEvent(org.bukkit.event.world.ChunkLoadEvent) Listener(org.bukkit.event.Listener) EventHandler(org.bukkit.event.EventHandler)

Example 13 with Listener

use of org.bukkit.event.Listener in project SkinsRestorerX by DoNotSpamPls.

the class SkinsRestorer method onEnable.

public void onEnable() {
    ConsoleCommandSender console = getServer().getConsoleSender();
    @SuppressWarnings("unused") MetricsLite metrics = new MetricsLite(this);
    SpigetUpdate updater = new SpigetUpdate(this, 2124);
    updater.setVersionComparator(VersionComparator.EQUAL);
    updater.setVersionComparator(VersionComparator.SEM_VER);
    instance = this;
    factory = new UniversalSkinFactory();
    Config.load(getResource("config.yml"));
    Locale.load();
    console.sendMessage("§e[§2SkinsRestorer§e] §aDetected Minecraft §e" + ReflectionUtil.serverVersion + "§a, using §e" + factory.getClass().getSimpleName() + "§a.");
    // Detect ChangeSkin
    if (getServer().getPluginManager().getPlugin("ChangeSkin") != null) {
        console.sendMessage("§e[§2SkinsRestorer§e] §cWe have detected ChangeSkin on your server, disabling SkinsRestorer.");
        Bukkit.getPluginManager().disablePlugin(this);
    }
    // Bungeecord stuff
    try {
        bungeeEnabled = getServer().spigot().getConfig().getBoolean("settings.bungeecord");
    } catch (Exception e) {
        bungeeEnabled = false;
    }
    if (bungeeEnabled) {
        Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
        Bukkit.getMessenger().registerIncomingPluginChannel(this, "SkinsRestorer", (channel, player, message) -> {
            if (!channel.equals("SkinsRestorer"))
                return;
            Bukkit.getScheduler().runTaskAsynchronously(getInstance(), () -> {
                DataInputStream in = new DataInputStream(new ByteArrayInputStream(message));
                try {
                    String subchannel = in.readUTF();
                    if (subchannel.equalsIgnoreCase("SkinUpdate")) {
                        try {
                            factory.applySkin(player, SkinStorage.createProperty(in.readUTF(), in.readUTF(), in.readUTF()));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        factory.updateSkin(player);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        });
        if (Config.UPDATER_ENABLED) {
            updater.checkForUpdate(new UpdateCallback() {

                @Override
                public void updateAvailable(String newVersion, String downloadUrl, boolean hasDirectDownload) {
                    if (hasDirectDownload) {
                        console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a    +===============+");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a    | SkinsRestorer |");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a    |---------------|");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a    |  §eBungee Mode§a  |");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a    +===============+");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                        console.sendMessage("§e[§2SkinsRestorer§e] §b    Current version: §c" + getVersion());
                        console.sendMessage("§e[§2SkinsRestorer§e]     A new version is available! Downloading it now...");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                        if (updater.downloadUpdate()) {
                            console.sendMessage("§e[§2SkinsRestorer§e] Update downloaded successfully, it will be applied on the next restart.");
                        } else {
                            // Update failed
                            console.sendMessage("§e[§2SkinsRestorer§e] §cCould not download the update, reason: " + updater.getFailReason());
                        }
                    }
                }

                @Override
                public void upToDate() {
                    console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    +===============+");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    | SkinsRestorer |");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    |---------------|");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    |  §eBungee Mode§a  |");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    +===============+");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                    console.sendMessage("§e[§2SkinsRestorer§e] §b    Current version: §a" + getVersion());
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    This is the latest version!");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                }
            });
        }
        return;
    }
    // Initialise MySQL
    if (Config.USE_MYSQL)
        SkinStorage.init(mysql = new MySQL(Config.MYSQL_HOST, Config.MYSQL_PORT, Config.MYSQL_DATABASE, Config.MYSQL_USERNAME, Config.MYSQL_PASSWORD));
    else
        SkinStorage.init(getDataFolder());
    Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new CooldownStorage(), 0, 20);
    // Commands
    getCommand("skinsrestorer").setExecutor(new SrCommand());
    getCommand("skin").setExecutor(new SkinCommand());
    getCommand("skins").setExecutor(new GUICommand());
    Bukkit.getPluginManager().registerEvents(new SkinsGUI(), this);
    Bukkit.getPluginManager().registerEvents(new Listener() {

        // LoginEvent happens on attemptLogin so its the best place to set the skin
        @EventHandler
        public void onLogin(PlayerJoinEvent e) {
            Bukkit.getScheduler().runTaskAsynchronously(SkinsRestorer.getInstance(), () -> {
                try {
                    if (Config.DISABLE_ONJOIN_SKINS) {
                        // shouldn't it just skip it if it's true?
                        return;
                    }
                    if (Config.DEFAULT_SKINS_ENABLED)
                        if (SkinStorage.getPlayerSkin(e.getPlayer().getName()) == null) {
                            List<String> skins = Config.DEFAULT_SKINS;
                            int randomNum = (int) (Math.random() * skins.size());
                            factory.applySkin(e.getPlayer(), SkinStorage.getOrCreateSkinForPlayer(skins.get(randomNum)));
                            return;
                        }
                    factory.applySkin(e.getPlayer(), SkinStorage.getOrCreateSkinForPlayer(e.getPlayer().getName()));
                } catch (SkinRequestException ex) {
                    ex.printStackTrace();
                }
            });
        }
    }, this);
    Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
        if (Config.UPDATER_ENABLED) {
            updater.checkForUpdate(new UpdateCallback() {

                @Override
                public void updateAvailable(String newVersion, String downloadUrl, boolean hasDirectDownload) {
                    if (hasDirectDownload) {
                        console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a    +===============+");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a    | SkinsRestorer |");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a    +===============+");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                        console.sendMessage("§e[§2SkinsRestorer§e] §b    Current version: §c" + getVersion());
                        console.sendMessage("§e[§2SkinsRestorer§e]     A new version is available! Downloading it now...");
                        console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                        if (updater.downloadUpdate()) {
                            console.sendMessage("§e[§2SkinsRestorer§e] Update downloaded successfully, it will be applied on the next restart.");
                        } else {
                            // Update failed
                            console.sendMessage("§e[§2SkinsRestorer§e] §cCould not download the update, reason: " + updater.getFailReason());
                        }
                    }
                }

                @Override
                public void upToDate() {
                    console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    +===============+");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    | SkinsRestorer |");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    +===============+");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                    console.sendMessage("§e[§2SkinsRestorer§e] §b    Current version: §a" + getVersion());
                    console.sendMessage("§e[§2SkinsRestorer§e] §a    This is the latest version!");
                    console.sendMessage("§e[§2SkinsRestorer§e] §a----------------------------------------------");
                }
            });
        }
        if (Config.DEFAULT_SKINS_ENABLED)
            for (String skin : Config.DEFAULT_SKINS) try {
                SkinStorage.setSkinData(skin, MojangAPI.getSkinProperty(MojangAPI.getUUID(skin)));
            } catch (SkinRequestException e) {
                if (SkinStorage.getSkinData(skin) == null)
                    console.sendMessage("§e[§2SkinsRestorer§e] §cDefault Skin '" + skin + "' request error: " + e.getReason());
            }
    });
}
Also used : Listener(org.bukkit.event.Listener) EventHandler(org.bukkit.event.EventHandler) SkinRequestException(skinsrestorer.shared.utils.MojangAPI.SkinRequestException) MetricsLite(org.bstats.bukkit.MetricsLite) MySQL(skinsrestorer.shared.utils.MySQL) SrCommand(skinsrestorer.bukkit.commands.SrCommand) GUICommand(skinsrestorer.bukkit.commands.GUICommand) SkinCommand(skinsrestorer.bukkit.commands.SkinCommand) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) ConsoleCommandSender(org.bukkit.command.ConsoleCommandSender) SpigetUpdate(org.inventivetalent.update.spiget.SpigetUpdate) SkinRequestException(skinsrestorer.shared.utils.MojangAPI.SkinRequestException) IOException(java.io.IOException) UpdateCallback(org.inventivetalent.update.spiget.UpdateCallback) CooldownStorage(skinsrestorer.shared.storage.CooldownStorage) PlayerJoinEvent(org.bukkit.event.player.PlayerJoinEvent) ByteArrayInputStream(java.io.ByteArrayInputStream) UniversalSkinFactory(skinsrestorer.bukkit.skinfactory.UniversalSkinFactory)

Example 14 with Listener

use of org.bukkit.event.Listener in project CommandHelper by EngineHub.

the class BukkitDirtyRegisteredListener method Generate.

public static BukkitDirtyRegisteredListener Generate(RegisteredListener real) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    if (real instanceof BukkitDirtyRegisteredListener) {
        return (BukkitDirtyRegisteredListener) real;
    }
    Field rListener = real.getClass().getDeclaredField("listener");
    rListener.setAccessible(true);
    Listener nListener = (Listener) rListener.get(real);
    Field rPriority = real.getClass().getDeclaredField("priority");
    rPriority.setAccessible(true);
    EventPriority nPriority = (EventPriority) rPriority.get(real);
    Field rPlugin = real.getClass().getDeclaredField("plugin");
    rPlugin.setAccessible(true);
    Plugin nPlugin = (Plugin) rPlugin.get(real);
    Field rExecutor = real.getClass().getDeclaredField("executor");
    rExecutor.setAccessible(true);
    EventExecutor nExecutor = (EventExecutor) rExecutor.get(real);
    Field rIgnoreCancelled = real.getClass().getDeclaredField("ignoreCancelled");
    rIgnoreCancelled.setAccessible(true);
    boolean nIgnoreCancelled = rIgnoreCancelled.getBoolean(real);
    return new BukkitDirtyRegisteredListener(nListener, nExecutor, nPriority, nPlugin, nIgnoreCancelled);
}
Also used : Field(java.lang.reflect.Field) RegisteredListener(org.bukkit.plugin.RegisteredListener) Listener(org.bukkit.event.Listener) EventExecutor(org.bukkit.plugin.EventExecutor) EventPriority(org.bukkit.event.EventPriority) Plugin(org.bukkit.plugin.Plugin)

Example 15 with Listener

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

Aggregations

Listener (org.bukkit.event.Listener)26 EventHandler (org.bukkit.event.EventHandler)10 Event (org.bukkit.event.Event)8 EventExecutor (org.bukkit.plugin.EventExecutor)7 RegisteredListener (org.bukkit.plugin.RegisteredListener)7 Player (org.bukkit.entity.Player)6 EventException (org.bukkit.event.EventException)6 EventPriority (org.bukkit.event.EventPriority)6 PluginManager (org.bukkit.plugin.PluginManager)6 PlayerJoinEvent (org.bukkit.event.player.PlayerJoinEvent)5 Method (java.lang.reflect.Method)4 HandlerList (org.bukkit.event.HandlerList)4 Field (java.lang.reflect.Field)2 ArrayList (java.util.ArrayList)2 PlayerPortalEvent (org.bukkit.event.player.PlayerPortalEvent)2 AuthorNagException (org.bukkit.plugin.AuthorNagException)2 Plugin (org.bukkit.plugin.Plugin)2 PacketReceiveEvent (com.bergerkiller.bukkit.common.events.PacketReceiveEvent)1 PacketSendEvent (com.bergerkiller.bukkit.common.events.PacketSendEvent)1 BukkitWorldSupplier (com.bergerkiller.bukkit.common.offline.OfflineWorld.BukkitWorldSupplier)1