Weird config loading bug.

Discussion in 'Plugin Development' started by PragmaticObject, Aug 24, 2014.

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

    PragmaticObject

    I am developing a private plugin for someone and whenever I load an item that has damage values, and I put 35:14, it will show up as 2114 in the console. However when I put wool:14 it works fine and parses the integer correctly.

    I don't get why it's doing this. Here is my KitManager.java:
    Code:
    package com.tri_voltage.ak.kits;
     
    import java.util.List;
     
    import org.bukkit.ChatColor;
    import org.bukkit.Color;
    import org.bukkit.Material;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerCommandPreprocessEvent;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.inventory.meta.LeatherArmorMeta;
     
    import com.tri_voltage.ak.util.Tools;
     
    public class KitManager implements Listener {
     
        private Kit[] kits;
       
        private String kitCommand;
       
        private boolean enabled, debug;
       
       
        public KitManager() {
           
        }
     
        public void load() {
            enabled = Tools.getKits().getBoolean("auto-kits-enabled");
            debug = Tools.getKits().getBoolean("debug-enabled");
            kitCommand = Tools.getKits().getString("kit-command").toLowerCase();
            if (!kitCommand.contains("/"))
                setKitCommand("/" + kitCommand.toLowerCase());
            loadKitsFromConfig(Tools.getKits());
        }
       
        private void loadKitsFromConfig(YamlConfiguration config) {
            if (!enabled)
                return;
            int i = 0;
            int loadedKits = 0;
            kits = new Kit[config.getConfigurationSection("kits").getKeys(false).size()];
            Tools.logInfo("Loading " + kits.length + " AutoKit(s)..");
            for (String key : config.getConfigurationSection("kits").getKeys(false)) {
                try {
                    loadedKits ++;
                    kits[i] = new Kit(key, config.getString("kits." + key + ".permission"), construcItemList(config, "kits." + key + ".items"), constructStringList(config, "kits." + key + ".names"), constructStringList(config, "kits." + key + ".slot-types"), constructAmountList(config, "kits." + key + ".amounts"));
                } catch (Exception e) {
                    loadedKits --;
                    Tools.logSevere("Failed to load kit: \"" + key.toUpperCase() + "\"!");
                    if (debug)
                        e.printStackTrace();
                }
                i ++;
            }
            Tools.logInfo("Loaded " + loadedKits + " AutoKit(s)!");
        }
       
       
        @SuppressWarnings("deprecation")
        private void giveKit(Player p, Kit k) {
            Material m = null;
            String slotType;
            short durability = 0;
            int red = 0, green = 0, blue = 0;
            boolean hasDurability = false, hasColor = false;
            for (int i = 0; i < k.getItems().length; i ++) {
                try {
                    slotType = k.getSlotTypes()[i];
                    if (k.getItems()[i].contains(":")) {
                        if (k.getItems()[i].contains(",")) {
                            m = Material.getMaterial(Integer.parseInt(k.getItems()[i].split(":")[0]));
                            hasColor = true;
                            try {
                                String rgbCode = k.getItems()[i].replaceAll(m.getId() + ":", "");
                                red = Integer.parseInt(rgbCode.split(",")[0]);
                                green = Integer.parseInt(rgbCode.split(",")[1]);
                                blue = Integer.parseInt(rgbCode.split(",")[2]);
                            } catch (Exception e) {
                                Tools.logWarning("Invalid RGB scale at \"" + k.getItems()[i] + "\"!");
                            }
                        } else {
                            m = Material.getMaterial(Integer.parseInt(k.getItems()[i].split(":")[0]));
                            durability = Short.parseShort(k.getItems()[i].split(":")[1]);
                            hasDurability = true;
                        }
                    } else {
                        m = Material.getMaterial(Integer.parseInt(k.getItems()[i]));
                    }
                } catch (NumberFormatException e) {
                    Tools.logSevere("Failed giving Player: \"" + p.getName() + "\" item ID:" + k.getItems()[i] + "!");
                    if (debug)
                        e.printStackTrace();
                    return;
                }
                if (m != null) {//give player accepted kit items.
                    ItemStack itemStack = null;
                    if (hasDurability)
                        itemStack = new ItemStack(m, k.getAmounts()[i], (short) durability);
                    else
                        itemStack = new ItemStack(m, k.getAmounts()[i]);
                    if (!k.getCustomNames()[i].equalsIgnoreCase("DEFAULT")) {
                        ItemMeta itemMeta = itemStack.getItemMeta();
                        itemMeta.setDisplayName(replaceCodes(k.getCustomNames()[i]));
                        itemStack.setItemMeta(itemMeta);
                    }
                    if (hasColor)
                        try {
                            LeatherArmorMeta itemMeta = (LeatherArmorMeta) itemStack.getItemMeta();
                            itemMeta.setColor(Color.fromRGB(red, green, blue));
                            itemStack.setItemMeta(itemMeta);
                        } catch (Exception e) {
                            Tools.logWarning("Failed to set color for item ID:" + k.getItems()[i] + "!");
                            if (debug)
                                e.printStackTrace();
                        }
                    slotType = slotType.toUpperCase();
                    switch(slotType) {
                    case "NONE":
                        p.getInventory().addItem(itemStack);
                        break;
                    case "CAP":
                        p.getInventory().setHelmet(itemStack);
                        break;
                    case "TUNIC":
                        p.getInventory().setChestplate(itemStack);
                        break;
                    case "PANTS":
                        p.getInventory().setLeggings(itemStack);
                        break;
                    case "HELMET":
                        p.getInventory().setHelmet(itemStack);
                        break;
                    case "CHESTPLATE":
                        p.getInventory().setChestplate(itemStack);
                        break;
                    case "LEGGINGS":
                        p.getInventory().setLeggings(itemStack);
                        break;
                    case "BOOTS":
                        p.getInventory().setBoots(itemStack);
                        break;
                    default:
                        p.getInventory().addItem(itemStack);
                        break;
                    }
                    hasDurability = false;
                    hasColor = false;
                }
            }
        }
       
        /**
        * Replaces all of the lines (line) within the file containing key symbols that resemble a format code.
        * @param line
        * @return The correct formatted line.
        */
        public String replaceCodes(String line) {
            if (line != null) {
                line = line.replaceAll("&0", ChatColor.BLACK + "");
                line = line.replaceAll("&1", ChatColor.DARK_BLUE + "");
                line = line.replaceAll("&2", ChatColor.DARK_GREEN + "");
                line = line.replaceAll("&3", ChatColor.DARK_AQUA + "");
                line = line.replaceAll("&4", ChatColor.DARK_RED + "");
                line = line.replaceAll("&5", ChatColor.DARK_PURPLE + "");
                line = line.replaceAll("&6", ChatColor.GOLD + "");
                line = line.replaceAll("&7", ChatColor.GRAY + "");
                line = line.replaceAll("&8", ChatColor.DARK_GRAY + "");
                line = line.replaceAll("&9", ChatColor.BLUE + "");
                line = line.replaceAll("&a", ChatColor.GREEN + "");
                line = line.replaceAll("&b", ChatColor.AQUA + "");
                line = line.replaceAll("&c", ChatColor.RED + "");
                line = line.replaceAll("&d", ChatColor.LIGHT_PURPLE + "");
                line = line.replaceAll("&e", ChatColor.YELLOW + "");
                line = line.replaceAll("&f", ChatColor.WHITE + "");
                line = line.replaceAll("&l", ChatColor.BOLD + "");
                line = line.replaceAll("&k", ChatColor.MAGIC + "");
                line = line.replaceAll("&n", ChatColor.UNDERLINE + "");
                line = line.replaceAll("&r", ChatColor.RESET + "");
            }
            return line;
        }
       
        private int getColorID(String color) {
            color = color.toUpperCase();
            switch (color) {
            case "BLACK":
                return 15;
            case "RED":
                return 14;
            case "GREEN":
                return 13;
            case "BROWN":
                return 12;
            case "BLUE":
                return 11;
            case "PURPLE":
                return 10;
            case "CYAN":
                return 9;
            case "LIGHT_GRAY":
                return 8;
            case "GRAY":
                return 7;
            case "PINK":
                return 6;
            case "LIME_GREEN":
                return 5;
            case "LIGHT_GREEN":
                return 5;
            case "YELLOW":
                return 4;
            case "LIGHT_BLUE":
                return 3;
            case "MAGENTA":
                return 2;
            case "ORANGE":
                return 1;
            default:
                return -1;
            }
        }
       
        @SuppressWarnings("deprecation")
        private int getItemID(String item) {
            return Material.getMaterial(item.toUpperCase()).getId();
        }
     
        private String[] construcItemList(YamlConfiguration config, String path) {
            List<String> list = config.getStringList(path);
            String[] durabilityValue = new String[list.size()];
            String[] convertedList = new String[list.size()];
            for (int i = 0; i < list.size(); i ++) {
                if (list.get(i).contains(":")) {
                    System.out.println("ITEM: " + list.get(i).split(":")[0] + " CONTAINS :");
                    if (list.get(i).contains(",")) {
                        convertedList[i] = list.get(i).split(":")[0];
                        String rgbCode = list.get(i).replaceFirst(convertedList[i] + ":", "");
                        if (!isNumeric(convertedList[i]))
                            convertedList[i] = getItemID(convertedList[i].toUpperCase()) + "";
                        convertedList[i] = convertedList[i] + ":" + rgbCode;
                    } else {
                        System.out.println("ITEM: " + list.get(i).split(":")[0] + " HAS NO RGB");
                        convertedList[i] = list.get(i).split(":")[0];
                        durabilityValue[i] = list.get(i).split(":")[1];
                        if (!isNumeric(durabilityValue[i]))
                            durabilityValue[i] = getColorID(durabilityValue[i].toUpperCase()) + "";
                        if (!isNumeric(convertedList[i]))
                            convertedList[i] = getItemID(convertedList[i].toUpperCase()) + "";
                        convertedList[i] = convertedList[i] + ":" + durabilityValue[i];
                    }
                } else {
                    System.out.println("ITEM: " + list.get(i) + " HAS NO DAMAGE");
                    convertedList[i] = list.get(i);
                    if (!isNumeric(convertedList[i]))
                        convertedList[i] = getItemID(convertedList[i].toUpperCase()) + "";
                }
                System.out.println(convertedList[i]);
            }
            return convertedList;
        }
     
        private int[] constructAmountList(YamlConfiguration config, String path) {
            List<String> list = config.getStringList(path);
            int[] convertedList = new int[list.size()];
            for (int i = 0; i < list.size(); i ++)
                convertedList[i] = Integer.parseInt(list.get(i));
            return convertedList;
        }
     
        private String[] constructStringList(YamlConfiguration config, String path) {
            List<String> list = config.getStringList(path);
            return list.toArray(new String[list.size()]);
        }
       
        public static boolean isNumeric(String str) {
            try {
                @SuppressWarnings("unused")
                double d = Double.parseDouble(str);
                return true;
            } catch(NumberFormatException e) {
                return false;
            }
        }
       
        @EventHandler
        private void giveKitOnSpawn(PlayerCommandPreprocessEvent event) {
            Player p = event.getPlayer();
            if (event.getMessage().toLowerCase().startsWith(kitCommand)) {
                try {
                    for (int i = 0; i < kits.length; i ++)
                        try {
                            if (p.hasPermission(kits[i].getPermission()) || p.hasPermission("ak.*"))
                                giveKit(p, kits[i]);
                        } catch (Exception e) {
                            Tools.logSevere("Failed giving Player: \"" + p.getName() + "\" kit: \"" + kits[i].getName().toUpperCase() + "\"!");
                            if (debug)
                                e.printStackTrace();
                        }
                } catch (Exception e) {
                    Tools.logSevere("Failed searching for possible kits for Player: \"" + p.getName() + "\"!");
                    if (debug)
                        e.printStackTrace();
                }
            }
        }
       
     
        /**
        * @return the kits
        */
        public Kit[] getKits() {
            return kits;
        }
     
     
        /**
        * @param kits the kits to set
        */
        public void setKits(Kit[] kits) {
            this.kits = kits;
        }
     
     
        /**
        * @return the enabled
        */
        public boolean isEnabled() {
            return enabled;
        }
     
     
        /**
        * @param enabled the enabled to set
        */
        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
     
        /**
        * @return the kitCommand
        */
        public String getKitCommand() {
            return kitCommand;
        }
     
        /**
        * @param kitCommand the kitCommand to set
        */
        public void setKitCommand(String kitCommand) {
            this.kitCommand = kitCommand;
        }
       
    }
    
    The problem exists in the constructItemList() method.

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

    DevSock

    PragmaticObject I'm heading out currently, so I can't take the time to solve the whole issue. But I noticed you're doing an extremely long and over-written way of turning "&" into ChatColor codes. Here is a much quicker way to do it.

    Code:java
    1. public String changeColors(String string){
    2. return ChatColor.translateAlternateColorCodes('&', string);
    3. }
     
    PragmaticObject likes this.
  3. Offline

    PragmaticObject

    Appreciate it! Will change it
     
Thread Status:
Not open for further replies.

Share This Page