Util Making player flat-file data saving a lot easier

Discussion in 'Resources' started by Agentleader1, Sep 28, 2015.

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

    Agentleader1

    It's somewhat easy to create a flat-file and save data of a player underneath it. But it would be easier to save data under a util!

    Description
    This util allows you to save data specifically to one player's flat file according to their UUID. If they change their username, all the data will still be saved. It even creates the file for you! An additional feature to this util is that you can save inventories and locations!

    Source Code
    Code:
    package com.agentleader1.darkthunder.managers;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.List;
    import java.util.UUID;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Location;
    import org.bukkit.OfflinePlayer;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.PlayerInventory;
    
    import com.agentleader1.darkthunder.Hub;
    
    /**
    *
    * @author Agentleader1
    *
    */
    public final class ConfigManager {
      
        private UUID uid;
        private FileConfiguration config;
        private File file;
      
        public ConfigManager(Player player) {
            this.uid = player.getUniqueId();
            init();
        }
      
        public ConfigManager(OfflinePlayer player) {
            this.uid = player.getUniqueId();
            init();
        }
      
        public ConfigManager(UUID uid) {
            this.uid = uid;
            init();
        }
      
        public UUID getUUID() { return uid; }
        public OfflinePlayer getPlayer() { return Bukkit.getOfflinePlayer(getUUID()); }
        public FileConfiguration getConfig() { return config; }
        public File getFile() { return file; }
      
        public boolean exists() { return file.exists(); }
        public boolean hasStats() { return exists(); }
      
        private synchronized void init() {
            this.file = new File(Hub.instance.getDataFolder() + File.separator + "userdata" + File.separator + uid.toString() + ".yml");
            if (!exists()) {
                Hub.instance.getLogger().info("No config file, setting up for you now!");
                try {
                    file.createNewFile();
                } catch (IOException e) {}
                this.config = YamlConfiguration.loadConfiguration(getFile());
                setup();
            }
            this.config = YamlConfiguration.loadConfiguration(getFile());
        }
      
        /*
         *
         * Do some default setting up here.
         * Set the default values of the config.
         *
         */
        public void setup() {
            //Example:
            //Default value of alex_swag_level of a player's user data file should be 9001.0.
            //config.set("alex_swag_level", 9001.0D);
          
          
          
          
          
          
        }
      
        public synchronized void save() {
            try {
                config.save(file);
            } catch (IOException e) {}
        }
      
        public boolean hasStat(String path) { return config.contains(path); }
        public boolean hasPath(String path) { return hasStat(path); }
      
        public double getDouble(String path) { if (hasStat(path)) return config.getDouble(path); else return 0.0D; }
      
        public boolean getBoolean(String path) { if (hasStat(path)) return config.getBoolean(path); else return false; }
      
        public int getInteger(String path) { if (hasStat(path)) return config.getInt(path); else return 0; }
      
        public String getString(String path) { if (hasStat(path)) return config.getString(path); else return ""; }
      
        @SuppressWarnings("unchecked")
        public Inventory getInventory(String path) { if (hasStat(path)) return parseInventory((List<ItemStack>) config.getList(path)); else return null; }
      
        public Object get(String path) { if (hasStat(path)) return config.get(path); else return null; }
      
        public Location getLocation(String path) {
            if (hasStat(path)) {
                return parseLocation(config.getString(path));
            } else {
                return null;
            }
        }
      
        public void set(String path, Object obj) {
            if (obj instanceof Location) {
                String str = "";
                str += ((Location) obj).getWorld().getName();
                str += "," + ((Location) obj).getX();
                str += "," + ((Location) obj).getY();
                str += "," + ((Location) obj).getZ();
                set(path, str);
            } else if (obj instanceof Inventory) {
                List<ItemStack> items = Arrays.asList(((Inventory) obj).getContents());
                if (obj instanceof PlayerInventory) {
                    items.add(0, ((PlayerInventory) obj).getHelmet());
                    items.add(1, ((PlayerInventory) obj).getChestplate());
                    items.add(2, ((PlayerInventory) obj).getLeggings());
                    items.add(3, ((PlayerInventory) obj).getBoots());
                }
                set(path, items);
            } else {
                config.set(path, obj);
            }
        }
      
        public JavaDataType parseType(String path) {
            if (hasPath(path)) {
                if (config.isBoolean(path)) {
                    return JavaDataType.BOOLEAN;
                } else if (config.isColor(path)) {
                    return JavaDataType.COLOR;
                } else if (config.isConfigurationSection(path)) {
                    return JavaDataType.CONFIG_SECTION;
                } else if (config.isDouble(path)) {
                    return JavaDataType.DOUBLE;
                } else if (config.isInt(path)) {
                    return JavaDataType.INTEGER;
                } else if (config.isItemStack(path)) {
                    return JavaDataType.ITEM_STACK;
                } else if (config.isList(path)) {
                    return JavaDataType.LIST;
                } else if (config.isSet(path)) {
                    return JavaDataType.SET;
                } else if (config.isLong(path)) {
                    return JavaDataType.LONG;
                } else if (config.isString(path)) {
                    return JavaDataType.STRING;
                } else if (config.isVector(path)) {
                    return JavaDataType.VECTOR;
                } else {
                    return JavaDataType.OFFLINE_PLAYER;
                }
            } else {
                return JavaDataType.UNKNOWN;
            }
        }
      
        public enum JavaDataType {
            STRING,
            INTEGER,
            DOUBLE,
            FLOAT,
            LIST,
            LONG,
            BOOLEAN,
            COLOR,
            CONFIG_SECTION,
            OFFLINE_PLAYER,
            SET,
            ITEM_STACK,
            VECTOR,
            UNKNOWN
        }
      
        private Location parseLocation(String location) {
            String[] args = location.split(",");
            return new Location(Bukkit.getWorld(args[0]), Double.parseDouble(args[1]), Double.parseDouble(args[2]), Double.parseDouble(args[3]));
        }
      
        private Inventory parseInventory(List<ItemStack> items) {
            Inventory inv = Bukkit.createInventory(null, getHigherDivisible(items.size(), 9), "");
            for (ItemStack item : items) {
                inv.addItem(item);
            }
            return inv;
        }
      
        private int getHigherDivisible(int divis, int divide) {
            return ((divis) + (divis % divide));
        }
    }
    
    Instantiating/Using it
    To begin (open)

    Code:
    Player swaggest = Bukkit.getPlayer("Shotgun_master");
    ConfigManager config = new ConfigManager(swaggest);
    //Also works with UUIDs and Offline Players.

    Saving Basic Data (open)

    Code:
    //normal methods from FileConfiguration
    int swagLevel = config.getInteger("swagLevel");
    swagLevel += 9001;
    config.set("swagLevel", swagLevel);
    
    //saving locations
    config.set("lastLocation", player.getLocation());
    
    //saving inventories
    config.set("lastInv", player.getInventory());


    Warnings
    Location saving and inventory saving has been untested. Location saving is likely to work however I am unsure of inventory saving.
     
    ChipDev likes this.
  2. Offline

    Tecno_Wizard

    @Agentleader1, switch statements and ternary are badly needed here. In addition, I feel that this is just an API over an API.

    Regardless, it's a well thought out idea with room for improvement. I have a similar structure in my plugins designed for cacheing that data as well.
     
  3. Offline

    Totom3

    Why didn't you test your own API before posting it? It seems to me like one of the most obvious things to do... You may be distributing broken code right now.

    Also, what's the difference between hasStat() and hasPath()?
     
  4. Offline

    FisheyLP

    Why should I use this over bukkits built in config api?
     
  5. Offline

    Agentleader1

    @FisheyLP The advantage of using this over setting things yourself is that it helps create player flat files easier. When you create player flat filing, it takes extra lines by checking if the file exists, then creating it, then loading it. And when someone comes on, it's some work to re-create the FileConfiguration instance.
     
Thread Status:
Not open for further replies.

Share This Page