Solved How to save defaults to my lang.yml

Discussion in 'Plugin Development' started by Dave Nathanael, Jan 2, 2016.

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

    Dave Nathanael

    Hello Bukkit Forums!

    I am currently having a problem on copying default values that I have defined since beginning through my Eclipse. So the full explaination goes here:

    I wanted two configuration files, which is "config.yml" for any common configuration needs, and "lang.yml" specifically to configure message generated by my plugin. (Language customization is always lovely, isn't it?) I create the files manually on my Eclipse project folder, creating the YAML files, adding the default values for my plugin (such paths and values) by myself by typing it manually on the YAML files. When I exported my plugin it seems that I have successfully (or I thought it was a success) generated both of the files BUT failed to include my pre-defined default values only on the "lang.yml" file. (The plugin successfully copied the default values I've typed on the config.yml it generated). I could not figured out what's wrong with the YAML file besides the default config file (Is it because the config.yml is supported directly by the API and custom-named configs such as my lang.yml is harder to deal with?)

    I could provide my full classes codes, as I think the problems would be somewhere lurking beneath my code(?)

    Classes (open)

    Code:
    package me.kutuhiphop.enchantmentscrolls;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class Main extends JavaPlugin {
       
        public Main instance;
       
        SettingsManager config = SettingsManager.getInstance();
       
        public void onEnable(){
            instance = this;
            config.setup(this);
        }
       
        public void onDisable(){
            instance = null;
        }
       
        boolean isInt(String string){
            try{
                Integer.parseInt(string);
                return true;
            } catch (NumberFormatException e){
                return false;
            }
        }
       
        public boolean onCommand(CommandSender s, Command cmd, String label, String[] args){
           
            if(cmd.getName().equalsIgnoreCase("escroll")){
                if(args.length == 0){
                    Language.getInstance().printHelp(s);
                    return true;
                }
                if(args[0].equalsIgnoreCase("get")){
                    // escroll get <enchantment> <enchantment level> <amount> [player]
                    if(!(s instanceof Player)){
                        Language.getInstance().noConsole(s);
                        return true;
                    }
                   
                   
                    if((args.length < 4) || (args.length > 5) || (isInt(args[2])) || (isInt(args[3]))){
                        Language.getInstance().invalidArguments(s);
                        return true;
                    }
                   
                    Player p;
    
                    if (args.length == 4){
                        p = (Player)s;
                    } else {
                        if(Bukkit.getPlayerExact(args[4]) == null){
                            Language.getInstance().invalidPlayerName(s);
                            return true;
                        }
                        p = Bukkit.getPlayerExact(args[4]);
                    }
                   
                    int amount = Integer.parseInt(args[3]);
                   
                    ItemStack scroll = new ItemStack(Material.PAPER, amount);
                    ItemMeta scrollMeta = scroll.getItemMeta();
                    scrollMeta.setDisplayName(ChatColor.AQUA + "+" + args[1].toUpperCase() + args[2]);
                    scrollMeta.getLore().add(ChatColor.GOLD + "Enchantment Scroll");
                    scrollMeta.getLore().add(ChatColor.GOLD + config.getConfig().getString("scrollLore"));
                    scroll.setItemMeta(scrollMeta);
                   
                    if(!(p.getInventory().firstEmpty() == -1)){
                        p.getInventory().setItem(p.getInventory().firstEmpty(), scroll);
                        p.sendMessage(Language.prefix + ChatColor.getByChar(config.getData().getString("getSuccess.color")) + config.getData().getString("giveSuccess.message"));
                    } else {
                        p.sendMessage(Language.prefix + ChatColor.getByChar(config.getData().getString("getFailed.color")) + config.getData().getString("giveFailed.message"));
                       
                    }
                }
            }
            return true;
        }
    }
    

    Code:
    package me.kutuhiphop.enchantmentscrolls;
    
    import org.bukkit.ChatColor;
    import org.bukkit.command.CommandSender;
    
    public class Language {
    
        // Instance thingy
        private Language() {
        }
    
        static Language instance = new Language();
    
        public static Language getInstance() {
            return instance;
        }
    
        // EnchantmentScrolls Unique Prefix!
        public static String prefix = ChatColor.GOLD + "EnchantmentScrolls" + ChatColor.GRAY + ": ";
    
        // Getting the config instance.
        SettingsManager lang = SettingsManager.getInstance();
    
        // Help
        public void printHelp(CommandSender s) {
            ChatColor color = ChatColor.getByChar(lang.getData().getString("printHelp.color"));
    
            s.sendMessage(prefix + color + lang.getData().getString("printHelp.message"));
    
        }
    
        // Error message if the sender was the console.
        public void noConsole(CommandSender s) {
            s.sendMessage(lang.getData().getString("noConsole"));
        }
    
        // Error message if the sender defines not enough arguments(too short).
        public void invalidArguments(CommandSender s) {
            ChatColor color = ChatColor.getByChar(lang.getData().getString("invalidArguments.color"));
    
            s.sendMessage(prefix + color + lang.getData().getString("invalidArguments.message"));
        }
       
        //Error message when plugin could not find specified player on the command.
        public void invalidPlayerName(CommandSender s){
           
            ChatColor color = ChatColor.getByChar(lang.getData().getString("invalidPlayerName.color"));
            s.sendMessage(prefix + color + lang.getData().getString("invalidPlayerName.message"));
           
        }
    }

    Code:
    package me.kutuhiphop.enchantmentscrolls;
    
    import java.io.File;
    import java.io.IOException;
    
    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 SettingsManager {
       
        //Instance thingy
        private SettingsManager() {}
       
        static SettingsManager instance = new SettingsManager();
       
        public static SettingsManager getInstance(){
            return instance;
        }
       
        Plugin plugin;
        FileConfiguration config;
        File configfile;
        FileConfiguration data;
        File datafile;
       
        public void setup(Plugin p){
           
            this.plugin = p;
           
            configfile = new File(p.getDataFolder(), "config.yml");
            config = p.getConfig();
            config.options().copyDefaults(true);
            saveConfig();
           
           
            //Creating the plugin folder that contains the config.
            if (!p.getDataFolder().exists()){
                p.getDataFolder().mkdir();
            }
           
            datafile = new File(p.getDataFolder(), "lang.yml");
           
            if(!datafile.exists()){
               
                try {
                    datafile.createNewFile();
               
                }
                catch (IOException e) {
                   
                    Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create lang.yml!");
                   
                }
            }
           
            data = YamlConfiguration.loadConfiguration(datafile);
        }
       
        public FileConfiguration getData(){
            return data;
        }
       
        public void saveData(){
            try{
                data.save(datafile);
            }
            catch (IOException e){
                Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save lang.yml!");
               
            }
        }
       
        public void reloadData(){
            data = YamlConfiguration.loadConfiguration(datafile);
        }
       
        public FileConfiguration getConfig(){
            return config;
        }
       
        public void saveConfig(){
            try{
                config.save(configfile);
            }
            catch (IOException e){
                Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save config.yml!");
            }
        }
       
        public void reloadConfig(){
            config = YamlConfiguration.loadConfiguration(configfile);
        }
       
        public PluginDescriptionFile getDesc(){
            return plugin.getDescription();
        }
    
    }
    


    Thanks for reading and any solutions that could make it against my problem would be great! As I myself just recently learned on how to code Java/Bukkit.

    Cheers! :D
     
  2. Offline

    mcdorli

    Yep. Try File.copy(File from, File to)
     
  3. Offline

    Dave Nathanael

    Which files are the "from-file" and the "to-file" exactly? Because the default values I've defined is in the same file I think (the same "lang.yml", so there is no intention to copy defaults from file A to the file "lang.yml" for example)

    [​IMG]
     
  4. Offline

    mcdorli

  5. Offline

    Ruptur

  6. Offline

    Dave Nathanael

    (First of all, sorry for the late reply, because I was on vacation for the last two days so I can't continue my work on the code yet.)

    Big thanks to @mcdorli and @Ruptur for helping me, I have tried several ways on saving the default values to the empty files, and it seems this code below managed to do that just fine. If anyone finds my code have something's that unappropriate programmatically, or it is unefficient, let me know so I too can improve it.


    Code:
    @SuppressWarnings("deprecation")
        public void setup(Plugin p) {
            this.p = p;
    
            if (!p.getDataFolder().exists()) {
                p.getDataFolder().mkdir();
            }
    
            configfile = new File(p.getDataFolder(), "config.yml");
            langfile = new File(p.getDataFolder(), "lang.yml");
    
            // Creating new and empty files.
            if (!configfile.exists()) {
                try {
                    configfile.createNewFile();
                    InputStream isConfig = p.getResource("config.yml");
                    config = YamlConfiguration.loadConfiguration(isConfig);
                    try {
                        config.save(configfile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                  
                } catch (Exception e) {
                    Bukkit.getLogger().info("EnchantmentScrolls could not generate new config.yml file!");
                }
            }
            if (!langfile.exists()) {
                try {
                    langfile.createNewFile();
                    InputStream isLang = p.getResource("lang.yml");
                    lang = YamlConfiguration.loadConfiguration(isLang);
                    try {
                        lang.save(langfile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                  
                } catch (Exception e) {
                    Bukkit.getLogger().info("EnchantmentScrolls could not generate new lang.yml file!");
                }
            }
    EDIT: I have changed the thread prefix to "SOLVED", as the solution is here. :D

    Hope this could help other people as well!
     
Thread Status:
Not open for further replies.

Share This Page