YamlConfiguration Methods Returning Null

Discussion in 'Plugin Development' started by KingOfTheEast01, Nov 10, 2017.

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

    KingOfTheEast01

    Hey guys,
    My name is Lucas. I've been having some trouble with a plugin of mine for some time, and can't seem to find the issue. I was hoping you all could provide some sort of help or answer.

    My problem is with the ConfigurationSection interface. I created a new YamlConfiguration file and am attempting to get the keys of a ConfigurationSection within it. Here's the file:

    warps.yml (open)

    Warps:
    Example Warp:
    Group: Example
    X: 1
    Pitch: 0
    Y: 2
    Z: 3
    Yaw: 0


    I'm trying to obtain the string "Example Warp" in a list of Strings of all the keys to the "Warps" ConfigurationSection. However, when I attempt to obtain the Map of values in the section, or even its keys, I get an NPE, which is quite frustrating, but I think I know why I'm getting it. The two methods I tried using, #getValues() and #getKeys(), return the values of a Map<String, Object>, however each key points to another ConfigurationSection, or another Map<String, Object>, which isn't being passed as the Object in the first map. I just want to get a list of all the keys in the "Warps" ConfigurationSection as some sort of set of strings, be it an actual Set or List.

    Here's a look at all the methods I tried experimenting with:
    Code:
    ConfigurationSection warps = configYAML.getConfigurationSection("Warps");
    //                    Set<String> warpNames = warps.getValues(true).keySet();
    //                    Map<String, Object> warpList = warps.getValues(true);
    //                    Set<String> warpNames = warps.getKeys(true);
    //                    Map<String, Object> warpList = configYAML.getValues(true);
    //                    Map<String, Object> warpList = (Map<String, Object>) warps.get("Warps");
    Ignore the different variable names, as they're all to be used for the same purpose, however they all return null.

    Any help that can be provided is much appreciated. Thank you
    -Lucas
     
  2. Offline

    MightyOne

    @KingOfTheEast01 couldnt it be possible that anything is wrong with you configYAML? Post the whole code of the class.
     
  3. Offline

    RunsWithShovels

    @KingOfTheEast01

    pseudo code

    set<string> configsection = how.you.get.your.file.instance.getConfigSection("Warps").getkeys(false)
     
  4. Offline

    KingOfTheEast01

    I already tried that method. Please look at all the ones I used.

    Here is the full class. Some of it is commented out, as it requires some variables, which I am trying to create where I was testing out different methods, which is the code I already posted.

    Code:
    package me.callmefilms.GroupWarps;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Location;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.ConfigurationSection;
    import org.bukkit.configuration.InvalidConfigurationException;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.Player;
    
    import net.milkbowl.vault.Vault;
    import net.milkbowl.vault.chat.plugins.Chat_DroxPerms.PermissionServerListener;
    import net.milkbowl.vault.permission.Permission;
    
    public class Commands implements CommandExecutor {
    
        @Override
        public boolean onCommand(CommandSender sndr, Command cmd, String label, String[] args) {
            if(!(sndr instanceof Player)) {
                sndr.sendMessage("That command can not be executed by console personnel. Please try again in-game.");
            } else {
                Player player = (Player) sndr;
                Permission perms = GWFront.getPermissions();
                String[] playerGroups = perms.getPlayerGroups(player);
                File config = new File(Bukkit.getServer().getPluginManager().getPlugin("GroupWarps").getDataFolder() + "\\config.yml");
                YamlConfiguration configYAML = new YamlConfiguration();
                try {
                    configYAML.load(config);
                } catch (IOException | InvalidConfigurationException e) {
                    e.printStackTrace();
                }
                Map<String, Object> groups = configYAML.getConfigurationSection("Warp Limits").getValues(false);
                File warpFile = new File(Bukkit.getServer().getPluginManager().getPlugin("GroupWarps").getDataFolder() + "\\warps.yml");
                YamlConfiguration warpsYAML = new YamlConfiguration();
                try {
                    warpsYAML.load(warpFile);
                } catch (IOException | InvalidConfigurationException e) {
                    e.printStackTrace();
                }
                switch(cmd.getName()) {
                case "setwarp":
                    if(args.length < 1) {
                        System.out.println("Correct usage: /setwarp <name>");
                    } else {
                        String highest = getHighestGroup(player);
                        ConfigurationSection warps = configYAML.getConfigurationSection("Warps");
    //                    Set<String> warpNames = warps.getValues(true).keySet();
    //                    Map<String, Object> warpsNames = warps.getValues(true);
    //                    Set<String> warpNames = warps.getKeys(true);
    //                    Map<String, Object> warps = configYAML.getValues(true);
    //                    Map<String, Object> warpList = (Map<String, Object>) warps.get("Warps");
    //                    List<String> warpNames = new ArrayList<String>();
    //                    for(String targWarp : warpNames) {
    //                        if(!(warps.getConfigurationSection(targWarp).get("Group") == highest)) {
    //                            warpNames.remove(targWarp);
    //                        }
    //                    }
    //                    int max = (int) groups.get(highest);
    //                    if(warpNames.size() == max) {
    //                        System.out.println("Your group can not add any more warps.");
    //                    } else {
    //                        Map<String, Object> warpInfo = new HashMap<String, Object>();
    //                        Location warpLoc = player.getLocation();
    //                        warpInfo.put("Group", highest);
    //                        warpInfo.put("X", warpLoc.getX());
    //                        warpInfo.put("Y", warpLoc.getY());
    //                        warpInfo.put("Z", warpLoc.getZ());
    //                        warpInfo.put("Yaw", warpLoc.getYaw());
    //                        warpInfo.put("Pitch", warpLoc.getPitch());
    //                        warps.set(args[0], warpInfo);
    //                        System.out.println("Set warp at " + warpLoc.getX() + ", " + warpLoc.getY() + ", " + warpLoc.getZ());
    //                    }
                    }
                }
            }
            return true;
        }
       
        static public String getHighestGroup(Player player) {
            Permission perms = GWFront.getPermissions();
            String[] playerGroups = perms.getPlayerGroups(player);
            File config = new File(Bukkit.getServer().getPluginManager().getPlugin("GroupWarps").getDataFolder() + "\\config.yml");
            YamlConfiguration configYAML = new YamlConfiguration();
            try {
                configYAML.load(config);
            } catch (IOException | InvalidConfigurationException e) {
                e.printStackTrace();
            }
            Map<String, Object> groups = configYAML.getConfigurationSection("Warp Limits").getValues(false);
            List<Integer> limits = new ArrayList<Integer>();
            for(String targGroup : playerGroups) {
                if(groups.containsKey(targGroup)) {
                    limits.add((Integer) groups.get(targGroup));
                }
            }
            int max = Collections.max(limits);
            for(String targGroup : groups.keySet()) {
                if(groups.get(targGroup) == (Object) max) {
                    return targGroup;
                }
            }
            return null;
        }
       
    }
    
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
  5. Offline

    RunsWithShovels

    I have, though its the correct one. Please post your whole class, as the error has to be coming from that.

    * Edit
    1. using the separator \\ in your file path isn't a good practice. Use + file.separator + so that it places what system it's being ran on in there.
    2. Are you able to write information to the file?
     
    Last edited: Nov 10, 2017
  6. Offline

    KingOfTheEast01

    1. Thanks. I'll go ahead and make that change.
    2. Yes, I did so in my onEnable() method. I'll paste it below.

    Code:
    package me.callmefilms.GroupWarps;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.logging.Logger;
    
    import net.milkbowl.vault.chat.Chat;
    import net.milkbowl.vault.economy.Economy;
    import net.milkbowl.vault.permission.Permission;
    
    import org.bukkit.Bukkit;
    import org.bukkit.configuration.Configuration;
    import org.bukkit.configuration.InvalidConfigurationException;
    import org.bukkit.configuration.MemoryConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.plugin.RegisteredServiceProvider;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class GWFront extends JavaPlugin {
       
        private static final Logger log = Logger.getLogger("Minecraft");
        private static Economy econ = null;
        private static Permission perms = null;
        private static Chat chat = null;
    
        @Override
        public void onDisable() {
            log.info(String.format("[%s] Disabled Version %s", getDescription().getName(), getDescription().getVersion()));
        }
    
        @Override
        public void onEnable() {
            if (!setupEconomy() ) {
                log.severe(String.format("[%s] - Disabled due to no Vault dependency found!", getDescription().getName()));
                getServer().getPluginManager().disablePlugin(this);
                return;
            }
            setupPermissions();
            setupChat();
            if(this.getDataFolder().exists()) {
                log.info("Successfully found data folder...");
            }
            else {
                log.info("Data folder does not exist...");
                log.info("Creating a data folder...");
                this.getDataFolder().mkdir();
                log.info("Created data folder...");
            }
            File config = new File(this.getDataFolder().getPath() + File.separator + "config.yml");
            if(config.exists()) {
                log.info("Found config file...");
            } else {
                log.info("Config file does not exist...");
                log.info("Creating config file...");
                try {
                    config.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                log.info("Created config file...");
                }
            YamlConfiguration configYAML = new YamlConfiguration();
            configYAML.createSection("Warp Limits");
            configYAML.set("Warp Limits.Example", 3);
            try {
                configYAML.save(config);
                } catch (IOException e) {
                    e.printStackTrace();
                    }
            try {
                configYAML.load(config);
                } catch (IOException | InvalidConfigurationException e) {
                    e.printStackTrace();
                    }
            File warps = new File(this.getDataFolder().getPath() + File.separator + "warps.yml");
            if(warps.exists()) {
                log.info("Found warps file...");
            } else {
                log.info("Warps file does not exist...");
                log.info("Creating warps file...");
                try {
                    warps.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                log.info("Created warps file...");
            }
            YamlConfiguration warpsYAML = new YamlConfiguration();
            warpsYAML.createSection("Warps");
            Map<String, Object> exWarpInfo = new HashMap<String, Object>();
            exWarpInfo.put("Group", "Example");
            exWarpInfo.put("X", 1);
            exWarpInfo.put("Y", 2);
            exWarpInfo.put("Z", 3);
            exWarpInfo.put("Yaw", 0);
            exWarpInfo.put("Pitch", 0);
            warpsYAML.set("Warps.Example Warp", exWarpInfo);
    //      warpsYAML.addDefault("Warps.Example Warp", exWarpInfo);
    //      warpsYAML.addDefaults(exWarpInfo);
    //      MemoryConfiguration exWarpDefs = new MemoryConfiguration();
    //      warpsYAML.setDefaults(exWarpDefs);
            try {
                warpsYAML.save(warps);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                warpsYAML.load(warps);
            } catch (IOException | InvalidConfigurationException e1) {
                e1.printStackTrace();
            }
            Bukkit.getServer().getPluginCommand("setwarp").setExecutor(new Commands());
            }
       
        private boolean setupEconomy() {
            if (getServer().getPluginManager().getPlugin("Vault") == null) {
                return false;
            }
            RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
            if (rsp == null) {
                return false;
            }
            econ = rsp.getProvider();
            return econ != null;
        }
       
        private boolean setupChat() {
            RegisteredServiceProvider<Chat> rsp = getServer().getServicesManager().getRegistration(Chat.class);
            chat = rsp.getProvider();
            return chat != null;
        }
       
        private boolean setupPermissions() {
            RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class);
            perms = rsp.getProvider();
            return perms != null;
        }
       
        public static Economy getEcononomy() {
            return econ;
        }
       
        public static Permission getPermissions() {
            return perms;
        }
       
        public static Chat getChat() {
            return chat;
        }
    }
    
    Edit: I replaced all the double black slashes with File.separator.
     
  7. Offline

    RunsWithShovels

    This!!
    ConfigurationSection warps = configYAML.getConfigurationSection("Warps");

    Should be this!!
    ConfigurationSection warps = warpsYAML.getConfigurationSection("Warps");

    NPE was due to the fact that you don't have a Warps section in the config.yml, which is what you were checking.

    Also, just a couple tips. If you're going to be using more than one yaml file, its typically good to create a ConfigManager class to handle all the get, set, and creation of the files. It would make your core code a lot less messy. And, this is just an opinion more so, but unless you're going to be using the economy or chat features of Vault, I wouldn't place the unused methods in the code. Good luck
     
    Last edited: Nov 10, 2017
  8. Offline

    KingOfTheEast01

    You're right! I can't believe I missed that! That reminds me of all the times my classmates in my coding class and I miss small things in HTML that screw up the whole look of the site.

    Anyhow, thanks for that, and I'll definitely be using a YAML file manager class of some sort in the future. In fact, you inspired a project I plan on working on next.

    Thanks for all the help! :D
    -Lucas
     
Thread Status:
Not open for further replies.

Share This Page