How to create multiple .yml 's (flatfile database)

Discussion in 'Plugin Development' started by thehutch, Oct 24, 2011.

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

    thehutch

    Ok so me and some people are creating a plugin which requires to store quite a few ArrayLists (List<String>) which ever one is which but my question is how do I create them because I cant just use the new configurationAPI because you can only create one of them. Yes I have read the new configuration tutorial by (Some russian named person :p) but this has failed to work and there is apparently an easier way. I know of BufferedWriter which I have seen a few but because there are many different types of file writers the same goes for the readers but idk which to choose. This is the tutorial which I followed and the method is complicated :)
    Also i'd like to ask if anyone here is skilled with making databases other than flatfile (H2, SQLite, MYSQL) any would be awesome, just pm if you want to aid us.
    Code:
    public class TheSocialNetwork extends JavaPlugin {
    
        /*
         * Variables
         */
        public File configFile;
        public File friendsFile;
        public File mailBoxFile;
        public File ignoreListFile;
        protected FileConfiguration config;
        protected FileConfiguration friends;
        protected FileConfiguration mailBox;
        protected FileConfiguration ignoreList;
     
        @Override
        public void onDisable() {
            System.out.println("[FriendsList] Disabled version: " + getDescription().getVersion());
        }
    
        @Override
        public void onEnable() {
    
            configFile = new File(getDataFolder(), "config.yml");
            friendsFile = new File(getDataFolder(), "friends.yml");
            mailBoxFile = new File(getDataFolder(), "mailbox.yml");
            ignoreListFile = new File(getDataFolder(), "ignoreList.yml");
    
            try {
                firstRun();
            } catch (Exception e) {
                System.out.println("Exception :O error error error");
                e.printStackTrace();
            }
    
            setupMcmmo();
            setupHeroes();
            /*
             * Register Commands
             */
            getCommand("xFriends").setExecutor(new AddFriendCommands(this));
            getCommand("mailbox").setExecutor(new MailBoxCommands(this));
            PluginManager pm = getServer().getPluginManager();
            /*
             * Player Listener Events
             */
            pm.registerEvent(Event.Type.PLAYER_INTERACT_ENTITY, new Plistener(this) , Event.Priority.Normal, this);
            pm.registerEvent(Event.Type.PLAYER_LOGIN, new Plistener(this) , Event.Priority.Normal, this);
            pm.registerEvent(Event.Type.PLAYER_JOIN, new Plistener(this), Event.Priority.Normal, this);
            /*
             * Custom Events
             */
            pm.registerEvent(Event.Type.CUSTOM_EVENT, new HeroesListener(this), Event.Priority.Normal, this);
            System.out.println("[FriendsList] Enabled version: " + getDescription().getVersion());
            System.out.println("[FriendsList] created by " + getDescription().getAuthors());
        }
        /*
         * Generates the files
         */
    
        private void firstRun() throws Exception {
    
            if (configFile == null) {
                config.load(getResource("config.yml"));
                config.save(configFile);
            }
            if (friendsFile == null) {
                friends.load(getResource("friends.yml"));
                friends.save(friendsFile);
            }
            if (mailBoxFile == null) {
                mailBox.load(getResource("mailbox.yml"));
                mailBox.save(mailBoxFile);
            }
            if (ignoreListFile == null) {
                ignoreList.load(getResource("ignoreList.yml"));
                ignoreList.save(ignoreListFile);
            }
        }
        /*
         * Saves files
         */
        public void saveYamls() {
            try {
                friends.save(configFile);
                mailBox.save(mailBoxFile);
                config.save(configFile);
                ignoreList.save(ignoreListFile);
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
        /*
         * Load files
         */
        public void loadYamls() {
            try {
                config.load(configFile);
                friends.load(configFile);
                mailBox.load(mailBoxFile);
                ignoreList.load(ignoreListFile);
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
        /**
         * Write a message to mailbox.yml
         **/
        @SuppressWarnings("unchecked")
        public void writeMessageToMailBox(String msg, String player) {
            mailBox.getList("Mail." + player).add(msg);
        }
    
        public void readFromMailBox(String player) {
      
        }
    
        @SuppressWarnings("unchecked")
        public List<String> getMailBox(String mailowner) {
            return mailBox.getList("mail." + mailowner);
        }
      
        /**
         * Gets every player that has ever joined
         **/
        public HashSet<OfflinePlayer> getAllExistingPlayers() {
    
        List<World> worlds = Bukkit.getServer().getWorlds();
        HashSet<OfflinePlayer> allPlayers = new HashSet<OfflinePlayer>();
    
            for (World w : worlds) {
                File f = new File(w.getName() + File.separator + "players" + File.separator);
    
            for (File playerFile : f.listFiles()) {
                allPlayers.add(Bukkit.getServer().getOfflinePlayer(playerFile.getName().substring(0, playerFile.getName().length() - 4)));
            }
        }
        return allPlayers;
        }
    
        /**
         * Creates friends.txt
    
        public void loadFile() throws IOException {
    
            File file = new File(this.getDataFolder() + File.separator + "Friends.txt");
    
            if (!file.exists()) {
    
                try {
                    file.createNewFile();
                } catch (IOException ex) {
                    System.out.println("[FriendsList] Error creating Friends.txt");
                    ex.printStackTrace();
                }
                BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                bw.write("stuff");
                bw.close();
            }
    
        }
    
        /**
         * Help Message
        **/
        public void helpMessage(CommandSender cs) {
    
            cs.sendMessage(ChatColor.GOLD + "========= xFriends =========");
            cs.sendMessage(ChatColor.GREEN + "/addfriend - Add a friend to your friends list.");
            cs.sendMessage(ChatColor.GREEN + "/removefriend - Remove some from your friends list.");
            cs.sendMessage(ChatColor.GREEN + "/mailbox view - Shows the content of your mailbox");
            cs.sendMessage(ChatColor.GREEN + "/mailbox empty - Emptys the content of your mailbox");
            cs.sendMessage(ChatColor.GREEN + "/M2AF - Enable sending of messages to friends.");
            cs.sendMessage(ChatColor.GOLD + "");
    
        }
        // converts a string into a player
        public Player stringToPlayer(String player) {
            return this.getServer().getPlayer(player);
        }
        
        /**
         * mcMMO Setup
         **/
        public mcMMO mcmmo = null;
        public boolean setupMcmmo() {
    
            Plugin p = this.getServer().getPluginManager().getPlugin("mcMMO");
    
            if (p !=null) {
                mcmmo = (mcMMO)p;
                System.out.println("[FriendsList] mcMMO has been detected!");
                // if plugin "mcMMO" does exist then cast the mcmmo plugins over to mcmmo
            }
            return false;
        }
        public mcMMO getMcmmo() {
            return mcmmo;
            // returns mcmmo plugin
        }
     
        /*
         * Heroes setup
         */
        public Heroes heroes = null;
        public boolean setupHeroes() {
    
            Plugin p = this.getServer().getPluginManager().getPlugin("Heroes");
    
            if (p != null) {
                heroes = (Heroes)p;
                System.out.println("[FriendsList] Heroes has been detected!");
                // if plugin "Heroes" does exist then cast the heroes plugin over to heroes
            }
            return false;
        }
        public Heroes getHeroes() {
                return heroes;
                // returns heroes plugin
        }
    
        @SuppressWarnings("unchecked")
        public void sendMessageToAllFriends(Player p, String msg) {
    
            p = this.getServer().getPlayer(p.toString());
            List<String> f = getConfig().getList("Friends." + p.toString());
    
            p.sendMessage("A message has been sent to your friends");
    
            for (String player : f) {
                Player pl = this.stringToPlayer(player);
    
            if (pl.isOnline()) {
                pl.sendMessage(msg);
            } else {
                p.sendMessage(ChatColor.BLUE + "The following players are offline and cannot recieve your message");
    
                for (int x=0 ; x<= f.size() ; x++) {
                    p.sendMessage(pl.toString() + ChatColor.GREEN + ", ");
                    }
                }
            }
        }
    }
     
  2. Offline

    DDoS

    Create a new YamlConfiguration object, set it's data, and save it. A file will automatically be created.

    Code:
    YamlConfiguration config2 = new YamlConfiguration();
    config2.save("plugins/yourPlugin/config2.yml");
     
  3. Offline

    thehutch

    this doenst work :(
    Code:
    FileConfiguration config2 = new FileConfiguration();
     
  4. Offline

    DDoS

    Sorry for the double post, but I'm having the weirdest bug right now, the formatting for my post above is going crazy!

    Also, what's up with these null checks?

    Code:
    if (configFile == null)
    {
      config.load(getResource("config.yml"));
      config.save(configFile);
    }
    configFile won't be null since your set set it's data with:

    Code:
    configFile = new File(getDataFolder(), "config.yml");
     
  5. Offline

    thehutch

    Well this is what it says to do in this tutorial :p
    http://forums.bukkit.org/threads/bukkits-yaml-configuration-tutorial.42770/
     
  6. Offline

    Sagacious_Zed Bukkit Docs

  7. Offline

    coldandtired

    Couldn't you just save them to an XML file?
     
  8. Offline

    thehutch

    I am just starting on my database knowledge so atm I am starting with flatfile :p and this is my mainlcass @Sagacious_Zed
    Code:
    public class TheSocialNetwork extends JavaPlugin {
     
        public FileConfiguration config = null;
        public FileConfiguration friends = null;
        public FileConfiguration ignorelist = null;
        public FileConfiguration mailbox = null;
    
        public File configFile = new File(getDataFolder(), "config.yml");
        public File friendsFile = new File(getDataFolder(), "friends.yml");
        public File ignorelistFile = new File(getDataFolder(), "ignorelist.yml");
        public File mailboxFile = new File(getDataFolder(), "mailbox.yml");
       
        /**
         * Variables
        **/
    
        @Override
        public void onDisable() {
            System.out.println("[TheSocialNetwork] Disabled Version: " + getDescription().getVersion());
        }
    
        @Override
        public void onEnable() {
    
            setupMcmmo();
            setupHeroes();
            /*
             * Register Commands
             */
            getCommand("xFriends").setExecutor(new AddFriendCommands(this));
            getCommand("mailbox").setExecutor(new MailBoxCommands(this));
            PluginManager pm = getServer().getPluginManager();
            /*
             * Player Listener Events
             */
            pm.registerEvent(Event.Type.PLAYER_INTERACT_ENTITY, new Plistener(this), Event.Priority.Normal, this);
            pm.registerEvent(Event.Type.PLAYER_LOGIN, new Plistener(this), Event.Priority.Normal, this);
            pm.registerEvent(Event.Type.PLAYER_JOIN, new Plistener(this), Event.Priority.Normal, this);
            /*
             * Custom Events
             */
            pm.registerEvent(Event.Type.CUSTOM_EVENT, new HeroesListener(this), Event.Priority.Normal, this);
            System.out.println("[TheSocialNetwork] Enabled version: " + getDescription().getVersion());
            System.out.println("[TheSocialNetwork] created by " + getDescription().getAuthors());
        }
    
        public FileConfiguration getFile(FileConfiguration Yfile, File file, String filepath) {
            if (file == null) {
                reloadFile(Yfile, file, filepath);
            }
            return Yfile;
        }
    
        public void reloadFile(FileConfiguration Yfile, File file1, String filename) {
            Yfile = YamlConfiguration.loadConfiguration(file1);
    
            InputStream defConfigStream = getResource(filename);
            if (defConfigStream !=null) {
                YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
                Yfile.setDefaults(defConfig);
            }
        }
    
        public void saveFile(File file) {
            try {
                config.save(file);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
     
  9. Offline

    Sagacious_Zed Bukkit Docs

    Your saveFile is wrong.
    What you are doing is saving config to file
     
  10. Offline

    PatrickFreed

    Example of loading
    PHP:
    YamlConfiguration config YamlConfiguration.load("plugins/dir/config.yml");
    List<
    String> list = config.getStringList("path.to.node");
    System.out.println(list.get(0));
    Example of saving
    PHP:
    config.save(new File("plugins/DirectoryName/config.yml"));
     
  11. Offline

    thehutch

    @Sagacious_Zed this is from your tutorial :p and so im asking is everthing there ok except for that little problem?
    And @PatrickFreed is this method doesnt work does your method support multiple files and also there isnt a "getStringList()" method anymore :(
     
  12. Offline

    PatrickFreed

    Yes it does support multiple files, just change it in the args of YamlConfiguration.load()
    Also, to get the list, use getList() instead.

    Finally, the javadocs are your friend/
     
Thread Status:
Not open for further replies.

Share This Page