How should I reach this (Setting things in custom file)

Discussion in 'Spigot Plugin Development' started by Kyllian, Apr 24, 2017.

  1. Hey,

    I tried this

    Code (Text):
    if (!commandsfile.exists()) {
                try {
                    commandsfile.createNewFile();
                    ArrayList<String> discord = new ArrayList<String>();
                    discord.add("&a&lJoin our discord now!");
                    discord.add("&a&lLink: blabla.com");
                    commands.addDefault("discord", discord);
                    saveData();
                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create customcommands.yml!");
                }
            }
    This gets called, creates a file, no exception.

    Only thing is, the file is empty. I'm wanting to put out like this:

    Code (Text):
    discord:
      - '&a&lJoin our discord now!'
      - '&a&lLink: blabla.com'
    My method should work, right?
     
  2. Mas

    Mas

    What is 'commands'?
    Show us your saveData() method also.
     
  3. Not the most efficient way, but here it is:

    Code (Text):
    package me.kyllian.system32.utils;

    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;

    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.plugin.Plugin;
    import org.bukkit.plugin.PluginDescriptionFile;

    public class FileCreator {

        private static FileCreator fc = new FileCreator();

        public static FileCreator getInstance() {
            return fc;
        }

        Plugin p;

        FileConfiguration config;
        File cfile;

        FileConfiguration data;
        File dfile;

        FileConfiguration spawn;
        File spawnfile;

        FileConfiguration warps;
        File warpfile;

        FileConfiguration jail;
        File jailfile;

        FileConfiguration commands;
        File commandsfile;

        public void setup(Plugin p) {
            if (!p.getDataFolder().exists()) {
                p.getDataFolder().mkdir();
            }
            dfile = new File(p.getDataFolder(), "data.yml");
            spawnfile = new File(p.getDataFolder(), "spawn.yml");
            warpfile = new File(p.getDataFolder(), "warps.yml");
            jailfile = new File(p.getDataFolder(), "jail.yml");
            commandsfile = new File(p.getDataFolder(), "customcommands.yml");

            if (!dfile.exists()) {
                try {
                    dfile.createNewFile();
                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create data.yml!");
                }
            }
            if (!spawnfile.exists()) {
                try {
                    spawnfile.createNewFile();
                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create spawn.yml!");
                }
            }
            if (!warpfile.exists()) {
                try {
                    warpfile.createNewFile();
                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create warps.yml!");
                }

            }
            if (!jailfile.exists()) {
                try {
                    jailfile.createNewFile();
                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create jail.yml!");
                }
            }
            if (!commandsfile.exists()) {
                try {
                    commandsfile.createNewFile();
                    ArrayList<String> discord = new ArrayList<String>();
                    discord.add("&a&lJoin our discord now!");
                    discord.add("&a&lLink: blabla.com");
                    commands.addDefault("discord", discord);
                    saveData();
                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create customcommands.yml!");
                }
            }

            data = YamlConfiguration.loadConfiguration(dfile);
            spawn = YamlConfiguration.loadConfiguration(spawnfile);
            warps = YamlConfiguration.loadConfiguration(warpfile);
            jail = YamlConfiguration.loadConfiguration(jailfile);
            commands = YamlConfiguration.loadConfiguration(commandsfile);
        }

        public FileConfiguration getData() {
            return data;
        }

        public FileConfiguration getSpawnData() {
            return spawn;
        }

        public FileConfiguration getWarpData() {
            return warps;
        }

        public FileConfiguration getJailData() {
            return jail;
        }

        public FileConfiguration getCustomCommands() {
            return commands;
        }

        public void saveData() {
            try {
                data.save(dfile);
            } catch (IOException e) {
                Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save data.yml!");
            }
            try {
                spawn.save(spawnfile);
            } catch (IOException e) {
                Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save spawn.yml!");
            }
            try {
                warps.save(warpfile);
            } catch (IOException e) {
                Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save warps.yml!");
            }

            try {
                jail.save(jailfile);
            } catch (IOException e) {
                Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save jail.yml!");
            }
            try {
                commands.save(commandsfile);
            } catch (IOException e) {
                Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save customcommands.yml!");
            }
        }

        public void reloadData() {
            data = YamlConfiguration.loadConfiguration(dfile);
            spawn = YamlConfiguration.loadConfiguration(spawnfile);
            warps = YamlConfiguration.loadConfiguration(warpfile);
            jail = YamlConfiguration.loadConfiguration(jailfile);
            commands = YamlConfiguration.loadConfiguration(commandsfile);
        }

        public PluginDescriptionFile getDesc() {
            return p.getDescription();
        }
    }
     
  4. Mas

    Mas

    Try commands.set(path, whatever) instead of addDefault
     
  5. Code (Text):
    if (!commandsfile.exists()) {
                try {
                    commandsfile.createNewFile();
                    ArrayList<String> discord = new ArrayList<String>();
                    discord.add("&a&lJoin our discord now!");
                    discord.add("&a&lLink: blabla.com");
                    commands.set("discord", discord);
                    saveData();
                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create customcommands.yml!");
                }
            }
    Still empty
     
  6. After debugging I see none of those gets called.

    Even when I do this:

    Code (Text):
    if (!commandsfile.exists()) {
                try {
                    commandsfile.createNewFile();

                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create customcommands.yml!");
                }
                ArrayList<String> discord = new ArrayList<String>();
                discord.add("&a&lJoin our discord now!");
                discord.add("&a&lLink: blabla.com");
                commands.set("discord", discord);
                Bukkit.broadcastMessage("testststststtstststtsts");
            }
    it doesnt work
     
  7. Hmm, nevermind. I see that this:

    Code (Text):
    if (!commandsfile.exists()) {
                try {
                    commandsfile.createNewFile();
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "LOOOOOOOOOOOOOOOOL");
                } catch (IOException e) {
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create customcommands.yml!");
                }
                ArrayList<String> discord = new ArrayList<String>();
                discord.add("&a&lJoin our discord now!");
                discord.add("&a&lLink: blabla.com");
                commands.set("discord", discord);
                Bukkit.broadcastMessage("testststststtstststtsts");
            }
    Doesnt put LOOOOOOOOOOOOOOL out, but the file gets created?
     
  8. then it already exists
     
  9. Honestly, the way you're handling your configs looks super-messy. Let me suggest you an another, probably less-messy way for achieving what you have.

    Here's a class I made for myself because I'm lazy because I didn't want to have ugly classes like that:
    Code (Java):
    package me.jetp250.spigotmc;

    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;

    import org.bukkit.configuration.file.YamlConfiguration;

    public abstract class SimpleConfiguration extends YamlConfiguration {

        private final File file;
        private final List<Listener> listeners;

        public SimpleConfiguration(File folder, String name, String header) {
            this(folder, name);
            options().header(header);
        }

        public SimpleConfiguration(File folder, String name) {
            this.listeners = new ArrayList<Listener>();
            this.file = new File(folder, name.endsWith(".yml") ? name : name + ".yml");
            if (!file.exists()) {
                save();
            }
            for (Listener listener : listeners)
                listener.onEvent(Event.INIT);
            reload();
        }

        public abstract void onLoad();

        public List<Listener> getListeners() {
            return listeners;
        }

        public boolean addListener(final Listener listener) {
            if (listener == null || this.getListeners().contains(listener))
                return false;
            listener.setConfig(this);
            return this.getListeners().add(listener);
        }

        public boolean load() {
            final Event event = Event.PREPARE_LOAD;
            for (Listener listener : listeners)
                listener.onEvent(event);
            if (event.isCancelled())
                return false;
            try {
                load(file);
                onLoad();
                for (Listener listener : listeners)
                    listener.onEvent(Event.LOAD);
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        public boolean save() {
            final Event event = Event.PREPARE_SAVE;
            for (Listener listener : listeners)
                listener.onEvent(event);
            if (event.isCancelled())
                return false;
            try {
                save(file);
                for (Listener listener : listeners)
                    listener.onEvent(Event.SAVE);
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        public boolean reload() {
            final Event event = Event.PREPARE_RELOAD;
            for (Listener listener : listeners)
                listener.onEvent(event);
            if (event.isCancelled())
                return false;
            try {
                load();
                onLoad();
                for (Listener listener : listeners)
                    listener.onEvent(Event.RELOAD);
                save();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        public File getFile() {
            return file;
        }

        public void remove(String path) {
            set(path, null);
        }

        @SuppressWarnings("unchecked")
        public <T> T getOrCreate(String path, T def) {
            if (contains(path))
                return (T) get(path);
            set(path, def);
            return def;
        }

        public static abstract class Listener {
           
            private SimpleConfiguration config;
           
            private void setConfig(final SimpleConfiguration config) {
                this.config = config;
            }
           
            public SimpleConfiguration getConfig() {
                return config;
            }
           
            protected abstract void onEvent(Event event);
        }

        public static enum Event {
            PREPARE_LOAD(true), LOAD(false), PREPARE_SAVE(true), SAVE(false), PREPARE_RELOAD(true), RELOAD(false), INIT(
                    false);

            private final boolean cancellable;

            private boolean cancelled;

            private Event(final boolean cancellable) {
                this.cancellable = cancellable;
                this.cancelled = false;
            }

            public boolean isCancellable() {
                return cancellable;
            }

            public boolean cancel() {
                if (!isCancellable())
                    return cancelled;
                this.cancelled = true;
                return true;
            }

            public boolean isCancelled() {
                return cancelled;
            }
        }
    }
     

    Now, with this, you can drastically shorten & clean up that config class.
    Here's an example of usage.
    Config class that extends SimpleConfiguration (which extends YamlConfiguration..)
    Code (Java):
    public class MyConfigClass extends SimpleConfiguration {
       
        private int timesLoaded;
        private String someRandomConfigField;
       
        public MyConfigClass(final File folder) {
            super(folder, "Config.yml", "Header");
        }
       
        @Override
        public void onLoad() {
            someRandomConfigField = this.getOrCreate("Yarr Said", "Mo' Barrels' o Wine");
            ++this.timesLoaded;
        }
       
        public String getSomeRandomConfigFieldPleaseNameYourMethodsProperly() {
            return someRandomConfigField;
        }
       
        public int uselessDataAboutTheTimesLoaded() {
            return timesLoaded;
        }
    }
    and an example usage in main class if that wasn't enough.
    Code (Java):
    public class YourMainClass extends JavaPlugin implements Listener {
       
        private MyConfigClass config;
        private String someFieldUpdatedInMainClassInstead;
       
        @Override
        public void onEnable() {
            this.getServer().getPluginManager().registerEvents(this, this);
            this.config = new MyConfigClass(this.getDataFolder());
           
            config.addListener(new SimpleConfiguration.Listener() {
                @Override
                protected void onEvent(Event event) {
                    if (event != Event.LOAD)
                        return;
                    someFieldUpdatedInMainClassInstead = this.getConfig().getOrCreate("Dynamite", "Flint and Steel");  
                }
            });
            // Reloading, because we added Listeners that need to be updated.
            config.reload();
        }
       
        @Override
        public MyConfigClass getConfig() {
            return config;
        }
    }
    This way, in every class that grabs stuff from configs, you can just add a SimpleConfiguration.Listener (and check for Event.LOAD or Event.RELOAD, LOAD is called in RELOAD though) and update the values in each class through those.

    You can also cancel events, just call event.cancel() like so:
    Code (Java):
    config.addListener(new SimpleConfiguration.Listener() {
        @Override
        protected void onEvent(Event event) {
            if (event == Event.PREPARE_LOAD && someCondition)
                event.cancel();
        }
    });
    But note, only 'PREPARE' events can be cancelled. You can check if it's cancellable with Event#isCancellable() if you really need to cancel something for whatever odd reason.

    Now, the getOrCreate() should also drastically reduce your lines, because it does literally what it says; if the requested value doesn't exist, it'll create it with the default value (second parameter) but otherwise it'll return the value from config.

    You still have access to reload(), and because I overrode the getConfig() in the main class, you can treat it like the Bukkit API if you'd really like to.

    Hope this helps, even though it doesn't really answer your question.