1.12.2 Weird Problem

Discussion in 'Spigot Plugin Development' started by MMC2019, Jan 27, 2020.

  1. Hi, I encounter a weird problem

    I have a class named "AGMConfig"
    I used it in several plugins and it worked without any issue

    But now when I do
    Code (Text):
    YML = new AGMConfig("database","database",databaseFolder,this);
    Events that were registering now don't work.

    Events works
    Code (Java):
    package me.ashenguard.agmor;

    import me.ashenguard.agmor.classes.AGMConfig;
    import me.ashenguard.agmor.classes.AGMMessenger;
    import me.ashenguard.agmor.database.RespawnerDatabase;
    import me.ashenguard.agmor.listeners.BlockListener;
    import org.bukkit.Bukkit;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.command.TabCompleter;
    import org.bukkit.plugin.java.JavaPlugin;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    public final class AGMOR extends JavaPlugin implements TabCompleter, CommandExecutor {

        public static AGMConfig config;
        public static boolean useMySQL;
        private static Connection SQL;
        private static AGMConfig YML;
        private File mainFolder;
        private File databaseFolder;
        private static JavaPlugin instance;
        private static BlockListener blockListener;

        public static JavaPlugin getInstance() {
            return instance;
        }

        @Override
        public void onEnable() {
            // ---- Set Instance ---- //
            instance = this;
            // ---- Load Configs ---- //
            setFolders();
            config = new AGMConfig("config",null, mainFolder, this);
            AGMMessenger.Info("Config loaded");
            // ---- Debuggers check ---- //
            AGMMessenger.Debug(0,"\"§6On Block Break§r\" debugger activated");
            AGMMessenger.Debug(2,"\"§6On Block Place§r\" debugger activated");
            AGMMessenger.Debug(1,"\"§6Respawner§r\" debugger activated");
            AGMMessenger.Debug(3,"\"§6MySQL Database§r\" debugger activated");
            AGMMessenger.Debug(4,"\"§6YML Database§r\" debugger activated");

            // ---- Database Activation ---- //
            useMySQL = config.get().getBoolean("database.useMySQL",false);
            if (useMySQL) {
                AGMMessenger.Debug(3,"\"§6MySQL Database§r\" was set §cEnabled§, Trying to connect ...");
                if (SQLSetup()) {
                    AGMMessenger.Debug(3,"\"§6MySQL Database§r\" activated");
                } else {
                    AGMMessenger.Debug(3,"\"§6MySQL Database§r\" activation failed");
                    return;
                }
            } else {
                AGMMessenger.Debug(3,"\"§6MySQL Database§r\" was set §cDisabled§r");
                AGMMessenger.Debug(4,"\"§6YML Database§r\" activated since MySQL wasn't enabled");
                // YML = new AGMConfig("database","database",databaseFolder,this);
            }
            // ---- Register Event ---- //
            blockListener = new BlockListener();
            // ---- Define command ---- //
            getCommand("AGMOR").setExecutor(this);
            getCommand("AGMOR").setTabCompleter(this);
            AGMMessenger.Info("Command activated");
        }

        private void setFolders() {
            mainFolder = this.getDataFolder();
            if(!mainFolder.exists())
                mainFolder.mkdirs();

            databaseFolder = new File(mainFolder, "database");
            if(!databaseFolder.exists())
                databaseFolder.mkdirs();
        }

        // ---- SQL ---- //
        private boolean SQLSetup() {
            String host = config.get().getString("database.MySQL.host");
            String username = config.get().getString("database.MySQL.username");
            String password = config.get().getString("database.MySQL.password");
            String database = config.get().getString("database.MySQL.database");
            int port = config.get().getInt("database.MySQL.port");
            boolean ssl = config.get().getBoolean("database.MySQL.useSSL");
            try {
                synchronized (this) {
                    if (getSQL() != null && !getSQL().isClosed())
                        return true;
                    Class.forName("com.mysql.jdbc.Driver");
                    setSQL(DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true&useSSL=" + ssl, username, password));
                }
            } catch (SQLException | ClassNotFoundException e) {
                AGMMessenger.Warning("MySQL Connection Failed");
                File file = new File(mainFolder,"MYSQL.AGMWarn");
                try {
                    PrintStream ps = new PrintStream(file);
                    e.printStackTrace(ps);
                    ps.close();
                    AGMMessenger.Warning("Check AGMOR plugin folder for an AGMWarn");
                } catch (FileNotFoundException ignored) {}
                Bukkit.getServer().getPluginManager().disablePlugin(this);
                return false;
            }
            return true;
        }
        public static Connection getSQL() {
            return SQL;
        }
        private static void setSQL(Connection SQL) {
            AGMOR.SQL = SQL;
        }

        // ---- Disable ---- //
        @Override
        public void onDisable() {
            if (RespawnerDatabase.getRespawnersCount() > 0) {
                int count = RespawnerDatabase.getRespawnersCount();
                AGMMessenger.Warning("Forcing §c" + count + "§r Respawner(s)");
                RespawnerDatabase.forceRespawners();
            }
        }

        // ---- Command ---- //
        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
            if (!command.getName().equalsIgnoreCase("agmor")) return true;
            if (args.length == 1 && args[0].equalsIgnoreCase("info")) {
                //TODO
                return true;
            }
            if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
                //TODO
                return true;
            }
            return true;
        }

        @Override
        public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
            List<String> tab = new ArrayList<>();
            int arg = 0;
            if (args.length == 1) {
                tab.add("info");
                tab.add("reload");
                arg = 0;
            }

            for (int i = 0; i < tab.size(); i++) {
                if (!tab.get(i).toLowerCase().startsWith(args[arg].toLowerCase())) {
                    tab.remove(i);
                    i--;
                }
            }
            Collections.sort(tab);
            return tab;
        }
    }
     

    Events don't work
    Code (Java):
    package me.ashenguard.agmor;

    import me.ashenguard.agmor.classes.AGMConfig;
    import me.ashenguard.agmor.classes.AGMMessenger;
    import me.ashenguard.agmor.database.RespawnerDatabase;
    import me.ashenguard.agmor.listeners.BlockListener;
    import org.bukkit.Bukkit;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.command.TabCompleter;
    import org.bukkit.plugin.java.JavaPlugin;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    public final class AGMOR extends JavaPlugin implements TabCompleter, CommandExecutor {

        public static AGMConfig config;
        public static boolean useMySQL;
        private static Connection SQL;
        private static AGMConfig YML;
        private File mainFolder;
        private File databaseFolder;
        private static JavaPlugin instance;
        private static BlockListener blockListener;

        public static JavaPlugin getInstance() {
            return instance;
        }

        @Override
        public void onEnable() {
            // ---- Set Instance ---- //
            instance = this;
            // ---- Load Configs ---- //
            setFolders();
            config = new AGMConfig("config",null, mainFolder, this);
            AGMMessenger.Info("Config loaded");
            // ---- Debuggers check ---- //
            AGMMessenger.Debug(0,"\"§6On Block Break§r\" debugger activated");
            AGMMessenger.Debug(2,"\"§6On Block Place§r\" debugger activated");
            AGMMessenger.Debug(1,"\"§6Respawner§r\" debugger activated");
            AGMMessenger.Debug(3,"\"§6MySQL Database§r\" debugger activated");
            AGMMessenger.Debug(4,"\"§6YML Database§r\" debugger activated");

            // ---- Database Activation ---- //
            useMySQL = config.get().getBoolean("database.useMySQL",false);
            if (useMySQL) {
                AGMMessenger.Debug(3,"\"§6MySQL Database§r\" was set §cEnabled§, Trying to connect ...");
                if (SQLSetup()) {
                    AGMMessenger.Debug(3,"\"§6MySQL Database§r\" activated");
                } else {
                    AGMMessenger.Debug(3,"\"§6MySQL Database§r\" activation failed");
                    return;
                }
            } else {
                AGMMessenger.Debug(3,"\"§6MySQL Database§r\" was set §cDisabled§r");
                AGMMessenger.Debug(4,"\"§6YML Database§r\" activated since MySQL wasn't enabled");
                YML = new AGMConfig("database","database",databaseFolder,this);
            }
            // ---- Register Event ---- //
            blockListener = new BlockListener();
            // ---- Define command ---- //
            getCommand("AGMOR").setExecutor(this);
            getCommand("AGMOR").setTabCompleter(this);
            AGMMessenger.Info("Command activated");
        }

        private void setFolders() {
            mainFolder = this.getDataFolder();
            if(!mainFolder.exists())
                mainFolder.mkdirs();

            databaseFolder = new File(mainFolder, "database");
            if(!databaseFolder.exists())
                databaseFolder.mkdirs();
        }

        // ---- SQL ---- //
        private boolean SQLSetup() {
            String host = config.get().getString("database.MySQL.host");
            String username = config.get().getString("database.MySQL.username");
            String password = config.get().getString("database.MySQL.password");
            String database = config.get().getString("database.MySQL.database");
            int port = config.get().getInt("database.MySQL.port");
            boolean ssl = config.get().getBoolean("database.MySQL.useSSL");
            try {
                synchronized (this) {
                    if (getSQL() != null && !getSQL().isClosed())
                        return true;
                    Class.forName("com.mysql.jdbc.Driver");
                    setSQL(DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true&useSSL=" + ssl, username, password));
                }
            } catch (SQLException | ClassNotFoundException e) {
                AGMMessenger.Warning("MySQL Connection Failed");
                File file = new File(mainFolder,"MYSQL.AGMWarn");
                try {
                    PrintStream ps = new PrintStream(file);
                    e.printStackTrace(ps);
                    ps.close();
                    AGMMessenger.Warning("Check AGMOR plugin folder for an AGMWarn");
                } catch (FileNotFoundException ignored) {}
                Bukkit.getServer().getPluginManager().disablePlugin(this);
                return false;
            }
            return true;
        }
        public static Connection getSQL() {
            return SQL;
        }
        private static void setSQL(Connection SQL) {
            AGMOR.SQL = SQL;
        }

        // ---- Disable ---- //
        @Override
        public void onDisable() {
            if (RespawnerDatabase.getRespawnersCount() > 0) {
                int count = RespawnerDatabase.getRespawnersCount();
                AGMMessenger.Warning("Forcing §c" + count + "§r Respawner(s)");
                RespawnerDatabase.forceRespawners();
            }
        }

        // ---- Command ---- //
        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
            if (!command.getName().equalsIgnoreCase("agmor")) return true;
            if (args.length == 1 && args[0].equalsIgnoreCase("info")) {
                //TODO
                return true;
            }
            if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
                //TODO
                return true;
            }
            return true;
        }

        @Override
        public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
            List<String> tab = new ArrayList<>();
            int arg = 0;
            if (args.length == 1) {
                tab.add("info");
                tab.add("reload");
                arg = 0;
            }

            for (int i = 0; i < tab.size(); i++) {
                if (!tab.get(i).toLowerCase().startsWith(args[arg].toLowerCase())) {
                    tab.remove(i);
                    i--;
                }
            }
            Collections.sort(tab);
            return tab;
        }
    }
     

    Code (Java):
    package me.ashenguard.agmor.classes;

    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.plugin.Plugin;

    import java.io.File;
    import java.io.IOException;

    public class AGMConfig {

        private static File file;
        private static FileConfiguration configFile;

        public AGMConfig(String config, String resource, File folder, Plugin plugin) {
            if (!config.endsWith(".yml")) config += ".yml";
            boolean fileCreated = false;
            file = new File(folder,config);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                    fileCreated = true;
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
            configFile = YamlConfiguration.loadConfiguration(file);

            if (fileCreated && resource == null) plugin.saveResource(config, true);
            if (fileCreated && resource != null)
                plugin.saveResource(resource + "/" + config, true);
            reload();
        }

        public AGMConfig(String config, String resource, File folder, Plugin plugin, boolean premium) {
            if (!config.endsWith(".yml")) config += ".yml";
            boolean fileCreated = false;
            file = new File(folder,config);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                    fileCreated = true;
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
            configFile = YamlConfiguration.loadConfiguration(file);

            if ((fileCreated || !premium) && resource == null) plugin.saveResource(config, true);
            if ((fileCreated || !premium) && resource != null)
                plugin.saveResource(resource + "/" + config, true);
            reload();
        }

        public FileConfiguration get() {
            return configFile;
        }

        private void reload() {
            try {
                configFile.load(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void save() {
            try {
                configFile.save(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
     

    Code (Java):
    package me.ashenguard.agmor.listeners;

    import me.ashenguard.agmor.AGMOR;
    import me.ashenguard.agmor.classes.AGMMessenger;
    import me.ashenguard.agmor.classes.Respawner;
    import me.ashenguard.agmor.database.RespawnerDatabase;
    import org.bukkit.*;
    import org.bukkit.block.Block;
    import org.bukkit.configuration.ConfigurationSection;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.BlockBreakEvent;
    import org.bukkit.event.block.BlockPlaceEvent;
    import org.bukkit.scheduler.BukkitScheduler;

    import java.util.List;
    import java.util.Random;
    import java.util.Set;

    public class BlockListener implements Listener {

        public BlockListener() {
            Bukkit.getPluginManager().registerEvents(this, AGMOR.getInstance());
            AGMMessenger.Info("Events registered");
        }

        @EventHandler(priority = EventPriority.HIGH)
        public void onBlockBreak(BlockBreakEvent event) {
            // ---- Check if event is not cancelled ---- //
            AGMMessenger.Debug(0,"\"§6On Block Break§r\" activated");
            if (event.isCancelled()) {
                AGMMessenger.Debug(0,"\"§6On Block Break§r\" disabled due: Event was §cCancelled§r");
                return;
            }

            // Other Stuff that works for sure
        }

        @EventHandler(priority = EventPriority.HIGH)
        public void OnBlockPlace(BlockPlaceEvent event) {
            // ---- Check if event is not cancelled ---- //
            AGMMessenger.Debug(2,"\"§6On Block Place§r\" activated");
            if (event.isCancelled()) {
                AGMMessenger.Debug(2,"\"§6On Block Place§r\" disabled due: Event was §cCancelled§r");
                return;
            }

            // Other Stuff that works for sure
        }
    }
     
     
  2. Any errors in the console
     
  3. No error, Everything works fine except events.
     
  4. upload_2020-1-27_16-24-33.png

    Literally that's the only difference, which makes it really strange that it doesn't work.
    The code in AGMConfig seems pretty normal. Have you tried printing something inside BlockListener's constructor or inside an EventHandler

    //Edit: I just saw, you ware indeed logging and debugging
    Is the constructor called?
     
  5. You can see BlockListener, The first line of each event handler is a debug message.
    When events work it will be printed, But when I set the YML variable, That line won't execute.
     
  6. Btw instead of
    Code (Java):

    @EventHandler(priority = EventPriority.HIGH)
        public void onBlockBreak(BlockBreakEvent event) {
            // ---- Check if event is not cancelled ---- //
     
    you can just do
    Code (Java):

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
        public void onBlockBreak(BlockBreakEvent event) {
     
    That's away from the main point.
     
    #6 Ablax, Jan 27, 2020
    Last edited: Jan 27, 2020
    • Informative Informative x 1
  7. Thanks for TIP, I'll keep it in mind (y)
     
  8. Unfortunately, I can't figure out where your issue is coming from.
    You may start debugging in every method in AGMConfig and in some lines in AGMConfig also in the constructor and see where the pipe gets broken.
     
  9. Maybe you optimized it using progusrd or something that removed the event handler methods? Happened to me once.
     
  10. I debug AGMConfig, There was no problem

    I don't think so, In the main file I used AGMConfig once for the config variable, The issue happens when I create the second one, Also AGMConfig has nothing with events, It only make config files
     
  11. @Ablax , @the3rdnumber

    I put this code on the main plugin so when I execute /agmor command it would show me listeners in console

    Code (Java):
    ArrayList<RegisteredListener> listeners = getRegisteredListeners(this);
            for (RegisteredListener listener:listeners) {
                AGMMessenger.Info(listener.getListener().toString());
            }
    Listeners are not working but I get this when executing the command
    upload_2020-1-27_20-24-8.png