The correct way of setting up a config file?

Discussion in 'Plugin Development' started by damo1995, Dec 25, 2011.

Thread Status:
Not open for further replies.
  1. Hello all,

    I'm still quite new to java and want to create a configuration file that can be reloaded by command aswell being able to set a value if it's null or not in the configuration file.

    Although I don't have a clue how to do it correctly so that it can be reloaded.
    I have tried following the guide on the wiki but I still don't understand it and hoped somebody could explain it


    Thanks
    Damo
     
  2. The simlpiest and fastest way to create the default "config.yml" into the directory "plugins/<plugin name from plugin.yml>/" is:
    Code:
    // in onEnable() or a in a method triggered afterwards
    
    FileConfiguration cfg = getConfig();
    
    // assign stuff using cfg. methods to variables
    
    saveConfig();
    You might want to set up default values and such... like so:
    Code:
    	// public variables set before onEnable()
    	
    	public String subnode1 = "default value1";
    	public String subnode2 = "your second value";
    	public boolean yourToggle = false;
    
    
    
    		// in onEnable() or a method that triggers after it
    		
    		FileConfiguration cfg = getConfig();
    		FileConfigurationOptions cfgOptions = cfg.options();
    		
    		// set defaults (node name, default value) and save them
    		cfg.addDefault("node.subnode", subnode1);
    		cfg.addDefault("node.subnode2", subnode2);
    		cfg.addDefault("just-a-toggle", yourToggle);
    		cfgOptions.copyDefaults(true);
    		
    		// set a header text and save it
    		cfgOptions.header("Your text here\r\ntext on a new line");
    		cfgOptions.copyHeader(true);
    		
    		saveConfig(); // save defaults or header to file
    		
    		// get values (assign var = (node, default if node doesn't exist))
    		subnode1 = cfg.getString("node.subnode", subnode1);
    		subnode2 = cfg.getString("node.subnode2", subnode2);
    		yourToggle = cfg.getBoolean("just-a-toggle", yourToggle);
    
    ( indentation is off 'cause I copied from editor to omit any possible typos)


    So your best bet is to set up all of those codes into a separate method, and call that method from onEnable() and your reload command.
     
    D-Technodude likes this.
  3. seems easy enough, Thanks. Shall have to try and update my plugin with this now
     
  4. Unless that is pseudo code the correct usage of the options() is:
    Code:
                cfg.options().copyDefaults(true);
     
  5. Digi did that all ready. The cfgOptions = cfg.getOptions(), and cfg = getConfig(). he calls cfgOptions.copyDefaults(true) after he declares the defaults.
     
  6. Ah, sorry didn't see that. Thanks ^^

    I might use that. haha
     
  7. Offline

    Sagacious_Zed Bukkit Docs

    Although he did call copyDefaults(true) twice within 2 lines of code....
     
  8. Where ? I called copyDefaults() and copyHeader()

    Oh, also, the configs and other stuff are explained here: http://wiki.bukkit.org/HUGE_Plugin_Tutorial I dunno why I always forget about that usefull link xD
     
  9. I tried following that but i couldent follow it and it kept failing, I attempting this now, had some sucess just need to implement the reload command and the abibility to change the damage via a cmd ingame

    Ok now im having problems with my command -.- Will this ever end xD

    Here is what i've got, I know i've mostlikley made a mistake and i wont be able to see it

    Main class:

    Code:
    public class SnowballFight extends JavaPlugin {
        public final Logger log = Logger.getLogger("Minecraft");
    
        public final SnowballListener sl = new SnowballListener();
        private SFCommandExecutor CommandExecutor;
    
        public String value1 = "damage 5";
    
        public void onEnable() {
            CommandExecutor = new SFCommandExecutor(this);
            final FileConfiguration cfg = getConfig();
            FileConfigurationOptions cfgOptions = cfg.options();
            cfg.addDefault("damage", 5);
            cfgOptions.copyDefaults(true);
            cfgOptions.header("Default Config for SnowbalLFight \n use the Damage value to change the damage done \n per snowball");
            cfgOptions.copyHeader(true);
            saveConfig();
            PluginManager pm = this.getServer().getPluginManager();
    }
    SFCommandExecutor:
    Code:
    package me.damo1995.SnowballFight;
    
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    
    public class SFCommandExecutor implements CommandExecutor {
        private SnowballFight plugin;
        public SFCommandExecutor(SnowballFight plugin){
            this.plugin = plugin;
        }
    
        public boolean onCommand(CommandSender s, Command c, String l, String [] args)
        {
    Player sender = (Player) s;
    
            if(l.equalsIgnoreCase("sf"))
    {
                if(args.length < 1)
                {
                    s.sendMessage(ChatColor.BLUE + "+++++++++SnowballFight++++++++++");
                    s.sendMessage(ChatColor.WHITE + "+ A Simple Snowball damage Plugin!");
                    s.sendMessage(ChatColor.RED + "+ Version: " + plugin.getDescription().getVersion());
                    s.sendMessage(ChatColor.RED + "+ Developer: " + plugin.getDescription().getAuthors());
                    s.sendMessage(ChatColor.YELLOW + "+++++++++++++++++++++++++++++");
                }
                else
                {
                    if(args[0].equalsIgnoreCase("reload"))
                    {
                        if(s.isOp()){
     
                        plugin.reloadConfig();
                            s.sendMessage(ChatColor.GREEN + "SnowbalLFight Configuration Reloaded!");
                        }
                        else
                        {
                            s.sendMessage("You cannot do this!");
                        }
                    }
                    else
                        if(args[0].equalsIgnoreCase("damage")){
                            if(sender.isOp()){
                            s.sendMessage("Snowball currentley do" + "" + plugin.getConfig().get("damage") + "" + "damage." );
                                            }
                            else
                            {
                                s.sendMessage("You cannot do this!");
                            }
                        }
                }
    
    }
            return false;
    
        }
    
    
    
    }
    
    But when i type /sf then any of my commands it does nothing and registers nothing in the console.

    Any ideas ?

    Thanks

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 22, 2016
  10. Offline

    Sagacious_Zed Bukkit Docs

  11. nevermind, I managed to get the commands working and reload working, Thanks for the help guy and girls, Turns out i forgot to define the command executor xP

    Hmm, Now i cannot get it to reload the config.

    I have it set so when the command /sf reload is run that it reloads the config from file using the plugin.reloadConfig(); Option but it dosent seem to be working as it is not changing the damage done by the snowballs.

    Anybody got any ideas?

    Thanks

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 22, 2016
  12. Offline

    Sagacious_Zed Bukkit Docs

    @damo1995
    by chance do you ever assign the returned object from getConfig() to a field?
     
  13. I beleve so yes,

    event.setDamage(cfg.getInt("damage")); if thats what you mean, Sorry im still new to java xD

    I shall post all my code anyway, that way you can see if thats not what you mean.

    SnowballFight.java
    Code:
    package me.damo1995.SnowballFight;
    
    import java.util.logging.Logger;
    
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.FileConfigurationOptions;
    import org.bukkit.entity.Entity;
    import org.bukkit.entity.LivingEntity;
    import org.bukkit.entity.Player;
    import org.bukkit.entity.Snowball;
    import org.bukkit.event.Event;
    import org.bukkit.event.Event.Priority;
    import org.bukkit.event.entity.EntityDamageByEntityEvent;
    import org.bukkit.event.entity.EntityDamageEvent;
    import org.bukkit.event.entity.EntityListener;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class SnowballFight extends JavaPlugin {
        public final Logger log = Logger.getLogger("Minecraft");
    
        public final SnowballListener sl = new SnowballListener();
        private SFCommandExecutor CommandExecutor;
    
        public String value1 = "damage 5";
    
        public void onEnable() {
            this.CommandExecutor = new SFCommandExecutor(this);
            this.getCommand("sf").setExecutor(this.CommandExecutor);
            final FileConfiguration cfg = getConfig();
            FileConfigurationOptions cfgOptions = cfg.options();
            cfg.addDefault("damage", 5);
            cfgOptions.copyDefaults(true);
            cfgOptions.header("Default Config for SnowbalLFight \n use the Damage value to change the damage done \n per snowball");
            cfgOptions.copyHeader(true);
            saveConfig();
            PluginManager pm = this.getServer().getPluginManager();
            pm.registerEvent(Event.Type.ENTITY_DAMAGE, new EntityListener() {
      
                public void onEntityDamage(EntityDamageEvent event) {
                    if (event instanceof EntityDamageByEntityEvent) {
                        Entity playerA = ((EntityDamageByEntityEvent) event).getDamager();
                            if (playerA instanceof Snowball) {
                                if (event.getEntity() instanceof Player)
                                if (event.getEntity() instanceof LivingEntity && !(event.getEntity() instanceof Player))
                                    return;
                                event.setDamage(cfg.getInt("damage"));
                            }
    
                        }
                    }
            }, Priority.Highest, this);
    
            this.logMessage("By Damo1995 Enabled");
            this.logMessage("Snowballs currentley doing" + " " + cfg.getInt("damage") + " " + "damage per hit.");
        
        }
    
        public void onDisable() {
            this.logMessage("By Damo1995 Disabled");
        }
    
        public void logMessage(String msg){
            PluginDescriptionFile pdFile = this.getDescription();
            this.log.info(pdFile.getName() + " " + pdFile.getVersion() + ": " +msg);
    
        }
     
    }
    
    SFCommandExecutor:
    Code:
    package me.damo1995.SnowballFight;
    
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    
    public class SFCommandExecutor implements CommandExecutor {
        private SnowballFight plugin;
        public SFCommandExecutor(SnowballFight plugin){
            this.plugin = plugin;
        }
    
        public boolean onCommand(CommandSender s, Command c, String l, String [] args)
        {
            int damage = plugin.getConfig().getInt("damage");
    Player sender = (Player) s;
    
            if(l.equalsIgnoreCase("sf"))
    {
                if(args.length < 1)
                {
                    sender.sendMessage(ChatColor.YELLOW + "+++++++++SnowballFight++++++++++");
                    sender.sendMessage(ChatColor.GREEN + "+ A simple snowball damage Plugin!");
                    sender.sendMessage(ChatColor.RED + "+ Version: " + plugin.getDescription().getVersion());
                    sender.sendMessage(ChatColor.LIGHT_PURPLE + "+ Developer: " + plugin.getDescription().getAuthors());
                    sender.sendMessage(ChatColor.GOLD + "Current snowball damage:" + damage);
                    sender.sendMessage(ChatColor.YELLOW + "+++++++++++++++++++++++++++++");
                    return true;
                }
                else if(args[0].equalsIgnoreCase("reload"))
                    {
                        plugin.reloadConfig();
                            sender.sendMessage(ChatColor.GREEN + "SnowballFight Configuration Reloaded!");
                    }
                    else if(args[0].equalsIgnoreCase("damage")){
                            sender.sendMessage("Snowballs currentley do" + " " + damage + " " + "damage." );
                        }
                    else if(args[0].equalsIgnoreCase("setdamage")){
                                int dmg =  Integer.parseInt(args[1]);
                                    plugin.getConfig().set("damage", dmg);
                                    sender.sendMessage("Snowball Damage set to" + " " + dmg);
                                    plugin.saveConfig();
                                    plugin.reloadConfig();
                        }
                }
            return false;
        }
    }
    
    Thanks in advanced.
     
  14. Offline

    Sagacious_Zed Bukkit Docs

    @damo1995
    in your anonymous EntityListener
    replace all occurrences of cfg with the getConfig() method
    If my suspicions are correct, that should fix it.

    In essence in onEnable you initialize cfg to the getConfig() object. however, when you call reloadConfig() it actually changes the config object, yet the reference to the old one remains for cfg.
     
  15. So in essence the main class should look like this:
    Code:
    package me.damo1995.SnowballFight;
    
    import java.util.logging.Logger;
    
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.FileConfigurationOptions;
    import org.bukkit.entity.Entity;
    import org.bukkit.entity.LivingEntity;
    import org.bukkit.entity.Player;
    import org.bukkit.entity.Snowball;
    import org.bukkit.event.Event;
    import org.bukkit.event.Event.Priority;
    import org.bukkit.event.entity.EntityDamageByEntityEvent;
    import org.bukkit.event.entity.EntityDamageEvent;
    import org.bukkit.event.entity.EntityListener;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class SnowballFight extends JavaPlugin {
        public final Logger log = Logger.getLogger("Minecraft");
    
        private SFCommandExecutor CommandExecutor;
    
        public String value1 = "damage 5";
    
        public void onEnable() {
            this.CommandExecutor = new SFCommandExecutor(this);
            this.getCommand("sf").setExecutor(this.CommandExecutor);
            final FileConfiguration cfg = getConfig();
            FileConfigurationOptions cfgOptions = cfg.options();
            getConfig().addDefault("damage", 5);
            cfgOptions.copyDefaults(true);
            cfgOptions.header("Default Config for SnowbalLFight \n use the Damage value to change the damage done \n per snowball");
            cfgOptions.copyHeader(true);
            saveConfig();
            PluginManager pm = this.getServer().getPluginManager();
            pm.registerEvent(Event.Type.ENTITY_DAMAGE, new EntityListener() {
    
    
    
                public void onEntityDamage(EntityDamageEvent event) {
                    if (event instanceof EntityDamageByEntityEvent) {
                        Entity playerA = ((EntityDamageByEntityEvent) event).getDamager();
                            if (playerA instanceof Snowball) {
                                if (event.getEntity() instanceof Player)
                                if (event.getEntity() instanceof LivingEntity && !(event.getEntity() instanceof Player))
                                    return;
                                event.setDamage(getConfig().getInt("damage"));
                            }
    
                        }
                    }
            }, Priority.Highest, this);
    
            this.logMessage("By Damo1995 Enabled");
            this.logMessage("Snowballs currentley doing" + " " + getConfig().getInt("damage") + " " + "damage per hit.");
    
    
    
    
    
        }
    
        public void onDisable() {
            this.logMessage("By Damo1995 Disabled");
        }
    
        public void logMessage(String msg){
            PluginDescriptionFile pdFile = this.getDescription();
            this.log.info(pdFile.getName() + " " + pdFile.getVersion() + ": " +msg);
    
        }
    
    
    }
    
    
    Is that what your saying?

    Edit: Just tried Works like a charm, tyvm.
     
Thread Status:
Not open for further replies.

Share This Page