[Tutorial/Intermediate] Configuration YAML - Make configs!

Discussion in 'Resources' started by TheWayIRoll, Nov 13, 2011.

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

    TheWayIRoll

    Because of the new config API breaks alot of plugins, I have written up an intermediate tutorial about setting up your own Configuration file (YAML).

    1.1 - Variable

    The Variable of the configuration is important. It has the cores and API of it and it can mess up with your code without it. Let's look at the variable.
    Code:java
    1.  
    2. FileConfiguration config;
    3.  

    Of course, you can change the second field ("config") to whatever you want, but make sure you modify the config word to your variable in the rest of this tutorial.

    1.2 - Try & Catch
    Probably the most simpliest way, you can do the following in onEnable.
    Code:java
    1.  
    2. try{
    3. }catch(Exception e1){
    4. e1.printStackTrace();
    5. }
    6.  

    I recommend that you print the stacktrace, so if anything goes wrong with the config file, they can show it and paste the configuration.

    1.3 - Get the config
    The first line of the try section should be something like this.
    Code:java
    1.  
    2. config = getConfig();
    3.  

    It will catch any configuration. Make sure the variable left of the equation symbol is the same after your FileConfiguration variable.

    1.4 - Making a Directory and Config
    This one is easy, too. I recommend using these lines.
    Code:java
    1.  
    2. File <pluginname> = new File("plugins" + File.separator + "<pluginname>" + File.separator + "config.yml");
    3. <pluginname>.mkdir();
    4.  

    Change <pluginname> to the name of your plugin.

    1.5 - My (@TheWayIRoll) method of configuration.
    Many people have their own way of installing configuration. I will share you one example of mines.

    1.5.1 - Boolean value

    Code:java
    1.  
    2. if(!config.contains("general.cake.eat")) {
    3. config.set("general.cake.eat", false);
    4. }
    5.  


    It roots down into like this:
    Code:
    general:
        cake:
            eat: false
    
    So you can do anything you want with it.

    1.5.2 Integer value

    Code:text
    1.  
    2. if(!config.contains("general.cake.reproduction")){
    3. config.set("general.cake.reproduction", 5);
    4. }
    5.  

    The syntax above will allow the cake to reproduce itself 5 more times. The config should look like this if you copy all of them.
    Code:
    general:
        cake:
            eat: false
            reproduction: 5
    
    1.5.3 - Strings
    Code:java
    1.  
    2. if(!config.contains("general.cake.broadcast") {
    3. config.set("general.cake.broadcast", "A cake has reproduced another cake.");
    4. }
    5.  

    The syntax above is the message that is broadcasted through the server.
    If you copy all of the code above in the 1.5 section, you can get the following configuration.
    Code:
    general:
        cake:
            eat: false
            reproduction: 5
            broadcast: "A cake has reproduced another cake!"
    
    (to be continued)

    1.6 Reading from Configuration
    Now that we have the configuration we want.. how about we can load the stuff and say it? We need to catch the line from the configuration line first before we can call it and say it. This part is a little intermediate. I'll give you the examples of what it is.

    Code:java
    1.  
    2. boolean <variable> = config.getBoolean("general.cake.eat");
    3. int <variable> = config.getInt("general.cake.reproduction");
    4. String <variable> = config.getString("general.cake.broadcast");
    5.  


    Replace <variable> with your own variable.

    Now, we want an event to occurr. Place an proper event, hook in the listener, then you can call anything like
    Code:java
    1.  
    2. Bukkit.getServer().broadcastMessage(<variable>);
    3.  

    The line above will broadcast the string of <variable> (change the variable thingy to your variable you called on the line you catch the configuration value). Now you can do saveConfig(); in the Try section.

    1.7 Ending
    I just want to say, this tutorial took me 15 minutes of hard work typing, effort, and old code look-up. I want everyone to read this amazing tutorial on my method of configuration and reading stuff. You can do a endless of possibilities that are possible in Bukkit using configuration.

    This is the only 1st tutorial in the series I plan to write up. Next is Hashmaps or Commands. Maybe who knows what will be next? If you have any suggestions to improve this tutorial, or have an issue, don't fret. Just post your issue on this topic.

    Thank you for taking your time.
    - TheWayIRoll
    + Future Dev
    + Future Server Owner

    EDIT: One more thing, if you pull all of them together, you will get this code. I post it because I don't want to confuse people.
    Code:java
    1.  
    2. try{
    3. config = getConfig();
    4. File <variable> = new File("plugins" + File.separator + "<variable>" + File.separator + "config.yml");
    5. <variable>.mkdir();
    6. if(!config.contains("general.cake.eat")){
    7. config.set("general.cake.eat", false);
    8. }
    9. if(!config.contains("general.cake.reproduction")){
    10. config.set("general.cake.reproduction", 5);
    11. }
    12. if(!config.contains("general.cake.broadcast")){
    13. config.set("general.cake.broadcast", "A cake has reproduced another cake");
    14. }
    15. saveConfig();
    16. }catch(Exception e1){
    17. e1.printStackTrace();
    18. }
    19.  


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

    thehutch

    Tutorial on saving and reloading?
     
    Limeth likes this.
  3. Offline

    TightMrKI113r

    1. File <pluginname> = File("plugins" + File.separator + "<pluginname>" + File.separator + "config.yml");
    2. <pluginname>.mkdir();
    should be:
    1. File <pluginname> = new File("plugins" + File.separator + "<pluginname>" + File.separator + "config.yml");
    2. <pluginname>.mkdir();
     
  4. Offline

    TheWayIRoll

    Oh, thanks for clarifying that. I missed it in the old code lookup.

    @thehutch I might do that later on, when I learn how to.
     
    thehutch likes this.
  5. Offline

    robxu9

    Thanks for the updated tutorial! This should go on the wiki for future reference, too ;)
     
  6. Offline

    TheWayIRoll

    @robxu9 Thanks for the feedback. I'm learning a way to save/reload the configuration.
     
  7. Offline

    TightMrKI113r

    Instead of
    Code:
    File <pluginname> = new File("plugins" + File.separator + "<pluginname>" + File.separator + "config.yml");
    Try Using
    Code:
    File <pluginname> = new File (getDataFolder() + "config.yml");
    This means that if for some reason bukkit rename the plugins folder to, say, 'addons', you wont need to go back and change anything :)
     
    Wizardo367 and 4am like this.
  8. Offline

    4am

    WRONG
    Please please NEVER do this! I can't tell you how many plugins are unusable to me and many others because of this!

    Don't forget that CraftBukkit allows you to configure your plugins/ directory to be anywhere! (Use the -P startup option!)

    ALWAYS USE getDataFolder().mkdirs(); then use FileConfiguration config = getConfig() to either open the existing config.yml OR it will copy the default one from the root of your JAR into the plugin's directory if it's not already there. Two lines of code, and you never need to worry about file separators or names of file, creating directories or, my worst enemy, trying to write to /opt/craftbukkit/bin which is read only on my server!

    NEVER EVER EVER HARD CODE YOUR PATH! EVER! PLEASE! :)

    That is exactly right. Users can rename plugins/ with command line flags! also, don't forget that world directory location is configurable! Don't hard code that, either!

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 21, 2016
    zack6849, ferrybig and SeeD419 like this.
  9. Offline

    feildmaster

    Remove the mkdir() call.

    4am Don't use mkdir().

    also,

    new File(getDataFolder(),"config.yml"); <- Done.
     
    blackwolf12333 likes this.
  10. plz uupdate main post for the "new File(getDataFolder(),"config.yml");" isue
     
  11. PHP:
    try
    {
        
    File file = new File("plugins/<plugin name>/config.yml"):
        
    FileConfiguration config getConfig();
        if(!
    file.exists)
        {
            
    config.addDefault(pathobject);
        }
    catch(
    Exception e){  }
    ^that is the config that i use for all my plugins.
    hope it helped!
     
  12. Offline

    x86cam

    Can you do a video tutorial on this?
     
  13. not a video, but this is more detailed:
    PHP:
    public void onEnable()
    {
        try
        {
            
    File file = new File("plugins/<folder>/config.yml");
            
    FileConfiguration cfg getConfig();
            if(!
    file.exists())
            {
                
    cfg.addDefault("this.is.a.string""yo i am a string");
                
    cfg.options().copyDefaults(true);
                
    saveConfig();
            }
        }
        catch(
    Exception e){ }
    }
    the config.yml would now contain:
    Code:
    this:
        is:
            a:
                string: yo i am a string
    hope it helped :D
     
  14. Offline

    Lolmewn

    What if I want to add comments to the config file? The Bukkit system tends to filter them out..
     
  15. Offline

    Tauryuu

    Is it possible to make more files (eg. database.yml) with this config like this?

    Code:
    config = getConfig();
    File config = new File(getDataFolder() + "config.yml");
    config.mkdir();
    File database = new File(getDataFolder() + "database.yml");
    database.mkdir();
     
  16. Offline

    chenr1

    111 thank you This is so helpfull i'm not here to cmoplain just to thanks.
     
  17. Offline

    x86cam

    How would I make warps with this?
     
  18. Offline

    Scullyking

    I get an error on the line that catches the variable from the config.
    Code:
    int baserep = config.getInt("config.baserep");
    
    It's on the first config and it sais, "config cannot be resolved"

    Help?
     
  19. Offline

    Limeth

    The file doesn't even get created =(
    help.
     
  20. Offline

    thehutch

    There is a new and better way to do all this now

    1. Create a file inside your plugin.jar called "config.yml" just the same way you'd make a plugin.yml
    2. Write out how you want the config to look like inside the file
    3. use this code to extract it from the jar:
    Code:
    File config = new File(this.getDataFolder(), "config.yml");
    if (!config.exists()) {
        this.saveDefaultConfig();
    }

    This is the simplest way to configure your config files. If you have other questions just ask :D
     
  21. Offline

    tacticalsk8er

    thehutch
    Could you make multiple .yml files this way?
    For example
    Code:
    File database = new File(this.getDataFolder(), "database.yml");
    if (!database.exists()) {
        this.saveDefaultConfig();
    }
     
  22. Offline

    thehutch

    You could but instead of "saveDefaultConfig()" you'd use saveResource("database.yml");
     
  23. Offline

    Vandrake

    You need to do the "saveConfig();" after everything on the onEnable(). ok? :3
     
  24. Offline

    64BFox

    I'm trying to figure out how to read from a file, and I my code so far doesn't work"
    Code:java
    1. File map = File(this.getDataFolder(), args[1]+".yml");
    2. if(!map.exists()) {
    3. //Code
    4. }


    It just doesn't seem to want to work :( Any help would be greatly appreciated!
     
  25. Offline

    4am

    Again, please never hard code the path to plugins/ folder. Use getDataFolder() instead. My plugins folder doesn't live in the same place as my craftbukkit.jar, and "just use a symlink dude" is NOT an acceptable answer (for anyone who thinks it is)
     
  26. Offline

    Zippo007

    Quick Question: I try using the getConfig(), and getDataFolder() function, and my environment(Eclispe) is telling me that it doesn't exist, I'm using bukkit 1.4.5. Is there a simple mistake that I made?
     
  27. Offline

    4am

    They are part of the Plugin class, make sure you are calling them in context or that you have a reference to your JavaPlugin object.
     
  28. Offline

    puyttre

    Or you can save it the simpler ways:

    1. Bukkit's automagical method:
    Code:java
    1. this.saveDefaultConfig()


    2. Bukkit's automagical method but with customizabilitism:
    Code:java
    1. FileConfiguration config;
    2.  
    3. if(!new File(getDataFolder(), "config.yml").exists()){
    4. // saveResource(String filePath, boolean replaceIfExists)
    5. saveResource("config.yml", false);
    6. log.info("Generating a new config for you.");
    7. }else{
    8. config = getConfig();
    9. log.info("Config found. Using it.");
    10. }
     
    MrMB2013, isodnerf and phondeux like this.
  29. Offline

    Weasel_Squeezer

    you can safely use a slash '/' and not File.separator with the Java File libraries because the library code handles translating platform-specific paths internally. Really the only time File.separator would be good to use is when dealing with UI and to make file paths make sense for the users specific platform.
    Just thought I'd share :p
     
  30. Offline

    MrLolEthan

    And this whole time I had been writing my own custom config class to handle reading/writing with BufferedReaders/BufferedWriters... I could have used a couple lines of code instead of a new class lol.
     
Thread Status:
Not open for further replies.

Share This Page