Search in sources :

Example 1 with KeyIntPair

use of com.archyx.aureliumskills.util.misc.KeyIntPair in project AureliumSkills by Archy-X.

the class MySqlStorageProvider method load.

@Override
public void load(Player player) {
    try {
        String query = "SELECT * FROM SkillData WHERE ID=?;";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, player.getUniqueId().toString());
            try (ResultSet result = statement.executeQuery()) {
                if (result.next()) {
                    PlayerData playerData = new PlayerData(player, plugin);
                    // Load skill data
                    for (Skill skill : Skills.values()) {
                        int level = result.getInt(skill.name().toUpperCase(Locale.ROOT) + "_LEVEL");
                        double xp = result.getDouble(skill.name().toUpperCase(Locale.ROOT) + "_XP");
                        playerData.setSkillLevel(skill, level);
                        playerData.setSkillXp(skill, xp);
                        // Add stat levels
                        plugin.getRewardManager().getRewardTable(skill).applyStats(playerData, level);
                    }
                    // Load stat modifiers
                    String statModifiers = result.getString("STAT_MODIFIERS");
                    if (statModifiers != null) {
                        JsonArray jsonModifiers = new Gson().fromJson(statModifiers, JsonArray.class);
                        for (JsonElement modifierElement : jsonModifiers.getAsJsonArray()) {
                            JsonObject modifierObject = modifierElement.getAsJsonObject();
                            String name = modifierObject.get("name").getAsString();
                            String statName = modifierObject.get("stat").getAsString();
                            double value = modifierObject.get("value").getAsDouble();
                            if (name != null && statName != null) {
                                Stat stat = plugin.getStatRegistry().getStat(statName);
                                StatModifier modifier = new StatModifier(name, stat, value);
                                playerData.addStatModifier(modifier);
                            }
                        }
                    }
                    playerData.setMana(result.getDouble("mana"));
                    // Load locale
                    String locale = result.getString("locale");
                    if (locale != null) {
                        playerData.setLocale(new Locale(locale));
                    }
                    // Load ability data
                    String abilityData = result.getString("ABILITY_DATA");
                    if (abilityData != null) {
                        JsonObject jsonAbilityData = new Gson().fromJson(abilityData, JsonObject.class);
                        for (Map.Entry<String, JsonElement> abilityEntry : jsonAbilityData.entrySet()) {
                            String abilityName = abilityEntry.getKey();
                            AbstractAbility ability = AbstractAbility.valueOf(abilityName.toUpperCase(Locale.ROOT));
                            if (ability != null) {
                                AbilityData data = playerData.getAbilityData(ability);
                                JsonObject dataObject = abilityEntry.getValue().getAsJsonObject();
                                for (Map.Entry<String, JsonElement> dataEntry : dataObject.entrySet()) {
                                    String key = dataEntry.getKey();
                                    JsonElement element = dataEntry.getValue();
                                    if (element.isJsonPrimitive()) {
                                        Object value = parsePrimitive(dataEntry.getValue().getAsJsonPrimitive());
                                        if (value != null) {
                                            data.setData(key, value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Load unclaimed items
                    String unclaimedItemsString = result.getString("UNCLAIMED_ITEMS");
                    if (unclaimedItemsString != null) {
                        List<KeyIntPair> unclaimedItems = new ArrayList<>();
                        String[] splitString = unclaimedItemsString.split(",");
                        for (String entry : splitString) {
                            String[] splitEntry = entry.split(" ");
                            String itemKey = splitEntry[0];
                            int amount = 1;
                            if (splitEntry.length >= 2) {
                                amount = NumberUtils.toInt(splitEntry[1], 1);
                            }
                            unclaimedItems.add(new KeyIntPair(itemKey, amount));
                        }
                        playerData.setUnclaimedItems(unclaimedItems);
                        playerData.clearInvalidItems();
                    }
                    playerManager.addPlayerData(playerData);
                    plugin.getLeveler().updatePermissions(player);
                    PlayerDataLoadEvent event = new PlayerDataLoadEvent(playerData);
                    new BukkitRunnable() {

                        @Override
                        public void run() {
                            Bukkit.getPluginManager().callEvent(event);
                        }
                    }.runTask(plugin);
                } else {
                    createNewPlayer(player);
                }
            }
        }
    } catch (Exception e) {
        Bukkit.getLogger().warning("There was an error loading player data for player " + player.getName() + " with UUID " + player.getUniqueId() + ", see below for details.");
        e.printStackTrace();
        PlayerData playerData = createNewPlayer(player);
        playerData.setShouldSave(false);
        sendErrorMessageToPlayer(player, e);
    }
}
Also used : AbstractAbility(com.archyx.aureliumskills.ability.AbstractAbility) StatModifier(com.archyx.aureliumskills.modifier.StatModifier) Stat(com.archyx.aureliumskills.stats.Stat) PlayerDataLoadEvent(com.archyx.aureliumskills.data.PlayerDataLoadEvent) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) IOException(java.io.IOException) Skill(com.archyx.aureliumskills.skills.Skill) KeyIntPair(com.archyx.aureliumskills.util.misc.KeyIntPair) PlayerData(com.archyx.aureliumskills.data.PlayerData) AbilityData(com.archyx.aureliumskills.data.AbilityData)

Example 2 with KeyIntPair

use of com.archyx.aureliumskills.util.misc.KeyIntPair in project AureliumSkills by Archy-X.

the class MySqlStorageProvider method save.

@Override
public void save(Player player, boolean removeFromMemory) {
    PlayerData playerData = playerManager.getPlayerData(player);
    if (playerData == null)
        return;
    if (playerData.shouldNotSave())
        return;
    try {
        StringBuilder sqlBuilder = new StringBuilder("INSERT INTO SkillData (ID, ");
        for (Skill skill : Skills.getOrderedValues()) {
            sqlBuilder.append(skill.toString()).append("_LEVEL, ");
            sqlBuilder.append(skill).append("_XP, ");
        }
        sqlBuilder.append("LOCALE, STAT_MODIFIERS, MANA, ABILITY_DATA, UNCLAIMED_ITEMS) VALUES(?, ");
        for (int i = 0; i < Skills.getOrderedValues().size(); i++) {
            sqlBuilder.append("?, ?, ");
        }
        sqlBuilder.append("?, ?, ?, ?, ?) ");
        sqlBuilder.append("ON DUPLICATE KEY UPDATE ");
        for (Skill skill : Skills.getOrderedValues()) {
            sqlBuilder.append(skill.toString()).append("_LEVEL=?, ");
            sqlBuilder.append(skill).append("_XP=?, ");
        }
        sqlBuilder.append("LOCALE=?, ");
        sqlBuilder.append("STAT_MODIFIERS=?, ");
        sqlBuilder.append("MANA=?, ");
        sqlBuilder.append("ABILITY_DATA=?, ");
        sqlBuilder.append("UNCLAIMED_ITEMS=?");
        // Enter values into prepared statement
        try (PreparedStatement statement = connection.prepareStatement(sqlBuilder.toString())) {
            statement.setString(1, player.getUniqueId().toString());
            int index = 2;
            for (int i = 0; i < 2; i++) {
                for (Skill skill : Skills.getOrderedValues()) {
                    statement.setInt(index++, playerData.getSkillLevel(skill));
                    statement.setDouble(index++, playerData.getSkillXp(skill));
                }
                statement.setString(index++, playerData.getLocale().toString());
                // Build stat modifiers json
                StringBuilder modifiersJson = new StringBuilder();
                if (playerData.getStatModifiers().size() > 0) {
                    modifiersJson.append("[");
                    for (StatModifier statModifier : playerData.getStatModifiers().values()) {
                        modifiersJson.append("{\"name\":\"").append(statModifier.getName()).append("\",\"stat\":\"").append(statModifier.getStat().toString().toLowerCase(Locale.ROOT)).append("\",\"value\":").append(statModifier.getValue()).append("},");
                    }
                    modifiersJson.deleteCharAt(modifiersJson.length() - 1);
                    modifiersJson.append("]");
                }
                // Add stat modifiers to prepared statement
                if (!modifiersJson.toString().equals("")) {
                    statement.setString(index++, modifiersJson.toString());
                } else {
                    statement.setNull(index++, Types.VARCHAR);
                }
                // Set mana
                statement.setDouble(index++, playerData.getMana());
                // Build ability json
                StringBuilder abilityJson = new StringBuilder();
                if (playerData.getAbilityDataMap().size() > 0) {
                    abilityJson.append("{");
                    for (AbilityData abilityData : playerData.getAbilityDataMap().values()) {
                        String abilityName = abilityData.getAbility().toString().toLowerCase(Locale.ROOT);
                        if (abilityData.getDataMap().size() > 0) {
                            abilityJson.append("\"").append(abilityName).append("\"").append(":{");
                            for (Map.Entry<String, Object> dataEntry : abilityData.getDataMap().entrySet()) {
                                String value = String.valueOf(dataEntry.getValue());
                                if (dataEntry.getValue() instanceof String) {
                                    value = "\"" + dataEntry.getValue() + "\"";
                                }
                                abilityJson.append("\"").append(dataEntry.getKey()).append("\":").append(value).append(",");
                            }
                            abilityJson.deleteCharAt(abilityJson.length() - 1);
                            abilityJson.append("},");
                        }
                    }
                    if (abilityJson.length() > 1) {
                        abilityJson.deleteCharAt(abilityJson.length() - 1);
                    }
                    abilityJson.append("}");
                }
                // Add ability data to prepared statement
                if (!abilityJson.toString().equals("")) {
                    statement.setString(index++, abilityJson.toString());
                } else {
                    statement.setNull(index++, Types.VARCHAR);
                }
                // Unclaimed items
                StringBuilder unclaimedItemsStringBuilder = new StringBuilder();
                List<KeyIntPair> unclaimedItems = playerData.getUnclaimedItems();
                if (unclaimedItems != null) {
                    for (KeyIntPair unclaimedItem : unclaimedItems) {
                        unclaimedItemsStringBuilder.append(unclaimedItem.getKey()).append(" ").append(unclaimedItem.getValue()).append(",");
                    }
                }
                if (unclaimedItemsStringBuilder.length() > 0) {
                    unclaimedItemsStringBuilder.deleteCharAt(unclaimedItemsStringBuilder.length() - 1);
                }
                if (!unclaimedItemsStringBuilder.toString().equals("")) {
                    statement.setString(index++, unclaimedItemsStringBuilder.toString());
                } else {
                    statement.setNull(index++, Types.VARCHAR);
                }
            }
            statement.executeUpdate();
        }
        if (removeFromMemory) {
            playerManager.removePlayerData(player.getUniqueId());
        }
    } catch (Exception e) {
        Bukkit.getLogger().warning("There was an error saving player data for player " + player.getName() + " with UUID " + player.getUniqueId() + ", see below for details.");
        e.printStackTrace();
    }
}
Also used : IOException(java.io.IOException) StatModifier(com.archyx.aureliumskills.modifier.StatModifier) Skill(com.archyx.aureliumskills.skills.Skill) KeyIntPair(com.archyx.aureliumskills.util.misc.KeyIntPair) PlayerData(com.archyx.aureliumskills.data.PlayerData) AbilityData(com.archyx.aureliumskills.data.AbilityData)

Example 3 with KeyIntPair

use of com.archyx.aureliumskills.util.misc.KeyIntPair in project AureliumSkills by Archy-X.

the class YamlStorageProvider method load.

@Override
public void load(Player player) {
    File file = new File(plugin.getDataFolder() + "/playerdata/" + player.getUniqueId() + ".yml");
    if (file.exists()) {
        FileConfiguration config = YamlConfiguration.loadConfiguration(file);
        PlayerData playerData = new PlayerData(player, plugin);
        try {
            // Make sure file name and uuid match
            UUID id = UUID.fromString(config.getString("uuid", player.getUniqueId().toString()));
            if (!player.getUniqueId().equals(id)) {
                throw new IllegalArgumentException("File name and uuid field do not match!");
            }
            // Load skill data
            for (Skill skill : Skills.values()) {
                String path = "skills." + skill.name().toLowerCase(Locale.ROOT) + ".";
                int level = config.getInt(path + "level", 1);
                double xp = config.getDouble(path + "xp", 0.0);
                playerData.setSkillLevel(skill, level);
                playerData.setSkillXp(skill, xp);
                // Add stat levels
                plugin.getRewardManager().getRewardTable(skill).applyStats(playerData, level);
            }
            // Load stat modifiers
            ConfigurationSection modifiersSection = config.getConfigurationSection("stat_modifiers");
            if (modifiersSection != null) {
                for (String entry : modifiersSection.getKeys(false)) {
                    ConfigurationSection modifierEntry = modifiersSection.getConfigurationSection(entry);
                    if (modifierEntry != null) {
                        String name = modifierEntry.getString("name");
                        String statName = modifierEntry.getString("stat");
                        double value = modifierEntry.getDouble("value");
                        if (name != null && statName != null) {
                            Stat stat = plugin.getStatRegistry().getStat(statName);
                            StatModifier modifier = new StatModifier(name, stat, value);
                            playerData.addStatModifier(modifier);
                        }
                    }
                }
            }
            // Load mana
            playerData.setMana(config.getDouble("mana"));
            // Load locale
            String locale = config.getString("locale");
            if (locale != null) {
                playerData.setLocale(new Locale(locale));
            }
            // Load ability data
            ConfigurationSection abilitySection = config.getConfigurationSection("ability_data");
            if (abilitySection != null) {
                for (String abilityName : abilitySection.getKeys(false)) {
                    ConfigurationSection abilityEntry = abilitySection.getConfigurationSection(abilityName);
                    if (abilityEntry != null) {
                        AbstractAbility ability = AbstractAbility.valueOf(abilityName.toUpperCase(Locale.ROOT));
                        if (ability != null) {
                            AbilityData abilityData = playerData.getAbilityData(ability);
                            for (String key : abilityEntry.getKeys(false)) {
                                Object value = abilityEntry.get(key);
                                abilityData.setData(key, value);
                            }
                        }
                    }
                }
            }
            // Unclaimed item rewards
            List<String> unclaimedItemsList = config.getStringList("unclaimed_items");
            if (unclaimedItemsList.size() > 0) {
                List<KeyIntPair> unclaimedItems = new ArrayList<>();
                for (String entry : unclaimedItemsList) {
                    String[] splitEntry = entry.split(" ");
                    String itemKey = splitEntry[0];
                    int amount = 1;
                    if (splitEntry.length >= 2) {
                        amount = NumberUtils.toInt(splitEntry[1], 1);
                    }
                    unclaimedItems.add(new KeyIntPair(itemKey, amount));
                }
                playerData.setUnclaimedItems(unclaimedItems);
                playerData.clearInvalidItems();
            }
            playerManager.addPlayerData(playerData);
            plugin.getLeveler().updatePermissions(player);
            PlayerDataLoadEvent event = new PlayerDataLoadEvent(playerData);
            new BukkitRunnable() {

                @Override
                public void run() {
                    Bukkit.getPluginManager().callEvent(event);
                }
            }.runTask(plugin);
        } catch (Exception e) {
            Bukkit.getLogger().warning("There was an error loading player data for player " + player.getName() + " with UUID " + player.getUniqueId() + ", see below for details.");
            e.printStackTrace();
            PlayerData data = createNewPlayer(player);
            data.setShouldSave(false);
            sendErrorMessageToPlayer(player, e);
        }
    } else {
        createNewPlayer(player);
    }
}
Also used : AbstractAbility(com.archyx.aureliumskills.ability.AbstractAbility) FileConfiguration(org.bukkit.configuration.file.FileConfiguration) StatModifier(com.archyx.aureliumskills.modifier.StatModifier) Stat(com.archyx.aureliumskills.stats.Stat) PlayerDataLoadEvent(com.archyx.aureliumskills.data.PlayerDataLoadEvent) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) IOException(java.io.IOException) Skill(com.archyx.aureliumskills.skills.Skill) KeyIntPair(com.archyx.aureliumskills.util.misc.KeyIntPair) File(java.io.File) PlayerData(com.archyx.aureliumskills.data.PlayerData) AbilityData(com.archyx.aureliumskills.data.AbilityData) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Example 4 with KeyIntPair

use of com.archyx.aureliumskills.util.misc.KeyIntPair in project AureliumSkills by Archy-X.

the class YamlStorageProvider method save.

@Override
public void save(Player player, boolean removeFromMemory) {
    PlayerData playerData = playerManager.getPlayerData(player);
    if (playerData == null)
        return;
    if (playerData.shouldNotSave())
        return;
    // Save lock
    if (playerData.isSaving())
        return;
    playerData.setSaving(true);
    // Load file
    File file = new File(plugin.getDataFolder() + "/playerdata/" + player.getUniqueId() + ".yml");
    FileConfiguration config = YamlConfiguration.loadConfiguration(file);
    try {
        config.set("uuid", player.getUniqueId().toString());
        // Save skill data
        for (Skill skill : Skills.values()) {
            String path = "skills." + skill.toString().toLowerCase(Locale.ROOT) + ".";
            config.set(path + "level", playerData.getSkillLevel(skill));
            config.set(path + "xp", playerData.getSkillXp(skill));
        }
        // Clear existing modifiers
        config.set("stat_modifiers", null);
        // Save stat modifiers
        int count = 0;
        for (StatModifier modifier : playerData.getStatModifiers().values()) {
            String path = "stat_modifiers." + count + ".";
            config.set(path + "name", modifier.getName());
            config.set(path + "stat", modifier.getStat().toString().toLowerCase(Locale.ROOT));
            config.set(path + "value", modifier.getValue());
            count++;
        }
        // Save mana
        config.set("mana", playerData.getMana());
        // Save locale
        Locale locale = playerData.getLocale();
        if (locale != null) {
            config.set("locale", locale.toString());
        }
        // Save ability data
        for (AbilityData abilityData : playerData.getAbilityDataMap().values()) {
            String path = "ability_data." + abilityData.getAbility().toString().toLowerCase(Locale.ROOT) + ".";
            for (Map.Entry<String, Object> entry : abilityData.getDataMap().entrySet()) {
                config.set(path + entry.getKey(), entry.getValue());
            }
        }
        // Save unclaimed items
        List<KeyIntPair> unclaimedItems = playerData.getUnclaimedItems();
        config.set("unclaimed_items", null);
        if (unclaimedItems != null && unclaimedItems.size() > 0) {
            List<String> stringList = new ArrayList<>();
            for (KeyIntPair unclaimedItem : unclaimedItems) {
                stringList.add(unclaimedItem.getKey() + " " + unclaimedItem.getValue());
            }
            config.set("unclaimed_items", stringList);
        }
        config.save(file);
        if (removeFromMemory) {
            // Remove from memory
            playerManager.removePlayerData(player.getUniqueId());
        }
    } catch (Exception e) {
        Bukkit.getLogger().warning("There was an error saving player data for player " + player.getName() + " with UUID " + player.getUniqueId() + ", see below for details.");
        e.printStackTrace();
    }
    // Unlock
    playerData.setSaving(false);
}
Also used : IOException(java.io.IOException) FileConfiguration(org.bukkit.configuration.file.FileConfiguration) StatModifier(com.archyx.aureliumskills.modifier.StatModifier) Skill(com.archyx.aureliumskills.skills.Skill) KeyIntPair(com.archyx.aureliumskills.util.misc.KeyIntPair) PlayerData(com.archyx.aureliumskills.data.PlayerData) File(java.io.File) AbilityData(com.archyx.aureliumskills.data.AbilityData)

Example 5 with KeyIntPair

use of com.archyx.aureliumskills.util.misc.KeyIntPair in project AureliumSkills by Archy-X.

the class UnclaimedItemsMenu method init.

@Override
public void init(Player player, InventoryContents contents) {
    for (int slot = 0; slot < 54; slot++) {
        int row = slot / 9;
        int column = slot % 9;
        if (playerData.getUnclaimedItems().size() <= slot) {
            // Empty slot
            contents.set(row, column, ClickableItem.empty(new ItemStack(Material.AIR)));
        } else {
            // Slot with item
            KeyIntPair keyIntPair = playerData.getUnclaimedItems().get(slot);
            String itemKey = keyIntPair.getKey();
            int amount = keyIntPair.getValue();
            ItemStack item = plugin.getItemRegistry().getItem(itemKey);
            if (item == null) {
                plugin.getLogger().warning("Could not find a registered item with key " + itemKey + " when claiming unclaimed item rewards");
                continue;
            }
            item.setAmount(amount);
            contents.set(row, column, ClickableItem.of(getDisplayItem(item), event -> {
                // Give item on click
                ItemStack leftoverItem = ItemUtils.addItemToInventory(player, item);
                if (leftoverItem == null) {
                    // All items were added
                    playerData.getUnclaimedItems().remove(keyIntPair);
                    if (playerData.getUnclaimedItems().size() > 0) {
                        init(player, contents);
                    } else {
                        player.closeInventory();
                    }
                } else if (leftoverItem.getAmount() != item.getAmount()) {
                    // Some items could not fit
                    keyIntPair.setValue(leftoverItem.getAmount());
                    init(player, contents);
                } else {
                    // All items could not fit
                    player.sendMessage(Lang.getMessage(MenuMessage.INVENTORY_FULL, playerData.getLocale()));
                    player.closeInventory();
                }
            }));
        }
    }
}
Also used : ItemUtils(com.archyx.aureliumskills.util.item.ItemUtils) MenuMessage(com.archyx.aureliumskills.lang.MenuMessage) ItemMeta(org.bukkit.inventory.meta.ItemMeta) SmartInventory(fr.minuskube.inv.SmartInventory) Player(org.bukkit.entity.Player) ItemStack(org.bukkit.inventory.ItemStack) ArrayList(java.util.ArrayList) List(java.util.List) AureliumSkills(com.archyx.aureliumskills.AureliumSkills) Lang(com.archyx.aureliumskills.lang.Lang) InventoryProvider(fr.minuskube.inv.content.InventoryProvider) InventoryContents(fr.minuskube.inv.content.InventoryContents) KeyIntPair(com.archyx.aureliumskills.util.misc.KeyIntPair) PlayerData(com.archyx.aureliumskills.data.PlayerData) Material(org.bukkit.Material) ClickableItem(fr.minuskube.inv.ClickableItem) ItemStack(org.bukkit.inventory.ItemStack) KeyIntPair(com.archyx.aureliumskills.util.misc.KeyIntPair)

Aggregations

PlayerData (com.archyx.aureliumskills.data.PlayerData)7 KeyIntPair (com.archyx.aureliumskills.util.misc.KeyIntPair)7 AbilityData (com.archyx.aureliumskills.data.AbilityData)4 StatModifier (com.archyx.aureliumskills.modifier.StatModifier)4 Skill (com.archyx.aureliumskills.skills.Skill)4 IOException (java.io.IOException)4 ItemStack (org.bukkit.inventory.ItemStack)3 AbstractAbility (com.archyx.aureliumskills.ability.AbstractAbility)2 PlayerDataLoadEvent (com.archyx.aureliumskills.data.PlayerDataLoadEvent)2 Stat (com.archyx.aureliumskills.stats.Stat)2 File (java.io.File)2 FileConfiguration (org.bukkit.configuration.file.FileConfiguration)2 BukkitRunnable (org.bukkit.scheduler.BukkitRunnable)2 AureliumSkills (com.archyx.aureliumskills.AureliumSkills)1 Lang (com.archyx.aureliumskills.lang.Lang)1 MenuMessage (com.archyx.aureliumskills.lang.MenuMessage)1 ItemUtils (com.archyx.aureliumskills.util.item.ItemUtils)1 ClickableItem (fr.minuskube.inv.ClickableItem)1 SmartInventory (fr.minuskube.inv.SmartInventory)1 InventoryContents (fr.minuskube.inv.content.InventoryContents)1