Bukkit's Yaml Configuration Tutorial

Discussion in 'Resources' started by DomovoiButler, Oct 23, 2011.

?

Is my first Guide good?

  1. yes

    69.5%
  2. no

    6.6%
  3. meh, needs improvement

    24.0%
Thread Status:
Not open for further replies.
  1. Offline

    Neodork

    Your yml doesn't shows a list.

    Look here for information about lists.
     
  2. Offline

    the_merciless

    How can u stop it overwriting your comments when saving?
     
  3. Offline

    Sagacious_Zed Bukkit Docs

    With the exception of the header comment, you can't.
     
  4. Offline

    the_merciless

    I'm quite sure I have seen 100 plugins that have managed this. Take towny for example. Comment, setting,Comment, setting,Comment, setting. If its not possible how have they managed it?
     
  5. Offline

    kumpelblase2

    Using their own/another yaml parser? Or maybe only for the default setting.
     
  6. Offline

    Sagacious_Zed Bukkit Docs

    Yes they would need their own parser, or heavily modify the underlying library, but it is not a supported use case out of the box for bukkit's handling.
     
  7. Offline

    the_merciless

    I understand now thx.
     
  8. Offline

    uvbeenzaned

    How come my config file gets written over every time? I set the value to false and then boom, right back to true.
     
  9. Offline

    Sagacious_Zed Bukkit Docs

    This could be for a multitude of reasons depending on what you have written.
    Some common ones normally involves using the set method unsafely inside onEnable.
    Also be aware that onDisable is called during a /reload on the server, which means it will save what is in memory to the disk, if any changes were made, they will be over written.
     
  10. Offline

    uvbeenzaned

    Here is my whole main class. Could you tell what my problem is?

    Code:
    public final MyListener ml = new MyListener();
        Logger log;
        File configFile;
        File usersFile;
        FileConfiguration config;
        FileConfiguration users;
        //public NETFireConfig nfc = new NETFireConfig();
     
        public void onEnable()
        {
            log = this.getLogger();
            PluginManager pm = getServer().getPluginManager();
            pm.registerEvents(this.ml, this);
            configFile = new File(getDataFolder(), "config.yml");
            usersFile = new File(getDataFolder(), "users.yml");
            try {
                firstRun();
            } catch (Exception e) {
                e.printStackTrace();
            }
            config = new YamlConfiguration();
            users = new YamlConfiguration();
            loadYamls();
            try {
                MetricsLite metrics = new MetricsLite(this);
                metrics.start();
            } catch (IOException e) {
                // Failed to submit the stats :-(
            }
        }
     
        public void onDisable()
        {
            saveYamls();
        }
     
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
        {
            if(cmd.getName().equalsIgnoreCase("testcfg"))
            {
                if(config.getBoolean("enabled"))
                {
                    sender.sendMessage("It's true!");
                }
                else
                {
                    sender.sendMessage("It's false!");
                }
                return true;
            }
            return false;
        }
     
     
        private void firstRun() throws Exception {
            if(!configFile.exists()){
                configFile.getParentFile().mkdirs();
                copy(getResource("config.yml"), configFile);
            }
            if(!usersFile.exists()){
                usersFile.getParentFile().mkdirs();
                copy(getResource("users.yml"), usersFile);
            }
        }
     
        private void copy(InputStream in, File file) {
            try {
                OutputStream out = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int len;
                while((len=in.read(buf))>0){
                    out.write(buf,0,len);
                }
                out.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        public void saveYamls() {
            try {
                config.save(configFile);
                users.save(usersFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void loadYamls() {
            try {
                config.load(configFile);
                users.load(usersFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
  11. Offline

    Steffion

    Great tut, still xD! Thanks!
     
  12. Offline

    Ch4t4r

    Somebody could help me? I got a seperate class PlayerJoinListener and decleard the yamlfiles as public in the main class. In the seperate class I use this:
    Code:
                this.plugin.users.addDefault(name + ".points", 10);
                this.plugin.users.addDefault(name + ".rang", "member");
                this.plugin.users.addDefault(name + ".coins", 2);
                this.plugin.users.addDefault(name + ".kills", 0);
                this.plugin.users.addDefault(name + ".deaths", 0);
                this.plugin.users.addDefault(name + ".clan", "null");
                this.plugin.users.addDefault(name + ".clanowner", false);
                this.plugin.users.addDefault(name + ".clanmod", false);
                this.plugin.users.addDefault(name + ".number", this.plugin.config.getInt("playernumber") + 1);
    this.plugin.saveYamls();
    But somehow if I reload (The files are saved in onDisable()) the changes I just done won't show up in the users.yml file. Full main class:

    Code:
    package me.ch4t4r.ultimaclans;
     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
     
    import me.ch4t4r.ultimaclans.listeners.EntityDamageListener;
    import me.ch4t4r.ultimaclans.listeners.PlayerDeathEventListener;
    import me.ch4t4r.ultimaclans.listeners.PlayerJoinListener;
     
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.Listener;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class main extends JavaPlugin implements Listener {
     
        public FileConfiguration config;
        public FileConfiguration clans;
        public FileConfiguration users;
        public FileConfiguration template;
        public File configFile;
        public File clansFile;
        public File usersFile;
        public HashMap<String,cspieler> spieler = new HashMap<String,cspieler>();
     
        @Override
        public void onEnable() {
     
            configFile = new File(getDataFolder(), "config.yml");
            clansFile = new File(getDataFolder(), "clans.yml");
            usersFile = new File(getDataFolder(), "users.yml");
            try {
                firstRun();
            } catch (Exception e) {
                e.printStackTrace();
            }
            config = new YamlConfiguration();
            clans = new YamlConfiguration();
            users = new YamlConfiguration();
            loadYamls();
            String[] players = this.users.getString("players").split(",");
            for(int i = 0;i < players.length;i++){
                int points = users.getInt(players[i] + ".points");
                int coins = users.getInt(players[i] + ".coins");
                String clan = users.getString(players[i] + ".clan");
                spieler.put(players[i], new cspieler(this,players[i],clan,points,coins));
            }
                getServer().getPluginManager().registerEvents(new EntityDamageListener(this), this);
                getServer().getPluginManager().registerEvents(new PlayerJoinListener(this), this);
                getServer().getPluginManager().registerEvents(new PlayerDeathEventListener(this), this);
                getCommand("clan").setExecutor(new commandlistener(this));
        }
        public void saveYamls() {
            try {
                config.save(configFile);
                clans.save(clansFile);
                users.save(usersFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void loadYamls() {
            try {
                config.load(configFile);
                clans.load(clansFile);
                users.load(usersFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onDisable() {
            System.out.println("UltimaClans deaktiviert!");
            saveYamls();
        }
        private void firstRun() throws Exception {
            if(!configFile.exists()){
                configFile.getParentFile().mkdirs();
                copy(getResource("config.yml"), configFile);
            }
            if(!clansFile.exists()){
                clansFile.getParentFile().mkdirs();
                copy(getResource("clans.yml"), clansFile);
            }
            if(!usersFile.exists()){
                usersFile.getParentFile().mkdirs();
                copy(getResource("users.yml"), usersFile);
            }
        }
        private void copy(InputStream in, File file) {
            try {
                OutputStream out = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int len;
                while((len=in.read(buf))>0){
                    out.write(buf,0,len);
                }
                out.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    full PlayerJoinListener class:

    Code:
    package me.ch4t4r.ultimaclans.listeners;
     
    import java.io.IOException;
     
    import me.ch4t4r.ultimaclans.cspieler;
    import me.ch4t4r.ultimaclans.main;
     
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class PlayerJoinListener extends JavaPlugin implements Listener{
    private main plugin;
     
        public PlayerJoinListener(main instance){
            plugin = instance;
        }
       
        @EventHandler(priority = EventPriority.NORMAL)
        public void onPlayerJoinEvent(PlayerJoinEvent e){
            String name = e.getPlayer().getName();
            String[] players = this.plugin.users.getString("players").split(",");
            if(this.playerexists(name)){
                String clan = this.plugin.spieler.get(name).clan();
                if(clan.equalsIgnoreCase("null") == false){
                    if(this.plugin.clans.getBoolean(clan + ".showclanjoin") == true){
                        if(this.plugin.users.getString(name + ".rang").equalsIgnoreCase("member") &&  this.plugin.clans.getBoolean(clan + ".showmemberjoin") == true){
     
                                for(int i = 0;i < players.length;i++){
                                    if(this.plugin.spieler.get(players[i]).clan().equalsIgnoreCase(clan)){
                                        Player p = Bukkit.getPlayer(players[i]);
                                        if(p.isOnline()){
                                            p.sendMessage("[" + ChatColor.BLUE + "Clan" + ChatColor.WHITE + " ]" + ChatColor.GREEN + " " + name + " ist dem Spiel beigetreten.");
                                        }
                                    }
                                }
     
                        }else if(this.plugin.users.getString(name + ".rang").equalsIgnoreCase("owner") &&  this.plugin.clans.getBoolean(clan + ".showownerjoin") == true){
                            for(int i = 0;i < players.length;i++){
                                if(this.plugin.spieler.get(players[i]).clan().equalsIgnoreCase(clan)){
                                    Player p = Bukkit.getPlayer(players[i]);
                                    if(p.isOnline()){
                                        p.sendMessage("[" + ChatColor.BLUE + "Clan" + ChatColor.WHITE + " ]" + ChatColor.GOLD + "Der Clanowner " + name + " ist dem Spiel beigetreten.");
                                    }
                                }
                            }
                        }else if(this.plugin.users.getString(name + ".rang").equalsIgnoreCase("mod") &&  this.plugin.clans.getBoolean(clan + ".showmodjoin") == true){
                            for(int i = 0;i < players.length;i++){
                                if(this.plugin.spieler.get(players[i]).clan().equalsIgnoreCase(clan)){
                                    Player p = Bukkit.getPlayer(players[i]);
                                    if(p.isOnline()){
                                        p.sendMessage("[" + ChatColor.BLUE + "Clan" + ChatColor.WHITE + " ]" + ChatColor.BLUE + "Der Clanmod " + name + " ist dem Spiel beigetreten.");
                                    }
                                }
                            }
                           
                        }
                    }
                }
            }else{
     
                this.plugin.users.addDefault(name + ".points", 10);
                this.plugin.users.addDefault(name + ".rang", "member");
                this.plugin.users.addDefault(name + ".coins", 2);
                this.plugin.users.addDefault(name + ".kills", 0);
                this.plugin.users.addDefault(name + ".deaths", 0);
                this.plugin.users.addDefault(name + ".clan", "null");
                this.plugin.users.addDefault(name + ".clanowner", false);
                this.plugin.users.addDefault(name + ".clanmod", false);
                this.plugin.users.addDefault(name + ".number", this.plugin.config.getInt("playernumber") + 1);
                this.plugin.config.set("playernumber",  this.plugin.users.getInt("playernumber") + 1);
                this.plugin.spieler.put(name, new cspieler(this.plugin,name,"null",0,0));
                this.plugin.saveYamls();
                try {
                    this.plugin.users.save(this.plugin.usersFile);
                } catch (IOException e1) {
                }
                System.out.println("Profil für den Spieler " + e.getPlayer().getName() + " angeleget.");
            }
        }
        public boolean playerexists(String name){
            boolean status = false;
            try{
                this.plugin.users.getString(name);
                if(this.plugin.users.getString(name).equalsIgnoreCase("") == false){
                    status = true;
                }
            }catch(Exception e){
                status = false;
            }
            return status;
        }
       
    }
    
     
  13. Offline

    jdawgerj515

    I know you made this guide a long time ago but what do you do now instead of firstRun(); ? Since I'm guessing that got deprecated
     
  14. Offline

    Neodork

    firstRun() is not deprecated for me, even though the tutorial is very old it still works perfectly fine!
     
  15. Offline

    bfgbfggf

    not work ;/ save only first comment
    Code:
            try {
                config.save(configFile);
            } catch (IOException e) {
                log.info("[plugin] Error");
                e.printStackTrace();
            }
    or just
    Code:
                            saveYamls();
    ;/ How to save that stupid comments
     
  16. Offline

    1SmallVille1

    DomovoiButler
    so I get an error at the getResource(), saying the method doesn't exist, am I missing something?
     
  17. Offline

    Croug

    Other than the vague use of "Text Talk", great tutorial!
     
  18. Offline

    th.eo

    Hello ! I follow this guide but when i want to reload my custom config file with this code :
    Code:java
    1. public void reloadCustomConfig() {
    2. if (customConfigFile == null) {
    3. customConfigFile = new File(getDataFolder(), "customConfig.yml");
    4. }
    5. customConfig = YamlConfiguration.loadConfiguration(customConfigFile);
    6.  
    7. // Look for defaults in the jar
    8. InputStream defConfigStream = this.getResource("customConfig.yml");
    9. if (defConfigStream != null) {
    10. YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
    11. customConfig.setDefaults(defConfig);
    12. }
    13. }
    from : http://wiki.bukkit.org/Configuration_API_Reference.
    But this function doesn't reload my config !
    Can you tell me why ?
    Thank you in advance :)
     
  19. Offline

    the_merciless

    save it
     
  20. Offline

    th.eo

    Thank you !
     
  21. Offline

    gabe4385

    I read all of this, maybe not extremely carefully, but I have one question, where IS the config.yml file, I mean it creates it, but arn't we supposed to create it and add things to it?
     
  22. Offline

    Goblom

    gabe4385 In your plugins jar its usually on the root of the jar. When its saved its saved like this... plugins/<plugin_name>/config.yml. You dont have to start adding things to it, you can already have data in the config and just start grabbing data.

    To get the config you do getConfig() to set data to it you do getConfig().set(path, value)
     
  23. Offline

    gabe4385

    lol, ok thanks.
     
  24. Offline

    reider45

    Great tutorial, I've been using this for a while now.
     
  25. Offline

    Kassestral

    it keeps telling me to make a getResource method, any help?
     
Thread Status:
Not open for further replies.

Share This Page