From 8207ff915b4206270f8feb323afd633aee1e4205 Mon Sep 17 00:00:00 2001 From: Brianna Date: Sun, 4 Aug 2019 17:49:57 -0400 Subject: [PATCH] Rewrote a bit. --- core/pom.xml | 124 ---- .../java/com/songoda/epicenchants/Action.java | 67 -- .../songoda/epicenchants/EpicEnchants.java | 125 ---- .../songoda/epicenchants/objects/Enchant.java | 53 -- .../songoda/epicenchants/objects/Group.java | 19 - .../wrappers/EnchantmentWrapper.java | 23 - core/src/main/resources/actions.yml | 67 -- core/src/main/resources/config.yml | 15 - pom.xml | 140 +++- .../songoda/epicenchants/EpicEnchants.java | 224 ++++++ .../epicenchants/commands/CustomCommand.java | 0 .../epicenchants/commands/EnchantCommand.java | 0 .../songoda/epicenchants/economy/Economy.java | 12 + .../economy/PlayerPointsEconomy.java | 38 + .../epicenchants/economy/ReserveEconomy.java | 32 + .../epicenchants/economy/VaultEconomy.java | 28 + .../effect/EffectEventExecutor.java | 0 .../epicenchants/effect/EffectExecutor.java | 0 .../epicenchants/effect/EffectManager.java | 0 .../epicenchants/effect/effects/Burn.java | 0 .../effect/effects/CancelEvent.java | 0 .../effect/effects/ConsoleCommand.java | 0 .../epicenchants/effect/effects/DropHead.java | 0 .../epicenchants/effect/effects/DropItem.java | 0 .../epicenchants/effect/effects/Explode.java | 0 .../effect/effects/Extinguish.java | 0 .../epicenchants/effect/effects/Fly.java | 0 .../effect/effects/Lightning.java | 0 .../epicenchants/effect/effects/Message.java | 0 .../effect/effects/ModifyBlock.java | 0 .../effect/effects/ModifyDamage.java | 0 .../effect/effects/ModifyExp.java | 0 .../effect/effects/ModifyFood.java | 0 .../effect/effects/ModifyHealth.java | 0 .../effect/effects/ModifyOxygen.java | 0 .../effect/effects/MoreDrops.java | 0 .../effect/effects/PlayerCommand.java | 0 .../epicenchants/effect/effects/Potion.java | 0 .../effect/effects/RemoveEffect.java | 0 .../epicenchants/effect/effects/Repair.java | 0 .../epicenchants/effect/effects/SpawnMob.java | 0 .../epicenchants/effect/effects/SpawnTnt.java | 0 .../epicenchants/effect/effects/StealExp.java | 0 .../effect/effects/StealHealth.java | 0 .../epicenchants/effect/effects/Throw.java | 0 .../epicenchants/enums/EnchantResult.java | 0 .../songoda/epicenchants/enums/EventType.java | 0 .../songoda/epicenchants/enums/GiveType.java | 0 .../songoda/epicenchants/enums/ItemType.java | 0 .../epicenchants/enums/TriggerType.java | 0 .../epicenchants/events/ArmorEquipEvent.java | 0 .../events/EnchantApplyEvent.java | 22 +- .../epicenchants/listeners/ArmorListener.java | 0 .../listeners/EntityListener.java | 7 +- .../listeners/PlayerListener.java | 3 +- .../listeners/item/BlackScrollListener.java | 0 .../listeners/item/BookListener.java | 0 .../listeners/item/DustListener.java | 0 .../listeners/item/ItemListener.java | 0 .../listeners/item/WhiteScrollListener.java | 0 .../epicenchants/managers/CommandManager.java | 2 +- .../epicenchants/managers/EnchantManager.java | 2 +- .../epicenchants/managers/FileManager.java | 28 +- .../epicenchants/managers/GroupManager.java | 0 .../epicenchants/managers/HookManager.java | 2 - .../epicenchants/managers/InfoManager.java | 8 +- .../epicenchants/managers/Manager.java | 0 .../epicenchants/menus/AlchemistMenu.java | 37 +- .../epicenchants/menus/EnchanterMenu.java | 25 +- .../songoda/epicenchants/menus/InfoMenu.java | 0 .../epicenchants/menus/MainInfoMenu.java | 0 .../epicenchants/menus/TinkererMenu.java | 28 +- .../epicenchants/objects/BookItem.java | 56 +- .../epicenchants/objects/Condition.java | 0 .../songoda/epicenchants/objects/Enchant.java | 170 +++++ .../songoda/epicenchants/objects/Group.java | 178 +++++ .../epicenchants/objects/LeveledModifier.java | 0 .../epicenchants/objects/Placeholder.java | 11 +- .../epicenchants/utils/EnchantUtils.java | 38 +- .../songoda/epicenchants/utils/Methods.java | 53 ++ .../songoda/epicenchants/utils/Metrics.java | 695 ++++++++++++++++++ .../epicenchants/utils/ServerVersion.java | 27 + .../epicenchants/utils/SpecialItems.java | 7 +- .../com/songoda/epicenchants/utils/Tuple.java | 23 + .../utils/itemnbtapi/ClassWrapper.java | 37 + .../utils/itemnbtapi/NBTCompound.java | 200 +++++ .../utils/itemnbtapi/NBTContainer.java | 35 + .../utils/itemnbtapi/NBTEntity.java | 22 + .../utils/itemnbtapi/NBTFile.java | 46 ++ .../utils/itemnbtapi/NBTItem.java | 52 ++ .../utils/itemnbtapi/NBTList.java | 127 ++++ .../utils/itemnbtapi/NBTListCompound.java | 102 +++ .../utils/itemnbtapi/NBTReflectionUtil.java | 347 +++++++++ .../utils/itemnbtapi/NBTTileEntity.java | 22 + .../utils/itemnbtapi/NBTType.java | 34 + .../utils/itemnbtapi/ObjectCreator.java | 28 + .../utils/itemnbtapi/ReflectionMethod.java | 128 ++++ .../utils/itemnbtapi/utils/GsonWrapper.java | 27 + .../itemnbtapi/utils/MinecraftVersion.java | 63 ++ .../epicenchants/utils/locale/Locale.java | 302 ++++++++ .../epicenchants/utils/locale/Message.java | 128 ++++ .../epicenchants/utils/objects/FastInv.java | 0 .../utils/objects/FileLocation.java | 4 + .../utils/objects/ItemBuilder.java | 0 .../epicenchants/utils/settings/Category.java | 31 + .../epicenchants/utils/settings/Setting.java | 156 ++++ .../utils/settings/SettingsManager.java | 311 ++++++++ .../utils/single/ConfigParser.java | 0 .../epicenchants/utils/single/Experience.java | 0 .../utils/single/GeneralUtils.java | 0 .../epicenchants/utils/single/ItemGroup.java | 0 .../utils/single/Placeholders.java | 0 .../utils/single/RomanNumber.java | 0 .../utils/updateModules/LocaleModule.java | 32 + .../wrappers/EnchantmentWrapper.java | 56 ++ src/main/resources/en_US.lang | 57 ++ .../resources/enchants/example-enchant.yml | 0 {core/src => src}/main/resources/groups.yml | 0 .../resources/menus/groups/elite-menu.yml | 0 .../resources/menus/groups/legendary-menu.yml | 0 .../resources/menus/groups/simple-menu.yml | 0 .../resources/menus/groups/ultimate-menu.yml | 0 .../resources/menus/groups/unique-menu.yml | 0 .../main/resources/menus/main-info-menu.yml | 0 {core/src => src}/main/resources/plugin.yml | 0 .../version-dependent/legacy/items/dusts.yml | 0 .../legacy/items/special-items.yml | 0 .../legacy/menus/alchemist-menu.yml | 0 .../legacy/menus/enchanter-menu.yml | 0 .../legacy/menus/tinkerer-menu.yml | 0 .../version-dependent/master/items/dusts.yml | 0 .../master/items/special-items.yml | 0 .../master/menus/alchemist-menu.yml | 0 .../master/menus/enchanter-menu.yml | 0 .../master/menus/tinkerer-menu.yml | 0 135 files changed, 4125 insertions(+), 611 deletions(-) delete mode 100644 core/pom.xml delete mode 100644 core/src/main/java/com/songoda/epicenchants/Action.java delete mode 100644 core/src/main/java/com/songoda/epicenchants/EpicEnchants.java delete mode 100644 core/src/main/java/com/songoda/epicenchants/objects/Enchant.java delete mode 100644 core/src/main/java/com/songoda/epicenchants/objects/Group.java delete mode 100644 core/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java delete mode 100644 core/src/main/resources/actions.yml delete mode 100644 core/src/main/resources/config.yml create mode 100644 src/main/java/com/songoda/epicenchants/EpicEnchants.java rename {core/src => src}/main/java/com/songoda/epicenchants/commands/CustomCommand.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/commands/EnchantCommand.java (100%) create mode 100644 src/main/java/com/songoda/epicenchants/economy/Economy.java create mode 100644 src/main/java/com/songoda/epicenchants/economy/PlayerPointsEconomy.java create mode 100644 src/main/java/com/songoda/epicenchants/economy/ReserveEconomy.java create mode 100644 src/main/java/com/songoda/epicenchants/economy/VaultEconomy.java rename {core/src => src}/main/java/com/songoda/epicenchants/effect/EffectEventExecutor.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/EffectExecutor.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/EffectManager.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Burn.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/DropHead.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/DropItem.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Explode.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Extinguish.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Fly.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Lightning.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Message.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/ModifyDamage.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/ModifyExp.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/ModifyFood.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/ModifyHealth.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/ModifyOxygen.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Potion.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/RemoveEffect.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Repair.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/SpawnTnt.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/StealExp.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/StealHealth.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/effect/effects/Throw.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/enums/EnchantResult.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/enums/EventType.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/enums/GiveType.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/enums/ItemType.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/enums/TriggerType.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java (77%) rename {core/src => src}/main/java/com/songoda/epicenchants/listeners/ArmorListener.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/listeners/EntityListener.java (96%) rename {core/src => src}/main/java/com/songoda/epicenchants/listeners/PlayerListener.java (97%) rename {core/src => src}/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/listeners/item/BookListener.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/listeners/item/DustListener.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/listeners/item/ItemListener.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/managers/CommandManager.java (97%) rename {core/src => src}/main/java/com/songoda/epicenchants/managers/EnchantManager.java (94%) rename {core/src => src}/main/java/com/songoda/epicenchants/managers/FileManager.java (77%) rename {core/src => src}/main/java/com/songoda/epicenchants/managers/GroupManager.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/managers/HookManager.java (94%) rename {core/src => src}/main/java/com/songoda/epicenchants/managers/InfoManager.java (87%) rename {core/src => src}/main/java/com/songoda/epicenchants/managers/Manager.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java (86%) rename {core/src => src}/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java (72%) rename {core/src => src}/main/java/com/songoda/epicenchants/menus/InfoMenu.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/menus/TinkererMenu.java (88%) rename {core/src => src}/main/java/com/songoda/epicenchants/objects/BookItem.java (66%) rename {core/src => src}/main/java/com/songoda/epicenchants/objects/Condition.java (100%) create mode 100644 src/main/java/com/songoda/epicenchants/objects/Enchant.java create mode 100644 src/main/java/com/songoda/epicenchants/objects/Group.java rename {core/src => src}/main/java/com/songoda/epicenchants/objects/LeveledModifier.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/objects/Placeholder.java (75%) rename {core/src => src}/main/java/com/songoda/epicenchants/utils/EnchantUtils.java (74%) create mode 100644 src/main/java/com/songoda/epicenchants/utils/Methods.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/Metrics.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/ServerVersion.java rename {core/src => src}/main/java/com/songoda/epicenchants/utils/SpecialItems.java (94%) create mode 100644 src/main/java/com/songoda/epicenchants/utils/Tuple.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ClassWrapper.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTCompound.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTContainer.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTEntity.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTFile.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTItem.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTList.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTListCompound.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTReflectionUtil.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTTileEntity.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTType.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ObjectCreator.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ReflectionMethod.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/utils/GsonWrapper.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/itemnbtapi/utils/MinecraftVersion.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/locale/Locale.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/locale/Message.java rename {core/src => src}/main/java/com/songoda/epicenchants/utils/objects/FastInv.java (100%) create mode 100644 src/main/java/com/songoda/epicenchants/utils/objects/FileLocation.java rename {core/src => src}/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java (100%) create mode 100644 src/main/java/com/songoda/epicenchants/utils/settings/Category.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/settings/Setting.java create mode 100644 src/main/java/com/songoda/epicenchants/utils/settings/SettingsManager.java rename {core/src => src}/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/utils/single/Experience.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/utils/single/GeneralUtils.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/utils/single/Placeholders.java (100%) rename {core/src => src}/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java (100%) create mode 100644 src/main/java/com/songoda/epicenchants/utils/updateModules/LocaleModule.java create mode 100644 src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java create mode 100644 src/main/resources/en_US.lang rename {core/src => src}/main/resources/enchants/example-enchant.yml (100%) rename {core/src => src}/main/resources/groups.yml (100%) rename {core/src => src}/main/resources/menus/groups/elite-menu.yml (100%) rename {core/src => src}/main/resources/menus/groups/legendary-menu.yml (100%) rename {core/src => src}/main/resources/menus/groups/simple-menu.yml (100%) rename {core/src => src}/main/resources/menus/groups/ultimate-menu.yml (100%) rename {core/src => src}/main/resources/menus/groups/unique-menu.yml (100%) rename {core/src => src}/main/resources/menus/main-info-menu.yml (100%) rename {core/src => src}/main/resources/plugin.yml (100%) rename {core/src => src}/main/resources/version-dependent/legacy/items/dusts.yml (100%) rename {core/src => src}/main/resources/version-dependent/legacy/items/special-items.yml (100%) rename {core/src => src}/main/resources/version-dependent/legacy/menus/alchemist-menu.yml (100%) rename {core/src => src}/main/resources/version-dependent/legacy/menus/enchanter-menu.yml (100%) rename {core/src => src}/main/resources/version-dependent/legacy/menus/tinkerer-menu.yml (100%) rename {core/src => src}/main/resources/version-dependent/master/items/dusts.yml (100%) rename {core/src => src}/main/resources/version-dependent/master/items/special-items.yml (100%) rename {core/src => src}/main/resources/version-dependent/master/menus/alchemist-menu.yml (100%) rename {core/src => src}/main/resources/version-dependent/master/menus/enchanter-menu.yml (100%) rename {core/src => src}/main/resources/version-dependent/master/menus/tinkerer-menu.yml (100%) diff --git a/core/pom.xml b/core/pom.xml deleted file mode 100644 index 9362b40..0000000 --- a/core/pom.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - EpicEnchants-Parent - com.songoda - 1.0.8-ALPHA - - 4.0.0 - - EpicEnchants - - - UTF-8 - - - - - jitpack.io - https://jitpack.io - - - - aikar - https://repo.aikar.co/content/groups/aikar/ - - - - placeholderapi - http://repo.extendedclip.com/content/repositories/placeholderapi/ - - - - - clean package - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - -parameters - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.1.0 - - ${project.build.directory}/dependency-reduced-pom.xml - - - - package - - shade - - - - - - - - src/main/resources - true - - - - - - - org.spigotmc - spigot - 1.13.2 - provided - - - - org.projectlombok - lombok - 1.18.2 - - - - com.github.tr7zw - Item-NBT-API - master-SNAPSHOT - compile - - - - co.aikar - acf-bukkit - 0.5.0-SNAPSHOT - compile - - - - net.milkbowl.vault - VaultAPI - 1.7 - provided - - - - com.songoda - UltimateBottles - 1.0 - provided - - - - me.clip - placeholderapi - 2.9.2 - provided - - - \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicenchants/Action.java b/core/src/main/java/com/songoda/epicenchants/Action.java deleted file mode 100644 index 75fccd8..0000000 --- a/core/src/main/java/com/songoda/epicenchants/Action.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.songoda.epicenchants; - -import com.songoda.epicenchants.objects.Placeholder; -import org.bukkit.Effect; -import org.bukkit.Sound; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import static com.songoda.epicenchants.utils.single.GeneralUtils.color; - -public class Action { - private FileConfiguration config; - - public void perform(CommandSender sender, String node, Placeholder... placeholders) { - if (config.isString(node)) { - getMessage(node, placeholders).forEach(sender::sendMessage); - return; - } - - if (!config.isConfigurationSection(node)) { - return; - } - - ConfigurationSection section = config.getConfigurationSection(node); - - if (section.isString("message") || section.isList("message")) { - getMessage(node + ".message", placeholders).forEach(sender::sendMessage); - } - - if (!(sender instanceof Player)) { - return; - } - - Player player = (Player) sender; - - if (section.isString("sound")) { - player.playSound(player.getLocation(), Sound.valueOf(section.getString("sound").toUpperCase()), 1F, 1F); - } - - if (section.isString("effect")) { - player.playEffect(player.getEyeLocation(), Effect.valueOf(section.getString("effect")), 10); - } - - } - - public List getMessage(String node, Placeholder... placeholders) { - List output = config.isList(node) ? config.getStringList(node) : config.getString(node).isEmpty() ? Collections.emptyList() : Collections.singletonList(config.getString(node)); - - return output.stream().map(s -> { - for (Placeholder placeholder : placeholders) { - s = s.replace(placeholder.getPlaceholder(), placeholder.getToReplace().toString()); - } - - return color(s); - }).collect(Collectors.toList()); - } - - public void load(FileConfiguration config) { - this.config = config; - } -} diff --git a/core/src/main/java/com/songoda/epicenchants/EpicEnchants.java b/core/src/main/java/com/songoda/epicenchants/EpicEnchants.java deleted file mode 100644 index 6cce4f3..0000000 --- a/core/src/main/java/com/songoda/epicenchants/EpicEnchants.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.songoda.epicenchants; - -import co.aikar.commands.BukkitCommandManager; -import com.songoda.epicenchants.listeners.ArmorListener; -import com.songoda.epicenchants.listeners.EntityListener; -import com.songoda.epicenchants.listeners.PlayerListener; -import com.songoda.epicenchants.listeners.item.BlackScrollListener; -import com.songoda.epicenchants.listeners.item.BookListener; -import com.songoda.epicenchants.listeners.item.DustListener; -import com.songoda.epicenchants.listeners.item.WhiteScrollListener; -import com.songoda.epicenchants.managers.*; -import com.songoda.epicenchants.objects.Enchant; -import com.songoda.epicenchants.utils.EnchantUtils; -import com.songoda.epicenchants.utils.SpecialItems; -import com.songoda.epicenchants.utils.objects.FastInv; -import com.songoda.epicenchants.utils.single.ItemGroup; -import lombok.Getter; -import net.milkbowl.vault.economy.Economy; -import org.bukkit.Bukkit; -import org.bukkit.event.Listener; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.HashSet; -import java.util.stream.Collectors; - -import static com.songoda.epicenchants.utils.single.GeneralUtils.color; -import static org.bukkit.Bukkit.getConsoleSender; - -@Getter -public class EpicEnchants extends JavaPlugin { - - private BukkitCommandManager commandManager; - private EnchantManager enchantManager; - private InfoManager infoManager; - private GroupManager groupManager; - private FileManager fileManager; - private HookManager hookManager; - - private SpecialItems specialItems; - private Action action; - private Economy economy; - private EnchantUtils enchantUtils; - private ItemGroup itemGroup; - private int version; - - @Override - public void onEnable() { - getConsoleSender().sendMessage(color("&a=============================")); - getConsoleSender().sendMessage(color("&7" + getDescription().getName() + " " + getDescription().getVersion() + " by &5Songoda <3&7!")); - getConsoleSender().sendMessage(color("&7Action: &aEnabling&7...")); - - preload(); - - this.action = new Action(); - this.groupManager = new GroupManager(this); - this.enchantManager = new EnchantManager(this); - this.enchantUtils = new EnchantUtils(this); - this.infoManager = new InfoManager(this); - this.specialItems = new SpecialItems(this); - this.economy = getServer().getServicesManager().getRegistration(Economy.class).getProvider(); - this.commandManager = new CommandManager(this); - this.hookManager = new HookManager(); - this.itemGroup = new ItemGroup(this); - - groupManager.loadGroups(); - enchantManager.loadEnchants(); - infoManager.loadMenus(); - action.load(fileManager.getConfiguration("actions")); - hookManager.setup(); - - setupListeners(); - - if (!enchantManager.getValues().isEmpty()) { - getLogger().info("Successfully loaded enchants: " + enchantManager.getValues().stream().map(Enchant::getIdentifier).collect(Collectors.joining(", "))); - } - - getConsoleSender().sendMessage(color("&a=============================")); - } - - private void preload() { - FastInv.init(this); - this.version = Integer.parseInt(Bukkit.getServer().getBukkitVersion().split("\\.")[1]); - this.fileManager = new FileManager(this); - fileManager.loadFiles(); - } - - @Override - public void onDisable() { - getConsoleSender().sendMessage(color("&a=============================")); - getConsoleSender().sendMessage(color("&7" + getDescription().getName() + " " + getDescription().getVersion() + " by &5Songoda <3&7!")); - getConsoleSender().sendMessage(color("&7Action: &cDisabling&7...")); - getConsoleSender().sendMessage(color("&a=============================")); - } - - private void setupListeners() { - EpicEnchants instance = this; - new HashSet() {{ - add(new BookListener(instance)); - add(new ArmorListener()); - add(new PlayerListener(instance)); - add(new EntityListener(instance)); - add(new WhiteScrollListener(instance)); - add(new BlackScrollListener(instance)); - add(new DustListener(instance)); - }}.forEach(listener -> Bukkit.getPluginManager().registerEvents(listener, this)); - } - - public void reload() { - reloadConfig(); - - fileManager.clear(); - fileManager.loadFiles(); - - groupManager.clear(); - groupManager.loadGroups(); - - enchantManager.clear(); - enchantManager.loadEnchants(); - - infoManager.clear(); - infoManager.loadMenus(); - - action.load(fileManager.getConfiguration("actions")); - } -} diff --git a/core/src/main/java/com/songoda/epicenchants/objects/Enchant.java b/core/src/main/java/com/songoda/epicenchants/objects/Enchant.java deleted file mode 100644 index 55afe1b..0000000 --- a/core/src/main/java/com/songoda/epicenchants/objects/Enchant.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.songoda.epicenchants.objects; - -import com.songoda.epicenchants.effect.EffectExecutor; -import com.songoda.epicenchants.enums.EventType; -import com.songoda.epicenchants.enums.TriggerType; -import com.songoda.epicenchants.utils.single.RomanNumber; -import lombok.Builder; -import lombok.Getter; -import org.bukkit.Material; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Set; - -import static com.songoda.epicenchants.utils.single.GeneralUtils.color; - -@Builder -@Getter -public class Enchant { - private String identifier; - private Group group; - private int maxLevel; - private Set conflict; - //TODO: ISSUES - private Set itemWhitelist; - private Set effectExecutors; - private List description; - private String format; - @Nullable private BookItem bookItem; - - public void onAction(@NotNull Player user, @Nullable LivingEntity opponent, Event event, int level, TriggerType triggerType, EventType eventType) { - effectExecutors.forEach(effect -> effect.testAndRun(user, opponent, level, triggerType, event, eventType)); - } - - public BookItem getBook() { - return bookItem != null ? bookItem : group.getBookItem(); - } - - public String getFormat(int level, boolean roman) { - String output = format.isEmpty() ? group.getFormat() : format; - - output = output - .replace("{level}", "" + (roman ? RomanNumber.toRoman(level) : level)) - .replace("{enchant}", "" + identifier) - .replace("{group_color}", "" + group.getColor()); - - return color(output); - } -} diff --git a/core/src/main/java/com/songoda/epicenchants/objects/Group.java b/core/src/main/java/com/songoda/epicenchants/objects/Group.java deleted file mode 100644 index eda73d5..0000000 --- a/core/src/main/java/com/songoda/epicenchants/objects/Group.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.songoda.epicenchants.objects; - -import lombok.Builder; -import lombok.Getter; - -@Getter -@Builder -public class Group { - private String identifier; - private String name; - private String format; - private String color; - private String descriptionColor; - private int slotsUsed; - private BookItem bookItem; - private int destroyRateMin, destroyRateMax, successRateMin, successRateMax; - private int tinkererExp; - private int order; -} diff --git a/core/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java b/core/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java deleted file mode 100644 index 4306ab7..0000000 --- a/core/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.songoda.epicenchants.wrappers; - -import com.songoda.epicenchants.objects.LeveledModifier; -import lombok.Builder; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -@Builder -public class EnchantmentWrapper { - private LeveledModifier amplifier; - private Enchantment enchantment; - - public int getAmplifier(int level, @NotNull Player user, @Nullable LivingEntity opponent) { - return (int) amplifier.get(level, 0, user, opponent); - } - - public Enchantment getEnchantment() { - return enchantment; - } -} diff --git a/core/src/main/resources/actions.yml b/core/src/main/resources/actions.yml deleted file mode 100644 index 6f80790..0000000 --- a/core/src/main/resources/actions.yml +++ /dev/null @@ -1,67 +0,0 @@ -general: - no-permission: "&cYou do not have permission to do that." - -command: - book: - received: "&7You have been given a &6{enchant} &7book." - gave: "&7You gave {player} a &6{enchant} &7book." - max-level: "&cThe max level for {enchant} is {max-level}." - min-level: "&cThe min level for {enchant} is 1." - - white-scroll: - received: "&7You have been given a whitescroll." - gave: "&7You gave {player} a whitescroll." - - apply: - invalid-item: "&cYou cannot apply {enchant} to this item." - - reload: "&6Configuration files reload" - give-unknown: "&cUnknown item to give: &f{unknown}." - -black-scroll: - success: "&aSuccessfully blackscrolled: {group_color}{enchant} {level}&a." - no-enchants: "&cNo enchants to blackscroll." - -white-scroll: - already-applied: "&cThis item is already protected!" - applied: "&aThis item is now protected!" - -enchanter: - cannot-afford: "&c&l(!) &r&cYou cannot afford this purchase." - success: "&7Purchased {group_color}{group_name} &7book for &f{exp_cost} EXP&7." - -tinkerer: - open: "&eTrading with the tinkerer." - cancelled: "&c&l(!) &r&cCancelled." - accepted: "&aAccepted" - no-items: "&c&l(!) &r&cThe tinkerer is not interested in any of your items!" - deposited-all: "&a&l(!) &r&aDeposited {amount} items." - -alchemist: - max-two-items: "&c&l(!) &r&cYou may only combine 2 items at once." - not-interested: "&c&l(!) &r&cThe alchemist is not interested in any of your items!" - max-level-book: "&c&l(!) &r&cThe alchemist cannot combine max level books." - max-percentage-dust: "&c&l(!) &r&cThe alchemist cannot combine 100% success rate dusts." - highest-group-dust: "&c&l(!) &r&cThe alchemist can't accept dust of the highest tier." - different-enchantment: "&c&l(!) &r&cThe alchemist can only combine books with the same enchantment." - different-levels: "&c&l(!) &r&cThe alchemist can only combine books of the same level." - different-groups: "&c&l(!) &r&cThe alchemist can only combine dusts of the same group." - cannot-afford: "&c&l(!) You cannot afford this exchange." - success: "&7Exchanged for &f{exp_cost} EXP&7." - -enchants: - invalid-material: "&cYou can not apply &6{enchant} &cto that item." - failure: "&6{enchant} &cfailed to apply..." - broken-failure: "&6{enchant} &cfailed to apply and broke your item..." - success: "&aYou have successfully applied &6{enchant}." - conflict: "&cYou cannot apply this enchant as it conflicts with another enchant." - maxed-out: "&cYou already have that enchant maxed on this item." - already-applied: "&cYou already have that enchant applied on this item." - protected: "&aYour book would have broken your item, luckily it was protected!" - -book: - discover: - - "&l&e(!) &r&eYou examine the {group_color}{group_name} Enchantment Book..." - - "&eand discover &n{enchant_format}!" - - diff --git a/core/src/main/resources/config.yml b/core/src/main/resources/config.yml deleted file mode 100644 index d79aa33..0000000 --- a/core/src/main/resources/config.yml +++ /dev/null @@ -1,15 +0,0 @@ -first-load: true - -language: "en_US" - -roman-numbers: true - -rates: - black-scroll-min: 20 - black-scroll-max: 100 - - -commands: - enchanter: "enchanter" - alchemist: "alchemist" - tinkerer: "tinkerer" \ No newline at end of file diff --git a/pom.xml b/pom.xml index 96134ec..8b0d3ad 100644 --- a/pom.xml +++ b/pom.xml @@ -1,41 +1,127 @@ - - - 4.0.0 - + com.songoda - EpicEnchants-Parent - pom - 1.0.8-ALPHA - - core - - - - - private - http://repo.songoda.com/repository/private/ - - - + EpicEnchants + 4.0.0 + maven-version-number + clean install + EpicHeads-${project.version} org.apache.maven.plugins maven-compiler-plugin - 3.5.1 + 3.8.0 1.8 1.8 + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + shaded + package + + shade + + + false + false + + + com.songoda:songodaupdater + fr.mymicky:FastInv + co.aikar:acf-bukkit + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + - - - src/main/resources - true - - + + + + private + http://repo.songoda.com/artifactory/private/ + + + reserve-repo + https://dl.bintray.com/theneweconomy/java/ + + + jitpack.io + https://jitpack.io + + + aikar + https://repo.aikar.co/content/groups/aikar/ + + + + + + org.spigotmc + spigot + 1.14.4 + + + co.aikar + acf-bukkit + 0.5.0-SNAPSHOT + compile + + + fr.mrmicky + FastInv + 3.0.2 + compile + + + com.songoda + songodaupdater + 1 + + + net.tnemc + Reserve + 0.1.3.0 + provided + + + org.black_ixx + playerpoints + 2.1.4 + + + net.milkbowl + vault + 1.7.1 + + + com.songoda + UltimateBottles + 1_0 + + + me.clip + placeholderapi + 2.9.2 + provided + + \ No newline at end of file diff --git a/src/main/java/com/songoda/epicenchants/EpicEnchants.java b/src/main/java/com/songoda/epicenchants/EpicEnchants.java new file mode 100644 index 0000000..f04c951 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/EpicEnchants.java @@ -0,0 +1,224 @@ +package com.songoda.epicenchants; + +import co.aikar.commands.BukkitCommandManager; +import com.songoda.epicenchants.economy.Economy; +import com.songoda.epicenchants.economy.PlayerPointsEconomy; +import com.songoda.epicenchants.economy.ReserveEconomy; +import com.songoda.epicenchants.economy.VaultEconomy; +import com.songoda.epicenchants.listeners.ArmorListener; +import com.songoda.epicenchants.listeners.EntityListener; +import com.songoda.epicenchants.listeners.PlayerListener; +import com.songoda.epicenchants.listeners.item.BlackScrollListener; +import com.songoda.epicenchants.listeners.item.BookListener; +import com.songoda.epicenchants.listeners.item.DustListener; +import com.songoda.epicenchants.listeners.item.WhiteScrollListener; +import com.songoda.epicenchants.managers.*; +import com.songoda.epicenchants.objects.Enchant; +import com.songoda.epicenchants.utils.EnchantUtils; +import com.songoda.epicenchants.utils.Metrics; +import com.songoda.epicenchants.utils.ServerVersion; +import com.songoda.epicenchants.utils.SpecialItems; +import com.songoda.epicenchants.utils.locale.Locale; +import com.songoda.epicenchants.utils.objects.FastInv; +import com.songoda.epicenchants.utils.settings.Setting; +import com.songoda.epicenchants.utils.settings.SettingsManager; +import com.songoda.epicenchants.utils.single.ItemGroup; +import com.songoda.epicenchants.utils.updateModules.LocaleModule; +import com.songoda.update.Plugin; +import com.songoda.update.SongodaUpdate; +import org.apache.commons.lang.ArrayUtils; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.stream.Collectors; + +import static com.songoda.epicenchants.utils.single.GeneralUtils.color; +import static org.bukkit.Bukkit.getConsoleSender; + +public class EpicEnchants extends JavaPlugin { + + private static EpicEnchants INSTANCE; + + private EnchantManager enchantManager; + private InfoManager infoManager; + private GroupManager groupManager; + private FileManager fileManager; + private HookManager hookManager; + private SettingsManager settingsManager; + private BukkitCommandManager commandManager; + + private Locale locale; + + private ServerVersion serverVersion = ServerVersion.fromPackageName(Bukkit.getServer().getClass().getPackage().getName()); + + private SpecialItems specialItems; + private Economy economy; + private EnchantUtils enchantUtils; + private ItemGroup itemGroup; + private int version; + + public static EpicEnchants getInstance() { + return INSTANCE; + } + + @Override + public void onEnable() { + INSTANCE = this; + + getConsoleSender().sendMessage(color("&a=============================")); + getConsoleSender().sendMessage(color("&7" + getDescription().getName() + " " + getDescription().getVersion() + " by &5Songoda <3&7!")); + getConsoleSender().sendMessage(color("&7Action: &aEnabling&7...")); + + // Setup Setting Manager + this.settingsManager = new SettingsManager(this); + this.settingsManager.setupConfig(); + + // Setup Language + new Locale(this, "en_US"); + this.locale = Locale.getLocale(getConfig().getString("System.Language Mode")); + + // Running Songoda Updater + Plugin plugin = new Plugin(this, -1); + plugin.addModule(new LocaleModule()); + SongodaUpdate.load(plugin); + + preload(); + + this.groupManager = new GroupManager(this); + this.enchantManager = new EnchantManager(this); + this.enchantUtils = new EnchantUtils(this); + this.infoManager = new InfoManager(this); + this.specialItems = new SpecialItems(this); + this.commandManager = new CommandManager(this); + this.hookManager = new HookManager(); + this.itemGroup = new ItemGroup(this); + + groupManager.loadGroups(); + enchantManager.loadEnchants(); + infoManager.loadMenus(); + hookManager.setup(); + + PluginManager pluginManager = Bukkit.getPluginManager(); + + // Listeners + pluginManager.registerEvents(new BookListener(this), this); + pluginManager.registerEvents(new ArmorListener(), this); + pluginManager.registerEvents(new PlayerListener(this), this); + pluginManager.registerEvents(new EntityListener(this), this); + pluginManager.registerEvents(new WhiteScrollListener(this), this); + pluginManager.registerEvents(new BlackScrollListener(this), this); + pluginManager.registerEvents(new DustListener(this), this); + + // Setup Economy + if (Setting.VAULT_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("Vault")) + this.economy = new VaultEconomy(); + else if (Setting.RESERVE_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("Reserve")) + this.economy = new ReserveEconomy(); + else if (Setting.PLAYER_POINTS_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("PlayerPoints")) + this.economy = new PlayerPointsEconomy(); + + // Start Metrics + new Metrics(this); + + if (!enchantManager.getValues().isEmpty()) { + getLogger().info("Successfully loaded enchants: " + enchantManager.getValues().stream().map(Enchant::getIdentifier).collect(Collectors.joining(", "))); + } + + getConsoleSender().sendMessage(color("&a=============================")); + } + + private void preload() { + FastInv.init(this); + this.version = Integer.parseInt(Bukkit.getServer().getBukkitVersion().split("\\.")[1]); + this.fileManager = new FileManager(this); + fileManager.loadFiles(); + } + + @Override + public void onDisable() { + getConsoleSender().sendMessage(color("&a=============================")); + getConsoleSender().sendMessage(color("&7" + getDescription().getName() + " " + getDescription().getVersion() + " by &5Songoda <3&7!")); + getConsoleSender().sendMessage(color("&7Action: &cDisabling&7...")); + getConsoleSender().sendMessage(color("&a=============================")); + } + + public void reload() { + reloadConfig(); + + fileManager.clear(); + fileManager.loadFiles(); + + groupManager.clear(); + groupManager.loadGroups(); + + enchantManager.clear(); + enchantManager.loadEnchants(); + + infoManager.clear(); + infoManager.loadMenus(); + + this.locale = Locale.getLocale(getConfig().getString("System.Language Mode")); + this.locale.reloadMessages(); + } + + public ServerVersion getServerVersion() { + return serverVersion; + } + + public boolean isServerVersion(ServerVersion version) { + return serverVersion == version; + } + + public boolean isServerVersion(ServerVersion... versions) { + return ArrayUtils.contains(versions, serverVersion); + } + + public boolean isServerVersionAtLeast(ServerVersion version) { + return serverVersion.ordinal() >= version.ordinal(); + } + + public EnchantManager getEnchantManager() { + return this.enchantManager; + } + + public InfoManager getInfoManager() { + return this.infoManager; + } + + public GroupManager getGroupManager() { + return this.groupManager; + } + + public FileManager getFileManager() { + return this.fileManager; + } + + public HookManager getHookManager() { + return this.hookManager; + } + + public SpecialItems getSpecialItems() { + return this.specialItems; + } + + public Economy getEconomy() { + return this.economy; + } + + public EnchantUtils getEnchantUtils() { + return this.enchantUtils; + } + + public ItemGroup getItemGroup() { + return this.itemGroup; + } + + public int getVersion() { + return this.version; + } + + public Locale getLocale() { + return locale; + } +} diff --git a/core/src/main/java/com/songoda/epicenchants/commands/CustomCommand.java b/src/main/java/com/songoda/epicenchants/commands/CustomCommand.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/commands/CustomCommand.java rename to src/main/java/com/songoda/epicenchants/commands/CustomCommand.java diff --git a/core/src/main/java/com/songoda/epicenchants/commands/EnchantCommand.java b/src/main/java/com/songoda/epicenchants/commands/EnchantCommand.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/commands/EnchantCommand.java rename to src/main/java/com/songoda/epicenchants/commands/EnchantCommand.java diff --git a/src/main/java/com/songoda/epicenchants/economy/Economy.java b/src/main/java/com/songoda/epicenchants/economy/Economy.java new file mode 100644 index 0000000..9d5a914 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/economy/Economy.java @@ -0,0 +1,12 @@ +package com.songoda.ultimateclaims.economy; + +import org.bukkit.OfflinePlayer; + +public interface Economy { + + boolean hasBalance(OfflinePlayer player, double cost); + + boolean withdrawBalance(OfflinePlayer player, double cost); + + boolean deposit(OfflinePlayer player, double amount); +} diff --git a/src/main/java/com/songoda/epicenchants/economy/PlayerPointsEconomy.java b/src/main/java/com/songoda/epicenchants/economy/PlayerPointsEconomy.java new file mode 100644 index 0000000..bc73955 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/economy/PlayerPointsEconomy.java @@ -0,0 +1,38 @@ +package com.songoda.ultimateclaims.economy; + +import org.black_ixx.playerpoints.PlayerPoints; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; + +public class PlayerPointsEconomy implements Economy { + + private final PlayerPoints playerPoints; + + public PlayerPointsEconomy() { + this.playerPoints = (PlayerPoints) Bukkit.getServer().getPluginManager().getPlugin("PlayerPoints"); + } + + private int convertAmount(double amount) { + return (int) Math.ceil(amount); + } + + @Override + public boolean hasBalance(OfflinePlayer player, double cost) { + int amount = convertAmount(cost); + return playerPoints.getAPI().look(player.getUniqueId()) >= amount; + + } + + @Override + public boolean withdrawBalance(OfflinePlayer player, double cost) { + int amount = convertAmount(cost); + return playerPoints.getAPI().take(player.getUniqueId(), amount); + + } + + @Override + public boolean deposit(OfflinePlayer player, double amount) { + int amt = convertAmount(amount); + return playerPoints.getAPI().give(player.getUniqueId(), amt); + } +} diff --git a/src/main/java/com/songoda/epicenchants/economy/ReserveEconomy.java b/src/main/java/com/songoda/epicenchants/economy/ReserveEconomy.java new file mode 100644 index 0000000..5fecdf3 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/economy/ReserveEconomy.java @@ -0,0 +1,32 @@ +package com.songoda.ultimateclaims.economy; + +import net.tnemc.core.Reserve; +import net.tnemc.core.economy.EconomyAPI; +import org.bukkit.OfflinePlayer; + +import java.math.BigDecimal; + +public class ReserveEconomy implements Economy { + + EconomyAPI economyAPI; + + public ReserveEconomy() { + if (Reserve.instance().economyProvided()) + economyAPI = Reserve.instance().economy(); + } + + @Override + public boolean hasBalance(OfflinePlayer player, double cost) { + return economyAPI.hasHoldings(player.getUniqueId(), new BigDecimal(cost)); + } + + @Override + public boolean withdrawBalance(OfflinePlayer player, double cost) { + return economyAPI.removeHoldings(player.getUniqueId(), new BigDecimal(cost)); + } + + @Override + public boolean deposit(OfflinePlayer player, double amount) { + return economyAPI.addHoldings(player.getUniqueId(), new BigDecimal(amount)); + } +} diff --git a/src/main/java/com/songoda/epicenchants/economy/VaultEconomy.java b/src/main/java/com/songoda/epicenchants/economy/VaultEconomy.java new file mode 100644 index 0000000..dca7967 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/economy/VaultEconomy.java @@ -0,0 +1,28 @@ +package com.songoda.ultimateclaims.economy; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; + +public class VaultEconomy implements Economy { + private final net.milkbowl.vault.economy.Economy vault; + + public VaultEconomy() { + this.vault = Bukkit.getServicesManager(). + getRegistration(net.milkbowl.vault.economy.Economy.class).getProvider(); + } + + @Override + public boolean hasBalance(OfflinePlayer player, double cost) { + return vault.has(player, cost); + } + + @Override + public boolean withdrawBalance(OfflinePlayer player, double cost) { + return vault.withdrawPlayer(player, cost).transactionSuccess(); + } + + @Override + public boolean deposit(OfflinePlayer player, double amount) { + return vault.depositPlayer(player, amount).transactionSuccess(); + } +} diff --git a/core/src/main/java/com/songoda/epicenchants/effect/EffectEventExecutor.java b/src/main/java/com/songoda/epicenchants/effect/EffectEventExecutor.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/EffectEventExecutor.java rename to src/main/java/com/songoda/epicenchants/effect/EffectEventExecutor.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/EffectExecutor.java b/src/main/java/com/songoda/epicenchants/effect/EffectExecutor.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/EffectExecutor.java rename to src/main/java/com/songoda/epicenchants/effect/EffectExecutor.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/EffectManager.java b/src/main/java/com/songoda/epicenchants/effect/EffectManager.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/EffectManager.java rename to src/main/java/com/songoda/epicenchants/effect/EffectManager.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Burn.java b/src/main/java/com/songoda/epicenchants/effect/effects/Burn.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Burn.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Burn.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java b/src/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java rename to src/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java b/src/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java rename to src/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/DropHead.java b/src/main/java/com/songoda/epicenchants/effect/effects/DropHead.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/DropHead.java rename to src/main/java/com/songoda/epicenchants/effect/effects/DropHead.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/DropItem.java b/src/main/java/com/songoda/epicenchants/effect/effects/DropItem.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/DropItem.java rename to src/main/java/com/songoda/epicenchants/effect/effects/DropItem.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Explode.java b/src/main/java/com/songoda/epicenchants/effect/effects/Explode.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Explode.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Explode.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Extinguish.java b/src/main/java/com/songoda/epicenchants/effect/effects/Extinguish.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Extinguish.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Extinguish.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Fly.java b/src/main/java/com/songoda/epicenchants/effect/effects/Fly.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Fly.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Fly.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Lightning.java b/src/main/java/com/songoda/epicenchants/effect/effects/Lightning.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Lightning.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Lightning.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Message.java b/src/main/java/com/songoda/epicenchants/effect/effects/Message.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Message.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Message.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java b/src/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java rename to src/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyDamage.java b/src/main/java/com/songoda/epicenchants/effect/effects/ModifyDamage.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyDamage.java rename to src/main/java/com/songoda/epicenchants/effect/effects/ModifyDamage.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyExp.java b/src/main/java/com/songoda/epicenchants/effect/effects/ModifyExp.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyExp.java rename to src/main/java/com/songoda/epicenchants/effect/effects/ModifyExp.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyFood.java b/src/main/java/com/songoda/epicenchants/effect/effects/ModifyFood.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyFood.java rename to src/main/java/com/songoda/epicenchants/effect/effects/ModifyFood.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyHealth.java b/src/main/java/com/songoda/epicenchants/effect/effects/ModifyHealth.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyHealth.java rename to src/main/java/com/songoda/epicenchants/effect/effects/ModifyHealth.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyOxygen.java b/src/main/java/com/songoda/epicenchants/effect/effects/ModifyOxygen.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/ModifyOxygen.java rename to src/main/java/com/songoda/epicenchants/effect/effects/ModifyOxygen.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java b/src/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java rename to src/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java b/src/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java rename to src/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Potion.java b/src/main/java/com/songoda/epicenchants/effect/effects/Potion.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Potion.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Potion.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/RemoveEffect.java b/src/main/java/com/songoda/epicenchants/effect/effects/RemoveEffect.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/RemoveEffect.java rename to src/main/java/com/songoda/epicenchants/effect/effects/RemoveEffect.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Repair.java b/src/main/java/com/songoda/epicenchants/effect/effects/Repair.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Repair.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Repair.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java b/src/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java rename to src/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/SpawnTnt.java b/src/main/java/com/songoda/epicenchants/effect/effects/SpawnTnt.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/SpawnTnt.java rename to src/main/java/com/songoda/epicenchants/effect/effects/SpawnTnt.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/StealExp.java b/src/main/java/com/songoda/epicenchants/effect/effects/StealExp.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/StealExp.java rename to src/main/java/com/songoda/epicenchants/effect/effects/StealExp.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/StealHealth.java b/src/main/java/com/songoda/epicenchants/effect/effects/StealHealth.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/StealHealth.java rename to src/main/java/com/songoda/epicenchants/effect/effects/StealHealth.java diff --git a/core/src/main/java/com/songoda/epicenchants/effect/effects/Throw.java b/src/main/java/com/songoda/epicenchants/effect/effects/Throw.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/effect/effects/Throw.java rename to src/main/java/com/songoda/epicenchants/effect/effects/Throw.java diff --git a/core/src/main/java/com/songoda/epicenchants/enums/EnchantResult.java b/src/main/java/com/songoda/epicenchants/enums/EnchantResult.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/enums/EnchantResult.java rename to src/main/java/com/songoda/epicenchants/enums/EnchantResult.java diff --git a/core/src/main/java/com/songoda/epicenchants/enums/EventType.java b/src/main/java/com/songoda/epicenchants/enums/EventType.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/enums/EventType.java rename to src/main/java/com/songoda/epicenchants/enums/EventType.java diff --git a/core/src/main/java/com/songoda/epicenchants/enums/GiveType.java b/src/main/java/com/songoda/epicenchants/enums/GiveType.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/enums/GiveType.java rename to src/main/java/com/songoda/epicenchants/enums/GiveType.java diff --git a/core/src/main/java/com/songoda/epicenchants/enums/ItemType.java b/src/main/java/com/songoda/epicenchants/enums/ItemType.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/enums/ItemType.java rename to src/main/java/com/songoda/epicenchants/enums/ItemType.java diff --git a/core/src/main/java/com/songoda/epicenchants/enums/TriggerType.java b/src/main/java/com/songoda/epicenchants/enums/TriggerType.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/enums/TriggerType.java rename to src/main/java/com/songoda/epicenchants/enums/TriggerType.java diff --git a/core/src/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java b/src/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java rename to src/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java diff --git a/core/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java b/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java similarity index 77% rename from core/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java rename to src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java index 44b9b9c..94ffe3a 100644 --- a/core/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java +++ b/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java @@ -1,13 +1,11 @@ package com.songoda.epicenchants.events; import com.songoda.epicenchants.objects.Enchant; -import lombok.Getter; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; -@Getter public class EnchantApplyEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private final ItemStack toEnchant; @@ -43,4 +41,24 @@ public class EnchantApplyEvent extends Event implements Cancellable { public HandlerList getHandlers() { return handlers; } + + public ItemStack getToEnchant() { + return this.toEnchant; + } + + public Enchant getEnchant() { + return this.enchant; + } + + public int getLevel() { + return this.level; + } + + public int getSuccessRate() { + return this.successRate; + } + + public int getDestroyRate() { + return this.destroyRate; + } } diff --git a/core/src/main/java/com/songoda/epicenchants/listeners/ArmorListener.java b/src/main/java/com/songoda/epicenchants/listeners/ArmorListener.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/listeners/ArmorListener.java rename to src/main/java/com/songoda/epicenchants/listeners/ArmorListener.java diff --git a/core/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java b/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java similarity index 96% rename from core/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java rename to src/main/java/com/songoda/epicenchants/listeners/EntityListener.java index 40a0df1..c749093 100644 --- a/core/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java @@ -2,8 +2,11 @@ package com.songoda.epicenchants.listeners; import com.songoda.epicenchants.EpicEnchants; import com.songoda.epicenchants.enums.TriggerType; -import de.tr7zw.itemnbtapi.NBTEntity; -import org.bukkit.entity.*; +import com.songoda.epicenchants.utils.itemnbtapi.NBTEntity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Monster; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; diff --git a/core/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java b/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java similarity index 97% rename from core/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java rename to src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java index aaa0335..cd26c21 100644 --- a/core/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java @@ -16,7 +16,8 @@ import org.bukkit.event.player.PlayerJoinEvent; import java.util.Arrays; import java.util.Map; -import static com.songoda.epicenchants.enums.EventType.*; +import static com.songoda.epicenchants.enums.EventType.OFF; +import static com.songoda.epicenchants.enums.EventType.ON; import static com.songoda.epicenchants.enums.TriggerType.*; public class PlayerListener implements Listener { diff --git a/core/src/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java rename to src/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java diff --git a/core/src/main/java/com/songoda/epicenchants/listeners/item/BookListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/BookListener.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/listeners/item/BookListener.java rename to src/main/java/com/songoda/epicenchants/listeners/item/BookListener.java diff --git a/core/src/main/java/com/songoda/epicenchants/listeners/item/DustListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/DustListener.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/listeners/item/DustListener.java rename to src/main/java/com/songoda/epicenchants/listeners/item/DustListener.java diff --git a/core/src/main/java/com/songoda/epicenchants/listeners/item/ItemListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/ItemListener.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/listeners/item/ItemListener.java rename to src/main/java/com/songoda/epicenchants/listeners/item/ItemListener.java diff --git a/core/src/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java rename to src/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java diff --git a/core/src/main/java/com/songoda/epicenchants/managers/CommandManager.java b/src/main/java/com/songoda/epicenchants/managers/CommandManager.java similarity index 97% rename from core/src/main/java/com/songoda/epicenchants/managers/CommandManager.java rename to src/main/java/com/songoda/epicenchants/managers/CommandManager.java index f887a21..4c72d9b 100644 --- a/core/src/main/java/com/songoda/epicenchants/managers/CommandManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/CommandManager.java @@ -24,7 +24,7 @@ public class CommandManager extends BukkitCommandManager { // COMPLETIONS - getCommandCompletions().registerCompletion("enchants", c -> + getCommandCompletions().registerCompletion("src/main/resources/enchants", c -> instance.getEnchantManager().getKeys().stream().map(s -> s.replaceAll("\\s", "_")).collect(Collectors.toList())); getCommandCompletions().registerCompletion("giveType", c -> diff --git a/core/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java b/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java similarity index 94% rename from core/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java rename to src/main/java/com/songoda/epicenchants/managers/EnchantManager.java index bfd5aeb..708a764 100644 --- a/core/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java @@ -30,7 +30,7 @@ public class EnchantManager extends Manager { } public void loadEnchants() { - instance.getFileManager().getYmlFiles("enchants").forEach(file -> { + instance.getFileManager().getYmlFiles("src/main/resources/enchants").forEach(file -> { try { loadEnchant(file); } catch (Exception e) { diff --git a/core/src/main/java/com/songoda/epicenchants/managers/FileManager.java b/src/main/java/com/songoda/epicenchants/managers/FileManager.java similarity index 77% rename from core/src/main/java/com/songoda/epicenchants/managers/FileManager.java rename to src/main/java/com/songoda/epicenchants/managers/FileManager.java index 7836640..916c741 100644 --- a/core/src/main/java/com/songoda/epicenchants/managers/FileManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/FileManager.java @@ -2,7 +2,6 @@ package com.songoda.epicenchants.managers; import com.songoda.epicenchants.EpicEnchants; import com.songoda.epicenchants.utils.objects.FileLocation; -import org.apache.commons.io.FileUtils; import org.bukkit.Bukkit; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; @@ -10,6 +9,8 @@ import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; import java.util.*; import static com.songoda.epicenchants.utils.objects.FileLocation.of; @@ -21,18 +22,17 @@ public class FileManager extends Manager { private final String directory; private final LinkedHashSet files = new LinkedHashSet<>(asList( of("config.yml", true), - of("menus/main-info-menu.yml", true), + of("src/main/resources/menus/main-info-menu.yml", true), of("menus/enchanter-menu.yml", true, true), of("menus/tinkerer-menu.yml", true, true), of("menus/alchemist-menu.yml", true, true), - of("menus/groups/simple-menu.yml", false), - of("menus/groups/unique-menu.yml", false), - of("menus/groups/elite-menu.yml", false), - of("menus/groups/ultimate-menu.yml", false), - of("menus/groups/legendary-menu.yml", false), - of("enchants/example-enchant.yml", false), - of("groups.yml", true), - of("actions.yml", true), + of("src/main/resources/menus/groups/simple-menu.yml", false), + of("src/main/resources/menus/groups/unique-menu.yml", false), + of("src/main/resources/menus/groups/elite-menu.yml", false), + of("src/main/resources/menus/groups/ultimate-menu.yml", false), + of("src/main/resources/menus/groups/legendary-menu.yml", false), + of("src/main/resources/enchants/example-enchant.yml", false), + of("src/main/resources/groups.yml", true), of("items/special-items.yml", true, true), of("items/dusts.yml", true, true) )); @@ -47,12 +47,14 @@ public class FileManager extends Manager { files.forEach(fileLocation -> { File file = new File(instance.getDataFolder() + separator + fileLocation.getPath()); - if (!file.exists() && (fileLocation.isRequired() || getConfiguration("config").getBoolean("first-load"))) { + if (!file.exists() && (fileLocation.isRequired() || getConfiguration("config").getBoolean("System.First Load"))) { file.getParentFile().mkdirs(); Bukkit.getConsoleSender().sendMessage("Creating file: " + fileLocation.getPath()); try { - FileUtils.copyInputStreamToFile(instance.getResource(fileLocation.getResourcePath(directory)), file); + InputStream in = instance.getResource(fileLocation.getResourcePath(directory)); + if (in != null) + Files.copy(in, file.toPath()); } catch (IOException e) { e.printStackTrace(); } @@ -69,7 +71,7 @@ public class FileManager extends Manager { } }); - getConfiguration("config").set("first-load", false); + getConfiguration("config").set("System.First Load", false); try { getConfiguration("config").save(new File(instance.getDataFolder() + separator + "config.yml")); } catch (IOException e) { diff --git a/core/src/main/java/com/songoda/epicenchants/managers/GroupManager.java b/src/main/java/com/songoda/epicenchants/managers/GroupManager.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/managers/GroupManager.java rename to src/main/java/com/songoda/epicenchants/managers/GroupManager.java diff --git a/core/src/main/java/com/songoda/epicenchants/managers/HookManager.java b/src/main/java/com/songoda/epicenchants/managers/HookManager.java similarity index 94% rename from core/src/main/java/com/songoda/epicenchants/managers/HookManager.java rename to src/main/java/com/songoda/epicenchants/managers/HookManager.java index d1c03b2..60ecd63 100644 --- a/core/src/main/java/com/songoda/epicenchants/managers/HookManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/HookManager.java @@ -1,12 +1,10 @@ package com.songoda.epicenchants.managers; import com.songoda.ultimatebottles.UltimateBottles; -import lombok.Getter; import org.bukkit.Bukkit; import java.util.Optional; -@Getter public class HookManager { private UltimateBottles ultimateBottles; diff --git a/core/src/main/java/com/songoda/epicenchants/managers/InfoManager.java b/src/main/java/com/songoda/epicenchants/managers/InfoManager.java similarity index 87% rename from core/src/main/java/com/songoda/epicenchants/managers/InfoManager.java rename to src/main/java/com/songoda/epicenchants/managers/InfoManager.java index 11009aa..a881e43 100644 --- a/core/src/main/java/com/songoda/epicenchants/managers/InfoManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/InfoManager.java @@ -4,7 +4,6 @@ import com.songoda.epicenchants.EpicEnchants; import com.songoda.epicenchants.menus.InfoMenu; import com.songoda.epicenchants.menus.MainInfoMenu; import com.songoda.epicenchants.objects.Group; -import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; @@ -12,7 +11,7 @@ import java.util.Optional; public class InfoManager extends Manager { private final EpicEnchants instance; - @Getter private MainInfoMenu mainInfoMenu; + private MainInfoMenu mainInfoMenu; public InfoManager(EpicEnchants instance) { super(instance); @@ -25,7 +24,7 @@ public class InfoManager extends Manager { public void loadMenus() { mainInfoMenu = new MainInfoMenu(instance, instance.getFileManager().getConfiguration("menus/main-info-menu")); - instance.getFileManager().getYmlFiles("menus/groups").forEach(file -> { + instance.getFileManager().getYmlFiles("src/main/resources/menus/groups").forEach(file -> { try { YamlConfiguration config = YamlConfiguration.loadConfiguration(file); add(instance.getGroupManager().getValue(config.getString("group")) @@ -38,4 +37,7 @@ public class InfoManager extends Manager { }); } + public MainInfoMenu getMainInfoMenu() { + return this.mainInfoMenu; + } } diff --git a/core/src/main/java/com/songoda/epicenchants/managers/Manager.java b/src/main/java/com/songoda/epicenchants/managers/Manager.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/managers/Manager.java rename to src/main/java/com/songoda/epicenchants/managers/Manager.java diff --git a/core/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java b/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java similarity index 86% rename from core/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java rename to src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java index cab4725..8dfcbee 100644 --- a/core/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java +++ b/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java @@ -4,10 +4,10 @@ import com.songoda.epicenchants.EpicEnchants; import com.songoda.epicenchants.objects.Enchant; import com.songoda.epicenchants.objects.Group; import com.songoda.epicenchants.objects.Placeholder; +import com.songoda.epicenchants.utils.itemnbtapi.NBTItem; import com.songoda.epicenchants.utils.objects.FastInv; import com.songoda.epicenchants.utils.objects.ItemBuilder; import com.songoda.epicenchants.utils.single.GeneralUtils; -import de.tr7zw.itemnbtapi.NBTItem; import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; @@ -18,8 +18,10 @@ import java.util.HashSet; import java.util.Set; import static com.songoda.epicenchants.objects.Placeholder.of; -import static com.songoda.epicenchants.utils.single.Experience.*; -import static com.songoda.epicenchants.utils.single.GeneralUtils.*; +import static com.songoda.epicenchants.utils.single.Experience.changeExp; +import static com.songoda.epicenchants.utils.single.Experience.getExp; +import static com.songoda.epicenchants.utils.single.GeneralUtils.color; +import static com.songoda.epicenchants.utils.single.GeneralUtils.getSlots; public class AlchemistMenu extends FastInv { private final EpicEnchants instance; @@ -122,13 +124,13 @@ public class AlchemistMenu extends FastInv { NBTItem nbtItem = new NBTItem(toHandle); if (!nbtItem.hasKey("book-item") && !nbtItem.hasKey("dust")) { - instance.getAction().perform(player, "alchemist.not-interested"); + instance.getLocale().getMessage("alchemist.notinterested").sendPrefixedMessage(player); return false; } // Both slots occupied if (getInventory().getItem(LEFT_SLOT) != null && getInventory().getItem(RIGHT_SLOT) != null) { - instance.getAction().perform(player, "alchemist.max-two-items"); + instance.getLocale().getMessage("alchemist.maxtwoitems").sendPrefixedMessage(player); return false; } @@ -141,14 +143,16 @@ public class AlchemistMenu extends FastInv { int level = nbtItem.getInteger("level"); if (enchant.getMaxLevel() == level) { - instance.getAction().perform(player, "alchemist.max-level-book"); + instance.getLocale().getMessage("alchemist.maxlevelbook") + .sendPrefixedMessage(player); return false; } } else { Group group = instance.getGroupManager().getValue(nbtItem.getString("group")).orElseThrow(() -> new IllegalStateException("Dust without group!")); if (group.getOrder() == instance.getGroupManager().getValues().stream().mapToInt(Group::getOrder).max().orElse(0) || successRate == 100) { - instance.getAction().perform(player, "alchemist." + (successRate == 100 ? "max-percentage-dust" : "highest-group-dust")); + instance.getLocale().getMessage("alchemist." + (successRate == 100 ? "maxpercentagedust" : "highestgroupdust")) + .sendPrefixedMessage(player); return false; } } @@ -162,22 +166,22 @@ public class AlchemistMenu extends FastInv { if (other.hasKey("book-item")) { if (!nbtItem.getString("enchant").equals(other.getString("enchant"))) { - instance.getAction().perform(player, "alchemist.different-enchantment"); + instance.getLocale().getMessage("alchemist.differentenchantment").sendPrefixedMessage(player); return false; } if (!nbtItem.getInteger("level").equals(other.getInteger("level"))) { - instance.getAction().perform(player, "alchemist.different-levels"); + instance.getLocale().getMessage("alchemist.differentlevels").sendPrefixedMessage(player); return false; } } else { if (!nbtItem.getString("group").equals(other.getString("group"))) { - instance.getAction().perform(player, "alchemist.different-groups"); + instance.getLocale().getMessage("alchemist.differentgroups").sendPrefixedMessage(player); return false; } if (successRate == 100) { - instance.getAction().perform(player, "alchemist.max-percentage-dust"); + instance.getLocale().getMessage("alchemist.maxpercentagedust").sendPrefixedMessage(player); return false; } } @@ -261,14 +265,17 @@ public class AlchemistMenu extends FastInv { of("eco_cost", ecoCost), of("exp_cost", expCost) ).build(), event -> { - if (!instance.getEconomy().has(event.getPlayer(), ecoCost) || getExp(event.getPlayer()) < expCost) { - instance.getAction().perform(event.getPlayer(), "alchemist.cannot-afford"); + if (!instance.getEconomy().hasBalance(event.getPlayer(), ecoCost) || getExp(event.getPlayer()) < expCost) { + instance.getLocale().getMessage("alchemist.cannotafford").sendPrefixedMessage(event.getPlayer()); return; } - instance.getEconomy().withdrawPlayer(event.getPlayer(), ecoCost); + instance.getEconomy().withdrawBalance(event.getPlayer(), ecoCost); changeExp(event.getPlayer(), -expCost); - instance.getAction().perform(event.getPlayer(), "alchemist.success", of("eco_cost", ecoCost), of("exp_cost", expCost)); + instance.getLocale().getMessage("alchemist.success") + .processPlaceholder("ecocost", ecoCost) + .processPlaceholder("expcost", expCost) + .sendPrefixedMessage(event.getPlayer()); event.getPlayer().getInventory().addItem(getInventory().getItem(PREVIEW_SLOT)); clear(RIGHT_SLOT); diff --git a/core/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java b/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java similarity index 72% rename from core/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java rename to src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java index 7cd9cda..f7c1f07 100644 --- a/core/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java +++ b/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java @@ -13,8 +13,10 @@ import java.util.Map; import java.util.UUID; import static com.songoda.epicenchants.objects.Placeholder.of; -import static com.songoda.epicenchants.utils.single.Experience.*; -import static com.songoda.epicenchants.utils.single.GeneralUtils.*; +import static com.songoda.epicenchants.utils.single.Experience.changeExp; +import static com.songoda.epicenchants.utils.single.Experience.getExp; +import static com.songoda.epicenchants.utils.single.GeneralUtils.color; +import static com.songoda.epicenchants.utils.single.GeneralUtils.getSlots; public class EnchanterMenu extends FastInv { private final Map DELAY = new HashMap<>(); @@ -33,7 +35,7 @@ public class EnchanterMenu extends FastInv { .forEach(section -> { int expCost = section.getInt("exp-cost"); int ecoCost = section.getInt("eco-cost"); - int xpLeft = expCost - player.getLevel() < 0 ? 0 : expCost - player.getLevel(); + int xpLeft = Math.max(expCost - player.getLevel(), 0); double ecoLeft = ecoCost - instance.getEconomy().getBalance(player) < 0 ? 0 : ecoCost - instance.getEconomy().getBalance(player); Group group = instance.getGroupManager().getValue(section.getString("group").toUpperCase()) .orElseThrow(() -> new IllegalArgumentException("Invalid group set in enchanter: " + section.getString("group"))); @@ -49,17 +51,18 @@ public class EnchanterMenu extends FastInv { return; } - if (!instance.getEconomy().has((player), ecoCost) || getExp(player) < expCost) { - instance.getAction().perform(player, "enchanter.cannot-afford"); + if (!instance.getEconomy().hasBalance((player), ecoCost) || getExp(player) < expCost) { + instance.getLocale().getMessage("enchanter.cannotafford").sendPrefixedMessage(player); return; } - instance.getEconomy().withdrawPlayer(player, ecoCost); - instance.getAction().perform(player, "enchanter.success", - of("group_name", group.getName()), - of("group_color", group.getColor()), - of("eco_cost", ecoCost), - of("exp_cost", expCost)); + instance.getEconomy().withdrawBalance(player, ecoCost); + instance.getLocale().getMessage("enchanter.success") + .processPlaceholder("groupname", group.getName()) + .processPlaceholder("groupcolor", group.getColor()) + .processPlaceholder("ecocost", ecoCost) + .processPlaceholder("expcost", expCost) + .sendPrefixedMessage(player); changeExp(player, -expCost); player.getInventory().addItem(instance.getSpecialItems().getMysteryBook(group)); diff --git a/core/src/main/java/com/songoda/epicenchants/menus/InfoMenu.java b/src/main/java/com/songoda/epicenchants/menus/InfoMenu.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/menus/InfoMenu.java rename to src/main/java/com/songoda/epicenchants/menus/InfoMenu.java diff --git a/core/src/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java b/src/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java rename to src/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java diff --git a/core/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java b/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java similarity index 88% rename from core/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java rename to src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java index bb49f05..ec2cf80 100644 --- a/core/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java +++ b/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java @@ -3,10 +3,10 @@ package com.songoda.epicenchants.menus; import com.songoda.epicenchants.EpicEnchants; import com.songoda.epicenchants.enums.ItemType; import com.songoda.epicenchants.objects.Enchant; +import com.songoda.epicenchants.utils.itemnbtapi.NBTCompound; +import com.songoda.epicenchants.utils.itemnbtapi.NBTItem; import com.songoda.epicenchants.utils.objects.FastInv; import com.songoda.epicenchants.utils.objects.ItemBuilder; -import de.tr7zw.itemnbtapi.NBTCompound; -import de.tr7zw.itemnbtapi.NBTItem; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; @@ -14,14 +14,18 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -import java.util.*; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static com.songoda.epicenchants.enums.ItemType.*; import static com.songoda.epicenchants.objects.Placeholder.of; -import static com.songoda.epicenchants.utils.single.GeneralUtils.*; +import static com.songoda.epicenchants.utils.single.GeneralUtils.color; +import static com.songoda.epicenchants.utils.single.GeneralUtils.getSlots; import static java.util.Arrays.stream; public class TinkererMenu extends FastInv { @@ -53,7 +57,7 @@ public class TinkererMenu extends FastInv { slotMap.keySet().forEach(slot -> getInventory().clear(slot)); accepted.set(true); event.getPlayer().closeInventory(); - instance.getAction().perform(event.getPlayer(), "tinkerer.accepted"); + instance.getLocale().getMessage("tinkerer.accepted").sendPrefixedMessage(event.getPlayer()); return; } @@ -61,7 +65,7 @@ public class TinkererMenu extends FastInv { int count = (int) stream(event.getPlayer().getInventory().getContents()).filter(i -> isTinkerable(i) != NONE).count(); if (count == 0) { - instance.getAction().perform(event.getPlayer(), "tinkerer.no-items"); + instance.getLocale().getMessage("tinkerer.noitems").sendPrefixedMessage(event.getPlayer()); return; } @@ -98,7 +102,9 @@ public class TinkererMenu extends FastInv { inventory.setItem(i, itemStack); } - instance.getAction().perform(event.getPlayer(), "tinkerer.deposited-all", of("amount", amount)); + instance.getLocale().getMessage("tinkerer.depositedall") + .processPlaceholder("amount", amount) + .sendPrefixedMessage(event.getPlayer()); } }); }); @@ -153,7 +159,7 @@ public class TinkererMenu extends FastInv { }); if (!accepted.get()) - instance.getAction().perform(event.getPlayer(), "tinkerer.cancelled"); + instance.getLocale().getMessage("tinkerer.cancelled").sendPrefixedMessage(event.getPlayer()); }); } @@ -172,7 +178,7 @@ public class TinkererMenu extends FastInv { return NONE; } - if (!itemStack.getEnchantments().isEmpty() || (nbtItem.getCompound("enchants") != null && !nbtItem.getCompound("enchants").getKeys().isEmpty())) { + if (!itemStack.getEnchantments().isEmpty() || (nbtItem.getCompound("src/main/resources/enchants") != null && !nbtItem.getCompound("src/main/resources/enchants").getKeys().isEmpty())) { if (getExpAmount(itemStack) == 0) { return NONE; } @@ -231,11 +237,11 @@ public class TinkererMenu extends FastInv { NBTItem nbtItem = new NBTItem(itemStack); - if (!nbtItem.hasKey("enchants")) { + if (!nbtItem.hasKey("src/main/resources/enchants")) { return total.get(); } - NBTCompound enchantments = nbtItem.getCompound("enchants"); + NBTCompound enchantments = nbtItem.getCompound("src/main/resources/enchants"); if (enchantments == null) { return total.get(); diff --git a/core/src/main/java/com/songoda/epicenchants/objects/BookItem.java b/src/main/java/com/songoda/epicenchants/objects/BookItem.java similarity index 66% rename from core/src/main/java/com/songoda/epicenchants/objects/BookItem.java rename to src/main/java/com/songoda/epicenchants/objects/BookItem.java index c971acd..19c1515 100644 --- a/core/src/main/java/com/songoda/epicenchants/objects/BookItem.java +++ b/src/main/java/com/songoda/epicenchants/objects/BookItem.java @@ -1,12 +1,12 @@ package com.songoda.epicenchants.objects; import com.songoda.epicenchants.EpicEnchants; +import com.songoda.epicenchants.utils.itemnbtapi.NBTItem; import com.songoda.epicenchants.utils.objects.ItemBuilder; +import com.songoda.epicenchants.utils.settings.Setting; import com.songoda.epicenchants.utils.single.GeneralUtils; import com.songoda.epicenchants.utils.single.ItemGroup; import com.songoda.epicenchants.utils.single.RomanNumber; -import de.tr7zw.itemnbtapi.NBTItem; -import lombok.Builder; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; @@ -18,13 +18,23 @@ import java.util.stream.Collectors; import static com.songoda.epicenchants.utils.single.GeneralUtils.color; import static java.util.concurrent.ThreadLocalRandom.current; -@Builder public class BookItem { private EpicEnchants instance; private Material material; private String displayName; private List lore; + BookItem(EpicEnchants instance, Material material, String displayName, List lore) { + this.instance = instance; + this.material = material; + this.displayName = displayName; + this.lore = lore; + } + + public static BookItemBuilder builder() { + return new BookItemBuilder(); + } + public ItemStack get(Enchant enchant) { return get(enchant, current().nextInt(enchant.getMaxLevel()) + 1); } @@ -64,7 +74,7 @@ public class BookItem { ItemBuilder itemBuilder = new ItemBuilder(material) .name(color(displayName - .replace("{level}", "" + (instance.getFileManager().getConfiguration("config").getBoolean("roman-numbers") ? RomanNumber.toRoman(level) : level)) + .replace("{level}", "" + (Setting.ROMAN.getBoolean() ? RomanNumber.toRoman(level) : level)) .replace("{enchant}", "" + enchant.getIdentifier()) .replace("{group_color}", enchant.getGroup().getColor()) .replace("{group_name}", enchant.getGroup().getName()) @@ -80,4 +90,42 @@ public class BookItem { return nbtItem.getItem(); } + + public static class BookItemBuilder { + private EpicEnchants instance; + private Material material; + private String displayName; + private List lore; + + BookItemBuilder() { + } + + public BookItemBuilder instance(EpicEnchants instance) { + this.instance = instance; + return this; + } + + public BookItemBuilder material(Material material) { + this.material = material; + return this; + } + + public BookItemBuilder displayName(String displayName) { + this.displayName = displayName; + return this; + } + + public BookItemBuilder lore(List lore) { + this.lore = lore; + return this; + } + + public BookItem build() { + return new BookItem(instance, material, displayName, lore); + } + + public String toString() { + return "BookItem.BookItemBuilder(instance=" + this.instance + ", material=" + this.material + ", displayName=" + this.displayName + ", lore=" + this.lore + ")"; + } + } } diff --git a/core/src/main/java/com/songoda/epicenchants/objects/Condition.java b/src/main/java/com/songoda/epicenchants/objects/Condition.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/objects/Condition.java rename to src/main/java/com/songoda/epicenchants/objects/Condition.java diff --git a/src/main/java/com/songoda/epicenchants/objects/Enchant.java b/src/main/java/com/songoda/epicenchants/objects/Enchant.java new file mode 100644 index 0000000..328d1f7 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/objects/Enchant.java @@ -0,0 +1,170 @@ +package com.songoda.epicenchants.objects; + +import com.songoda.epicenchants.effect.EffectExecutor; +import com.songoda.epicenchants.enums.EventType; +import com.songoda.epicenchants.enums.TriggerType; +import com.songoda.epicenchants.utils.single.RomanNumber; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Set; + +import static com.songoda.epicenchants.utils.single.GeneralUtils.color; + +public class Enchant { + private String identifier; + private Group group; + private int maxLevel; + private Set conflict; + //TODO: ISSUES + private Set itemWhitelist; + private Set effectExecutors; + private List description; + private String format; + @Nullable private BookItem bookItem; + + Enchant(String identifier, Group group, int maxLevel, Set conflict, Set itemWhitelist, Set effectExecutors, List description, String format, BookItem bookItem) { + this.identifier = identifier; + this.group = group; + this.maxLevel = maxLevel; + this.conflict = conflict; + this.itemWhitelist = itemWhitelist; + this.effectExecutors = effectExecutors; + this.description = description; + this.format = format; + this.bookItem = bookItem; + } + + public static EnchantBuilder builder() { + return new EnchantBuilder(); + } + + public void onAction(@NotNull Player user, @Nullable LivingEntity opponent, Event event, int level, TriggerType triggerType, EventType eventType) { + effectExecutors.forEach(effect -> effect.testAndRun(user, opponent, level, triggerType, event, eventType)); + } + + public BookItem getBook() { + return bookItem != null ? bookItem : group.getBookItem(); + } + + public String getFormat(int level, boolean roman) { + String output = format.isEmpty() ? group.getFormat() : format; + + output = output + .replace("{level}", "" + (roman ? RomanNumber.toRoman(level) : level)) + .replace("{enchant}", "" + identifier) + .replace("{group_color}", "" + group.getColor()); + + return color(output); + } + + public String getIdentifier() { + return this.identifier; + } + + public Group getGroup() { + return this.group; + } + + public int getMaxLevel() { + return this.maxLevel; + } + + public Set getConflict() { + return this.conflict; + } + + public Set getItemWhitelist() { + return this.itemWhitelist; + } + + public Set getEffectExecutors() { + return this.effectExecutors; + } + + public List getDescription() { + return this.description; + } + + public String getFormat() { + return this.format; + } + + @Nullable + public BookItem getBookItem() { + return this.bookItem; + } + + public static class EnchantBuilder { + private String identifier; + private Group group; + private int maxLevel; + private Set conflict; + private Set itemWhitelist; + private Set effectExecutors; + private List description; + private String format; + private BookItem bookItem; + + EnchantBuilder() { + } + + public Enchant.EnchantBuilder identifier(String identifier) { + this.identifier = identifier; + return this; + } + + public Enchant.EnchantBuilder group(Group group) { + this.group = group; + return this; + } + + public Enchant.EnchantBuilder maxLevel(int maxLevel) { + this.maxLevel = maxLevel; + return this; + } + + public Enchant.EnchantBuilder conflict(Set conflict) { + this.conflict = conflict; + return this; + } + + public Enchant.EnchantBuilder itemWhitelist(Set itemWhitelist) { + this.itemWhitelist = itemWhitelist; + return this; + } + + public Enchant.EnchantBuilder effectExecutors(Set effectExecutors) { + this.effectExecutors = effectExecutors; + return this; + } + + public Enchant.EnchantBuilder description(List description) { + this.description = description; + return this; + } + + public Enchant.EnchantBuilder format(String format) { + this.format = format; + return this; + } + + public Enchant.EnchantBuilder bookItem(BookItem bookItem) { + this.bookItem = bookItem; + return this; + } + + public Enchant build() { + return new Enchant(identifier, group, maxLevel, conflict, itemWhitelist, effectExecutors, description, format, bookItem); + } + + public String toString() { + return "Enchant.EnchantBuilder(identifier=" + this.identifier + ", group=" + this.group + ", maxLevel=" + this.maxLevel + ", conflict=" + this.conflict + ", itemWhitelist=" + this.itemWhitelist + ", effectExecutors=" + this.effectExecutors + ", description=" + this.description + ", format=" + this.format + ", bookItem=" + this.bookItem + ")"; + } + } +} diff --git a/src/main/java/com/songoda/epicenchants/objects/Group.java b/src/main/java/com/songoda/epicenchants/objects/Group.java new file mode 100644 index 0000000..bde2453 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/objects/Group.java @@ -0,0 +1,178 @@ +package com.songoda.epicenchants.objects; + +public class Group { + private String identifier; + private String name; + private String format; + private String color; + private String descriptionColor; + private int slotsUsed; + private BookItem bookItem; + private int destroyRateMin, destroyRateMax, successRateMin, successRateMax; + private int tinkererExp; + private int order; + + Group(String identifier, String name, String format, String color, String descriptionColor, int slotsUsed, BookItem bookItem, int destroyRateMin, int destroyRateMax, int successRateMin, int successRateMax, int tinkererExp, int order) { + this.identifier = identifier; + this.name = name; + this.format = format; + this.color = color; + this.descriptionColor = descriptionColor; + this.slotsUsed = slotsUsed; + this.bookItem = bookItem; + this.destroyRateMin = destroyRateMin; + this.destroyRateMax = destroyRateMax; + this.successRateMin = successRateMin; + this.successRateMax = successRateMax; + this.tinkererExp = tinkererExp; + this.order = order; + } + + public static GroupBuilder builder() { + return new GroupBuilder(); + } + + public String getIdentifier() { + return this.identifier; + } + + public String getName() { + return this.name; + } + + public String getFormat() { + return this.format; + } + + public String getColor() { + return this.color; + } + + public String getDescriptionColor() { + return this.descriptionColor; + } + + public int getSlotsUsed() { + return this.slotsUsed; + } + + public BookItem getBookItem() { + return this.bookItem; + } + + public int getDestroyRateMin() { + return this.destroyRateMin; + } + + public int getDestroyRateMax() { + return this.destroyRateMax; + } + + public int getSuccessRateMin() { + return this.successRateMin; + } + + public int getSuccessRateMax() { + return this.successRateMax; + } + + public int getTinkererExp() { + return this.tinkererExp; + } + + public int getOrder() { + return this.order; + } + + public static class GroupBuilder { + private String identifier; + private String name; + private String format; + private String color; + private String descriptionColor; + private int slotsUsed; + private BookItem bookItem; + private int destroyRateMin; + private int destroyRateMax; + private int successRateMin; + private int successRateMax; + private int tinkererExp; + private int order; + + GroupBuilder() { + } + + public Group.GroupBuilder identifier(String identifier) { + this.identifier = identifier; + return this; + } + + public Group.GroupBuilder name(String name) { + this.name = name; + return this; + } + + public Group.GroupBuilder format(String format) { + this.format = format; + return this; + } + + public Group.GroupBuilder color(String color) { + this.color = color; + return this; + } + + public Group.GroupBuilder descriptionColor(String descriptionColor) { + this.descriptionColor = descriptionColor; + return this; + } + + public Group.GroupBuilder slotsUsed(int slotsUsed) { + this.slotsUsed = slotsUsed; + return this; + } + + public Group.GroupBuilder bookItem(BookItem bookItem) { + this.bookItem = bookItem; + return this; + } + + public Group.GroupBuilder destroyRateMin(int destroyRateMin) { + this.destroyRateMin = destroyRateMin; + return this; + } + + public Group.GroupBuilder destroyRateMax(int destroyRateMax) { + this.destroyRateMax = destroyRateMax; + return this; + } + + public Group.GroupBuilder successRateMin(int successRateMin) { + this.successRateMin = successRateMin; + return this; + } + + public Group.GroupBuilder successRateMax(int successRateMax) { + this.successRateMax = successRateMax; + return this; + } + + public Group.GroupBuilder tinkererExp(int tinkererExp) { + this.tinkererExp = tinkererExp; + return this; + } + + public Group.GroupBuilder order(int order) { + this.order = order; + return this; + } + + public Group build() { + return new Group(identifier, name, format, color, descriptionColor, slotsUsed, bookItem, destroyRateMin, destroyRateMax, successRateMin, successRateMax, tinkererExp, order); + } + + public String toString() { + return "Group.GroupBuilder(identifier=" + this.identifier + ", name=" + this.name + ", format=" + this.format + ", color=" + this.color + ", descriptionColor=" + this.descriptionColor + ", slotsUsed=" + this.slotsUsed + ", bookItem=" + this.bookItem + ", destroyRateMin=" + this.destroyRateMin + ", destroyRateMax=" + this.destroyRateMax + ", successRateMin=" + this.successRateMin + ", successRateMax=" + this.successRateMax + ", tinkererExp=" + this.tinkererExp + ", order=" + this.order + ")"; + } + } +} diff --git a/core/src/main/java/com/songoda/epicenchants/objects/LeveledModifier.java b/src/main/java/com/songoda/epicenchants/objects/LeveledModifier.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/objects/LeveledModifier.java rename to src/main/java/com/songoda/epicenchants/objects/LeveledModifier.java diff --git a/core/src/main/java/com/songoda/epicenchants/objects/Placeholder.java b/src/main/java/com/songoda/epicenchants/objects/Placeholder.java similarity index 75% rename from core/src/main/java/com/songoda/epicenchants/objects/Placeholder.java rename to src/main/java/com/songoda/epicenchants/objects/Placeholder.java index 2a0d41c..1b6fb76 100644 --- a/core/src/main/java/com/songoda/epicenchants/objects/Placeholder.java +++ b/src/main/java/com/songoda/epicenchants/objects/Placeholder.java @@ -1,8 +1,5 @@ package com.songoda.epicenchants.objects; -import lombok.Getter; - -@Getter public class Placeholder { private String placeholder; private Object toReplace; @@ -15,4 +12,12 @@ public class Placeholder { public static Placeholder of(String placeholder, Object toReplace) { return new Placeholder(placeholder, toReplace); } + + public String getPlaceholder() { + return placeholder; + } + + public Object getToReplace() { + return toReplace; + } } diff --git a/core/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java b/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java similarity index 74% rename from core/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java rename to src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java index 567d82b..18aa465 100644 --- a/core/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java +++ b/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java @@ -5,11 +5,11 @@ import com.songoda.epicenchants.enums.EnchantResult; import com.songoda.epicenchants.enums.EventType; import com.songoda.epicenchants.enums.TriggerType; import com.songoda.epicenchants.objects.Enchant; +import com.songoda.epicenchants.utils.itemnbtapi.NBTCompound; +import com.songoda.epicenchants.utils.itemnbtapi.NBTItem; import com.songoda.epicenchants.utils.objects.ItemBuilder; +import com.songoda.epicenchants.utils.settings.Setting; import com.songoda.epicenchants.utils.single.GeneralUtils; -import de.tr7zw.itemnbtapi.NBTCompound; -import de.tr7zw.itemnbtapi.NBTItem; -import org.apache.commons.lang3.tuple.Pair; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; @@ -32,7 +32,7 @@ public class EnchantUtils { this.instance = instance; } - public Pair apply(ItemStack itemStack, Enchant enchant, int level, int successRate, int destroyRate) { + public Tuple apply(ItemStack itemStack, Enchant enchant, int level, int successRate, int destroyRate) { boolean hasProtection = new NBTItem(itemStack).hasKey("protected"); Map currentEnchantMap = getEnchants(itemStack); @@ -40,15 +40,15 @@ public class EnchantUtils { Set currentConflicts = currentEnchantMap.keySet().stream().map(Enchant::getConflict).flatMap(Collection::stream).collect(Collectors.toSet()); if (enchant.getConflict().stream().anyMatch(currentIds::contains) || currentConflicts.contains(enchant.getIdentifier())) { - return Pair.of(itemStack, CONFLICT); + return Tuple.of(itemStack, CONFLICT); } if (currentEnchantMap.entrySet().stream().anyMatch(entry -> entry.getKey().equals(enchant) && entry.getValue() == enchant.getMaxLevel())) { - return Pair.of(itemStack, MAXED_OUT); + return Tuple.of(itemStack, MAXED_OUT); } if (currentEnchantMap.entrySet().stream().anyMatch(entry -> entry.getKey().equals(enchant) && entry.getValue() >= level)) { - return Pair.of(itemStack, ALREADY_APPLIED); + return Tuple.of(itemStack, ALREADY_APPLIED); } if (!GeneralUtils.chance(successRate)) { @@ -56,11 +56,11 @@ public class EnchantUtils { if (hasProtection) { NBTItem nbtItem = new ItemBuilder(itemStack).removeLore(instance.getSpecialItems().getWhiteScrollLore()).nbt(); nbtItem.removeKey("protected"); - return Pair.of(nbtItem.getItem(), PROTECTED); + return Tuple.of(nbtItem.getItem(), PROTECTED); } - return Pair.of(new ItemStack(Material.AIR), BROKEN_FAILURE); + return Tuple.of(new ItemStack(Material.AIR), BROKEN_FAILURE); } - return Pair.of(itemStack, FAILURE); + return Tuple.of(itemStack, FAILURE); } ItemBuilder itemBuilder = new ItemBuilder(itemStack); @@ -69,8 +69,8 @@ public class EnchantUtils { itemBuilder.removeLore(instance.getSpecialItems().getWhiteScrollLore()); } - itemBuilder.removeLore(enchant.getFormat(-1, instance.getFileManager().getConfiguration("config").getBoolean("roman-numbers")).replace("-1", "").trim()); - itemBuilder.addLore(enchant.getFormat(level, instance.getFileManager().getConfiguration("config").getBoolean("roman-numbers"))); + itemBuilder.removeLore(enchant.getFormat(-1, Setting.ROMAN.getBoolean()).replace("-1", "").trim()); + itemBuilder.addLore(enchant.getFormat(level, Setting.ROMAN.getBoolean())); if (hasProtection) { itemBuilder.addLore(instance.getSpecialItems().getWhiteScrollLore()); @@ -78,12 +78,12 @@ public class EnchantUtils { NBTItem nbtItem = itemBuilder.nbt(); - nbtItem.addCompound("enchants"); + nbtItem.addCompound("src/main/resources/enchants"); - NBTCompound compound = nbtItem.getCompound("enchants"); + NBTCompound compound = nbtItem.getCompound("src/main/resources/enchants"); compound.setInteger(enchant.getIdentifier(), level); - return Pair.of(nbtItem.getItem(), SUCCESS); + return Tuple.of(nbtItem.getItem(), SUCCESS); } public Map getEnchants(ItemStack itemStack) { @@ -93,11 +93,11 @@ public class EnchantUtils { NBTItem nbtItem = new NBTItem(itemStack); - if (!nbtItem.hasNBTData() || !nbtItem.hasKey("enchants")) { + if (!nbtItem.hasNBTData() || !nbtItem.hasKey("src/main/resources/enchants")) { return Collections.emptyMap(); } - NBTCompound compound = nbtItem.getCompound("enchants"); + NBTCompound compound = nbtItem.getCompound("src/main/resources/enchants"); if (compound == null) { return Collections.emptyMap(); @@ -128,11 +128,11 @@ public class EnchantUtils { NBTItem nbtItem = new NBTItem(itemStack); - if (nbtItem.getCompound("enchants") == null || nbtItem.getCompound("enchants").getInteger(enchant.getIdentifier()) == null) { + if (nbtItem.getCompound("src/main/resources/enchants") == null || nbtItem.getCompound("src/main/resources/enchants").getInteger(enchant.getIdentifier()) == null) { return itemStack; } - nbtItem.getCompound("enchants").removeKey(enchant.getIdentifier()); + nbtItem.getCompound("src/main/resources/enchants").removeKey(enchant.getIdentifier()); ItemBuilder output = new ItemBuilder(nbtItem.getItem()); output.removeLore(enchant.getFormat().replace("{level}", "").trim()); return output.build(); diff --git a/src/main/java/com/songoda/epicenchants/utils/Methods.java b/src/main/java/com/songoda/epicenchants/utils/Methods.java new file mode 100644 index 0000000..7ac7bad --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/Methods.java @@ -0,0 +1,53 @@ +package com.songoda.epicenchants.utils; + +import com.songoda.epicenchants.EpicEnchants; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class Methods { + + public static ItemStack getGlass() { + EpicEnchants instance = EpicEnchants.getInstance(); + return Methods.getGlass(instance.getConfig().getBoolean("Interfaces.Replace Glass Type 1 With Rainbow Glass"), instance.getConfig().getInt("Interfaces.Glass Type 1")); + } + + public static ItemStack getBackgroundGlass(boolean type) { + EpicEnchants instance = EpicEnchants.getInstance(); + if (type) + return getGlass(false, instance.getConfig().getInt("Interfaces.Glass Type 2")); + else + return getGlass(false, instance.getConfig().getInt("Interfaces.Glass Type 3")); + } + + private static ItemStack getGlass(Boolean rainbow, int type) { + int randomNum = 1 + (int) (Math.random() * 6); + ItemStack glass; + if (rainbow) { + glass = new ItemStack(EpicEnchants.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? + Material.LEGACY_STAINED_GLASS_PANE : Material.valueOf("STAINED_GLASS_PANE"), 1, (short) randomNum); + } else { + glass = new ItemStack(EpicEnchants.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? + Material.LEGACY_STAINED_GLASS_PANE : Material.valueOf("STAINED_GLASS_PANE"), 1, (short) type); + } + ItemMeta glassmeta = glass.getItemMeta(); + glassmeta.setDisplayName("§l"); + glass.setItemMeta(glassmeta); + return glass; + } + + public static String formatText(String text) { + if (text == null || text.equals("")) + return ""; + return formatText(text, false); + } + + public static String formatText(String text, boolean cap) { + if (text == null || text.equals("")) + return ""; + if (cap) + text = text.substring(0, 1).toUpperCase() + text.substring(1); + return ChatColor.translateAlternateColorCodes('&', text); + } +} diff --git a/src/main/java/com/songoda/epicenchants/utils/Metrics.java b/src/main/java/com/songoda/epicenchants/utils/Metrics.java new file mode 100644 index 0000000..6179afc --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/Metrics.java @@ -0,0 +1,695 @@ +package com.songoda.epicenchants.utils; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Metrics { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public Metrics(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly blacklist effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has blacklist effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JSONObject getPluginData() { + JSONObject data = new JSONObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.put("pluginName", pluginName); // Append the name of the plugin + data.put("pluginVersion", pluginVersion); // Append the version of the plugin + JSONArray customCharts = new JSONArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JSONObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.put("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JSONObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JSONObject data = new JSONObject(); + + data.put("serverUUID", serverUUID); + + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", bukkitVersion); + + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JSONObject data = getServerData(); + + JSONArray pluginData = new JSONArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + } catch (NoSuchFieldException ignored) { } + } + + data.put("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(new Runnable() { + @Override + public void run() { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data.toString()); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); + + InputStream inputStream = connection.getInputStream(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + + StringBuilder builder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + bufferedReader.close(); + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JSONObject getRequestJsonObject() { + JSONObject chart = new JSONObject(); + chart.put("chartId", chartId); + try { + JSONObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.put("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JSONObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JSONObject value = new JSONObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.put(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.put(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JSONArray categoryValues = new JSONArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.put(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/songoda/epicenchants/utils/ServerVersion.java b/src/main/java/com/songoda/epicenchants/utils/ServerVersion.java new file mode 100644 index 0000000..c442d9b --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/ServerVersion.java @@ -0,0 +1,27 @@ +package com.songoda.epicenchants.utils; + +public enum ServerVersion { + + UNKNOWN("unknown_server_version"), + V1_7("org.bukkit.craftbukkit.v1_7"), + V1_8("org.bukkit.craftbukkit.v1_8"), + V1_9("org.bukkit.craftbukkit.v1_9"), + V1_10("org.bukkit.craftbukkit.v1_10"), + V1_11("org.bukkit.craftbukkit.v1_11"), + V1_12("org.bukkit.craftbukkit.v1_12"), + V1_13("org.bukkit.craftbukkit.v1_13"), + V1_14("org.bukkit.craftbukkit.v1_14"); + + + private final String packagePrefix; + + private ServerVersion(String packagePrefix) { + this.packagePrefix = packagePrefix; + } + + public static ServerVersion fromPackageName(String packageName) { + for (ServerVersion version : values()) + if (packageName.startsWith(version.packagePrefix)) return version; + return ServerVersion.UNKNOWN; + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java b/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java similarity index 94% rename from core/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java rename to src/main/java/com/songoda/epicenchants/utils/SpecialItems.java index ea4a10f..6b68548 100644 --- a/core/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java +++ b/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java @@ -2,8 +2,9 @@ package com.songoda.epicenchants.utils; import com.songoda.epicenchants.EpicEnchants; import com.songoda.epicenchants.objects.Group; +import com.songoda.epicenchants.utils.itemnbtapi.NBTItem; import com.songoda.epicenchants.utils.objects.ItemBuilder; -import de.tr7zw.itemnbtapi.NBTItem; +import com.songoda.epicenchants.utils.settings.Setting; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.inventory.ItemStack; @@ -34,8 +35,8 @@ public class SpecialItems { } public ItemStack getBlackScroll(Integer amount, Integer chance) { - int successRate = chance == null ? ThreadLocalRandom.current().nextInt(instance.getFileManager().getConfiguration("config").getInt("rates.black-scroll-min"), instance.getFileManager().getConfiguration("config").getInt("rates.black-scroll-max") + 1) : chance; - NBTItem nbtItem = new ItemBuilder(instance.getFileManager().getConfiguration("items/special-items").getConfigurationSection("black-scroll"), of("success-rate", successRate)).nbt(); + int successRate = chance == null ? ThreadLocalRandom.current().nextInt(Setting.BLACK_MIN.getInt(), Setting.BLACK_MAX.getInt() + 1) : chance; + NBTItem nbtItem = new ItemBuilder(instance.getFileManager().getConfiguration("items/special-items").getConfigurationSection("black-scroll"), of("success-rate", successRate)).nbt (); nbtItem.setBoolean("black-scroll", true); nbtItem.setInteger("success-rate", successRate); diff --git a/src/main/java/com/songoda/epicenchants/utils/Tuple.java b/src/main/java/com/songoda/epicenchants/utils/Tuple.java new file mode 100644 index 0000000..a8e5185 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/Tuple.java @@ -0,0 +1,23 @@ +package com.songoda.epicenchants.utils; + +public class Tuple { + private key x; + private value y; + + public Tuple(key x, value y) { + this.x = x; + this.y = y; + } + + public key getLeft() { + return this.x; + } + + public value getRight() { + return this.y; + } + + public static Tuple of(key x, value y) { + return new Tuple(x, y); + } +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ClassWrapper.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ClassWrapper.java new file mode 100644 index 0000000..d927dd6 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ClassWrapper.java @@ -0,0 +1,37 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import org.bukkit.Bukkit; + +public enum ClassWrapper { + CRAFT_ITEMSTACK("org.bukkit.craftbukkit.", ".inventory.CraftItemStack"), + CRAFT_ENTITY("org.bukkit.craftbukkit.", ".entity.CraftEntity"), + CRAFT_WORLD("org.bukkit.craftbukkit.", ".CraftWorld"), + NMS_NBTBASE("net.minecraft.server.", ".NBTBase"), + NMS_NBTTAGSTRING("net.minecraft.server.", ".NBTTagString"), + NMS_ITEMSTACK("net.minecraft.server.", ".ItemStack"), + NMS_NBTTAGCOMPOUND("net.minecraft.server.", ".NBTTagCompound"), + NMS_NBTTAGLIST("net.minecraft.server.", ".NBTTagList"), + NMS_NBTCOMPRESSEDSTREAMTOOLS("net.minecraft.server.", ".NBTCompressedStreamTools"), + NMS_MOJANGSONPARSER("net.minecraft.server.", ".MojangsonParser"), + NMS_TILEENTITY("net.minecraft.server.", ".TileEntity"), + NMS_BLOCKPOSITION("net.minecraft.server.", ".BlockPosition"), + NMS_WORLD("net.minecraft.server.", ".WorldServer"), + NMS_ENTITY("net.minecraft.server.", ".Entity"),; + + + private Class clazz; + + ClassWrapper(String pre, String suffix) { + try { + String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + clazz = Class.forName(pre + version + suffix); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public Class getClazz() { + return clazz; + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTCompound.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTCompound.java new file mode 100644 index 0000000..914a57f --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTCompound.java @@ -0,0 +1,200 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import com.songoda.epicbuckets.utils.itemnbtapi.utils.MinecraftVersion; + +import java.util.Set; + + +public class NBTCompound { + + private String compundName; + private NBTCompound parent; + + protected NBTCompound(NBTCompound owner, String name) { + this.compundName = name; + this.parent = owner; + } + + public String getName() { + return compundName; + } + + protected Object getCompound() { + return parent.getCompound(); + } + + protected void setCompound(Object compound) { + parent.setCompound(compound); + } + + public NBTCompound getParent() { + return parent; + } + + public void mergeCompound(NBTCompound comp) { + NBTReflectionUtil.addOtherNBTCompound(this, comp); + } + + public void setString(String key, String value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_STRING, key, value); + } + + public String getString(String key) { + return (String) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_STRING, key); + } + + protected String getContent(String key) { + return NBTReflectionUtil.getContent(this, key); + } + + public void setInteger(String key, Integer value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_INT, key, value); + } + + public Integer getInteger(String key) { + return (Integer) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_INT, key); + } + + public void setDouble(String key, Double value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_DOUBLE, key, value); + } + + public Double getDouble(String key) { + return (Double) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_DOUBLE, key); + } + + public void setByte(String key, Byte value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_BYTE, key, value); + } + + public Byte getByte(String key) { + return (Byte) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_BYTE, key); + } + + public void setShort(String key, Short value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_SHORT, key, value); + } + + public Short getShort(String key) { + return (Short) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_SHORT, key); + } + + public void setLong(String key, Long value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_LONG, key, value); + } + + public Long getLong(String key) { + return (Long) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_LONG, key); + } + + public void setFloat(String key, Float value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_FLOAT, key, value); + } + + public Float getFloat(String key) { + return (Float) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_FLOAT, key); + } + + public void setByteArray(String key, byte[] value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_BYTEARRAY, key, value); + } + + public byte[] getByteArray(String key) { + return (byte[]) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_BYTEARRAY, key); + } + + public void setIntArray(String key, int[] value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_INTARRAY, key, value); + } + + public int[] getIntArray(String key) { + return (int[]) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_INTARRAY, key); + } + + public void setBoolean(String key, Boolean value) { + NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_BOOLEAN, key, value); + } + + protected void set(String key, Object val) { + NBTReflectionUtil.set(this, key, val); + } + + public Boolean getBoolean(String key) { + return (Boolean) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_BOOLEAN, key); + } + + public void setObject(String key, Object value) { + NBTReflectionUtil.setObject(this, key, value); + } + + public T getObject(String key, Class type) { + return NBTReflectionUtil.getObject(this, key, type); + } + + public Boolean hasKey(String key) { + Boolean b = (Boolean) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_HAS_KEY, key); + if (b == null) return false; + return b; + } + + public void removeKey(String key) { + NBTReflectionUtil.remove(this, key); + } + + public Set getKeys() { + return NBTReflectionUtil.getKeys(this); + } + + public NBTCompound addCompound(String name) { + if (getType(name) == NBTType.NBTTagCompound) return getCompound(name); + NBTReflectionUtil.addNBTTagCompound(this, name); + return getCompound(name); + } + + public NBTCompound getCompound(String name) { + NBTCompound next = new NBTCompound(this, name); + if (NBTReflectionUtil.valideCompound(next)) return next; + return null; + } + + public NBTList getList(String name, NBTType type) { + return NBTReflectionUtil.getList(this, name, type); + } + + public NBTType getType(String name) { + if (MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) return null; + Object o = NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_TYPE, name); + if (o == null) return null; + return NBTType.valueOf((byte) o); + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + for (String key : getKeys()) { + result.append(toString(key)); + } + return result.toString(); + } + + public String toString(String key) { + StringBuilder result = new StringBuilder(); + NBTCompound compound = this; + while (compound.getParent() != null) { + result.append(" "); + compound = compound.getParent(); + } + if (this.getType(key) == NBTType.NBTTagCompound) { + return this.getCompound(key).toString(); + } else { + return result + "-" + key + ": " + getContent(key) + System.lineSeparator(); + } + } + + public String asNBTString() { + Object comp = NBTReflectionUtil.gettoCompount(getCompound(), this); + if (comp == null) return "{}"; + return comp.toString(); + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTContainer.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTContainer.java new file mode 100644 index 0000000..6023122 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTContainer.java @@ -0,0 +1,35 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +public class NBTContainer extends NBTCompound { + + private Object nbt; + + public NBTContainer() { + super(null, null); + nbt = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + + protected NBTContainer(Object nbt) { + super(null, null); + this.nbt = nbt; + } + + public NBTContainer(String nbtString) throws IllegalArgumentException { + super(null, null); + try { + nbt = ReflectionMethod.PARSE_NBT.run(null, nbtString); + } catch (Exception ex) { + ex.printStackTrace(); + throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); + } + } + + protected Object getCompound() { + return nbt; + } + + protected void setCompound(Object tag) { + nbt = tag; + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTEntity.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTEntity.java new file mode 100644 index 0000000..7eafb59 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTEntity.java @@ -0,0 +1,22 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import org.bukkit.entity.Entity; + +public class NBTEntity extends NBTCompound { + + private final Entity ent; + + public NBTEntity(Entity entity) { + super(null, null); + ent = entity; + } + + protected Object getCompound() { + return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent)); + } + + protected void setCompound(Object compound) { + NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent)); + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTFile.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTFile.java new file mode 100644 index 0000000..a3f0d4f --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTFile.java @@ -0,0 +1,46 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +public class NBTFile extends NBTCompound { + + private final File file; + private Object nbt; + + public NBTFile(File file) throws IOException { + super(null, null); + this.file = file; + if (file.exists()) { + FileInputStream inputsteam = new FileInputStream(file); + nbt = NBTReflectionUtil.readNBTFile(inputsteam); + } else { + nbt = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + save(); + } + } + + public void save() throws IOException { + if (!file.exists()) { + file.getParentFile().mkdirs(); + file.createNewFile(); + } + FileOutputStream outStream = new FileOutputStream(file); + NBTReflectionUtil.saveNBTFile(nbt, outStream); + } + + public File getFile() { + return file; + } + + protected Object getCompound() { + return nbt; + } + + protected void setCompound(Object compound) { + nbt = compound; + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTItem.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTItem.java new file mode 100644 index 0000000..35536c0 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTItem.java @@ -0,0 +1,52 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import org.bukkit.inventory.ItemStack; + +public class NBTItem extends NBTCompound { + + private ItemStack bukkitItem; + + public NBTItem(ItemStack item) { + super(null, null); + if (item == null) { + throw new NullPointerException("ItemStack can't be null!"); + } + bukkitItem = item.clone(); + } + + public static NBTContainer convertItemtoNBT(ItemStack item) { + return NBTReflectionUtil.convertNMSItemtoNBTCompound(ReflectionMethod.ITEMSTACK_NMSCOPY.run(null, item)); + } + + public static ItemStack convertNBTtoItem(NBTCompound comp) { + return (ItemStack) ReflectionMethod.ITEMSTACK_BUKKITMIRROR.run(null, NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp)); + } + + protected Object getCompound() { + return NBTReflectionUtil.getItemRootNBTTagCompound(ReflectionMethod.ITEMSTACK_NMSCOPY.run(null, bukkitItem)); + } + + protected void setCompound(Object compound) { + Object stack = ReflectionMethod.ITEMSTACK_NMSCOPY.run(null, bukkitItem); + ReflectionMethod.ITEMSTACK_SET_TAG.run(stack, compound); + bukkitItem = (ItemStack) ReflectionMethod.ITEMSTACK_BUKKITMIRROR.run(null, stack); + } + + public ItemStack getItem() { + return bukkitItem; + } + + protected void setItem(ItemStack item) { + bukkitItem = item; + } + + /** + * This may return true even when the NBT is empty. + * + * @return Does the ItemStack have a NBTCompound. + */ + public boolean hasNBTData() { + return getCompound() != null; + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTList.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTList.java new file mode 100644 index 0000000..7209869 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTList.java @@ -0,0 +1,127 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import com.songoda.epicbuckets.utils.itemnbtapi.utils.MinecraftVersion; + +public class NBTList { + + private String listName; + private NBTCompound parent; + private NBTType type; + private Object listObject; + + protected NBTList(NBTCompound owner, String name, NBTType type, Object list) { + parent = owner; + listName = name; + this.type = type; + this.listObject = list; + if (!(type == NBTType.NBTTagString || type == NBTType.NBTTagCompound)) { + System.err.println("List types != String/Compound are currently not implemented!"); + } + } + + protected void save() { + parent.set(listName, listObject); + } + + public NBTListCompound addCompound() { + if (type != NBTType.NBTTagCompound) { + new Throwable("Using Compound method on a non Compound list!").printStackTrace(); + return null; + } + try { + Object compound = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance(); + if (MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_14_R1.getVersionId()) { + ReflectionMethod.LIST_ADD.run(listObject, 0, compound); + } else { + ReflectionMethod.LEGACY_LIST_ADD.run(listObject, compound); + } + return new NBTListCompound(this, compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public NBTListCompound getCompound(int id) { + if (type != NBTType.NBTTagCompound) { + new Throwable("Using Compound method on a non Compound list!").printStackTrace(); + return null; + } + try { + Object compound = ReflectionMethod.LIST_GET.run(listObject, id); + return new NBTListCompound(this, compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public String getString(int i) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return null; + } + try { + return (String) ReflectionMethod.LIST_GET_STRING.run(listObject, i); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public void addString(String s) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return; + } + try { + if (MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_14_R1.getVersionId()) { + ReflectionMethod.LIST_ADD.run(listObject, 0, + ClassWrapper.NMS_NBTTAGSTRING.getClazz().getConstructor(String.class).newInstance(s)); + } else { + ReflectionMethod.LEGACY_LIST_ADD.run(listObject, + ClassWrapper.NMS_NBTTAGSTRING.getClazz().getConstructor(String.class).newInstance(s)); + } + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void setString(int i, String s) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return; + } + try { + ReflectionMethod.LIST_SET.run(listObject, i, + ClassWrapper.NMS_NBTTAGSTRING.getClazz().getConstructor(String.class).newInstance(s)); + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void remove(int i) { + try { + ReflectionMethod.LIST_REMOVE_KEY.run(listObject, i); + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public int size() { + try { + return (int) ReflectionMethod.LIST_SIZE.run(listObject); + } catch (Exception ex) { + ex.printStackTrace(); + } + return -1; + } + + public NBTType getType() { + return type; + } + +} \ No newline at end of file diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTListCompound.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTListCompound.java new file mode 100644 index 0000000..dad69fd --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTListCompound.java @@ -0,0 +1,102 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import java.util.HashSet; +import java.util.Set; + +public class NBTListCompound { + + private NBTList owner; + private Object compound; + + protected NBTListCompound(NBTList parent, Object obj) { + owner = parent; + compound = obj; + } + + public void setString(String key, String value) { + if (value == null) { + remove(key); + return; + } + try { + compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void setInteger(String key, int value) { + try { + compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public int getInteger(String value) { + try { + return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); + } catch (Exception ex) { + ex.printStackTrace(); + } + return 0; + } + + public void setDouble(String key, double value) { + try { + compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public double getDouble(String key) { + try { + return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return 0; + } + + + public String getString(String key) { + try { + return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return ""; + } + + public boolean hasKey(String key) { + try { + return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return false; + } + + @SuppressWarnings("unchecked") + public Set getKeys() { + try { + return (Set) ReflectionMethod.LISTCOMPOUND_GET_KEYS.run(compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return new HashSet<>(); + } + + public void remove(String key) { + try { + compound.getClass().getMethod("remove", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTReflectionUtil.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTReflectionUtil.java new file mode 100644 index 0000000..9c30e55 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTReflectionUtil.java @@ -0,0 +1,347 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import com.songoda.epicbuckets.utils.itemnbtapi.utils.GsonWrapper; +import com.songoda.epicbuckets.utils.itemnbtapi.utils.MinecraftVersion; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Entity; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.Set; +import java.util.Stack; + +public class NBTReflectionUtil { + + public static Object getNMSEntity(Entity entity) { + try { + return ReflectionMethod.CRAFT_ENTITY_GET_HANDLE.run(ClassWrapper.CRAFT_ENTITY.getClazz().cast(entity)); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object readNBTFile(FileInputStream stream) { + try { + return ReflectionMethod.NBTFILE_READ.run(null, stream); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object saveNBTFile(Object nbt, FileOutputStream stream) { + try { + return ReflectionMethod.NBTFILE_WRITE.run(null, nbt, stream); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + @SuppressWarnings({"unchecked"}) + public static Object getItemRootNBTTagCompound(Object nmsitem) { + @SuppressWarnings("rawtypes") + Class clazz = nmsitem.getClass(); + Method method; + try { + method = clazz.getMethod("getTag"); + Object answer = method.invoke(nmsitem); + return answer; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + @SuppressWarnings({"unchecked"}) + public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) { + @SuppressWarnings("rawtypes") + Class clazz = ClassWrapper.NMS_ITEMSTACK.getClazz(); + try { + if (MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_12_R1.getVersionId()) { + Constructor constructor = clazz.getConstructor(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()); + constructor.setAccessible(true); + return constructor.newInstance(nbtcompound.getCompound()); + } else { + Method method = clazz.getMethod("createStack", ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()); + method.setAccessible(true); + return method.invoke(null, nbtcompound.getCompound()); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + @SuppressWarnings({"unchecked"}) + public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) { + @SuppressWarnings("rawtypes") + Class clazz = nmsitem.getClass(); + Method method; + try { + method = clazz.getMethod("save", ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()); + Object answer = method.invoke(nmsitem, ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance()); + return new NBTContainer(answer); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object getEntityNBTTagCompound(Object NMSEntity) { + try { + Object nbt = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance(); + Object answer = ReflectionMethod.NMS_ENTITY_GET_NBT.run(NMSEntity, nbt); + if (answer == null) + answer = nbt; + return answer; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object setEntityNBTTag(Object NBTTag, Object NMSEntity) { + try { + ReflectionMethod.NMS_ENTITY_SET_NBT.run(NMSEntity, NBTTag); + return NMSEntity; + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static Object getTileEntityNBTTagCompound(BlockState tile) { + try { + Object pos = ObjectCreator.NMS_BLOCKPOSITION.getInstance(tile.getX(), tile.getY(), tile.getZ()); + Object cworld = ClassWrapper.CRAFT_WORLD.getClazz().cast(tile.getWorld()); + Object nmsworld = ReflectionMethod.CRAFT_WORLD_GET_HANDLE.run(cworld); + Object o = ReflectionMethod.NMS_WORLD_GET_TILEENTITY.run(nmsworld, pos); + Object tag = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance(); + Object answer = ReflectionMethod.TILEENTITY_GET_NBT.run(o, tag); + if (answer == null) + answer = tag; + return answer; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void setTileEntityNBTTagCompound(BlockState tile, Object comp) { + try { + Object pos = ObjectCreator.NMS_BLOCKPOSITION.getInstance(tile.getX(), tile.getY(), tile.getZ()); + Object cworld = ClassWrapper.CRAFT_WORLD.getClazz().cast(tile.getWorld()); + Object nmsworld = ReflectionMethod.CRAFT_WORLD_GET_HANDLE.run(cworld); + Object o = ReflectionMethod.NMS_WORLD_GET_TILEENTITY.run(nmsworld, pos); + ReflectionMethod.TILEENTITY_SET_NBT.run(o, comp); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @SuppressWarnings("unchecked") + public static Object getSubNBTTagCompound(Object compound, String name) { + @SuppressWarnings("rawtypes") + Class c = compound.getClass(); + Method method; + try { + method = c.getMethod("getCompound", String.class); + Object answer = method.invoke(compound, name); + return answer; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void addNBTTagCompound(NBTCompound comp, String name) { + if (name == null) { + remove(comp, name); + return; + } + Object nbttag = comp.getCompound(); + if (nbttag == null) { + nbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(nbttag, comp); + Method method; + try { + method = workingtag.getClass().getMethod("set", String.class, ClassWrapper.NMS_NBTBASE.getClazz()); + method.invoke(workingtag, name, ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance()); + comp.setCompound(nbttag); + return; + } catch (Exception ex) { + ex.printStackTrace(); + } + return; + } + + public static Boolean valideCompound(NBTCompound comp) { + Object root = comp.getCompound(); + if (root == null) { + root = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + return (gettoCompount(root, comp)) != null; + } + + static Object gettoCompount(Object nbttag, NBTCompound comp) { + Stack structure = new Stack<>(); + while (comp.getParent() != null) { + structure.add(comp.getName()); + comp = comp.getParent(); + } + while (!structure.isEmpty()) { + nbttag = getSubNBTTagCompound(nbttag, structure.pop()); + if (nbttag == null) { + return null; + } + } + return nbttag; + } + + public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + try { + ReflectionMethod.COMPOUND_ADD.run(workingtag, nbtcompound.getCompound()); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static String getContent(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + Method method; + try { + method = workingtag.getClass().getMethod("get", String.class); + return method.invoke(workingtag, key).toString(); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void set(NBTCompound comp, String key, Object val) { + if (val == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + if (!valideCompound(comp)) { + new Throwable("InvalideCompound").printStackTrace(); + return; + } + Object workingtag = gettoCompount(rootnbttag, comp); + Method method; + try { + method = workingtag.getClass().getMethod("set", String.class, ClassWrapper.NMS_NBTBASE.getClazz()); + method.invoke(workingtag, key, val); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static NBTList getList(NBTCompound comp, String key, NBTType type) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + Method method; + try { + method = workingtag.getClass().getMethod("getList", String.class, int.class); + return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId())); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setObject(NBTCompound comp, String key, Object value) { + if (!MinecraftVersion.hasGsonSupport()) return; + try { + String json = GsonWrapper.getString(value); + setData(comp, ReflectionMethod.COMPOUND_SET_STRING, key, json); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static T getObject(NBTCompound comp, String key, Class type) { + if (!MinecraftVersion.hasGsonSupport()) return null; + String json = (String) getData(comp, ReflectionMethod.COMPOUND_GET_STRING, key); + if (json == null) { + return null; + } + return GsonWrapper.deserializeJson(json, type); + } + + public static void remove(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + ReflectionMethod.COMPOUND_REMOVE_KEY.run(workingtag, key); + comp.setCompound(rootnbttag); + } + + @SuppressWarnings("unchecked") + public static Set getKeys(NBTCompound comp) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + return (Set) ReflectionMethod.COMPOUND_GET_KEYS.run(workingtag); + } + + public static void setData(NBTCompound comp, ReflectionMethod type, String key, Object data) { + if (data == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + type.run(workingtag, key, data); + comp.setCompound(rootnbttag); + } + + public static Object getData(NBTCompound comp, ReflectionMethod type, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + return null; + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + return type.run(workingtag, key); + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTTileEntity.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTTileEntity.java new file mode 100644 index 0000000..d9b7dbd --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTTileEntity.java @@ -0,0 +1,22 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import org.bukkit.block.BlockState; + +public class NBTTileEntity extends NBTCompound { + + private final BlockState tile; + + public NBTTileEntity(BlockState tile) { + super(null, null); + this.tile = tile; + } + + protected Object getCompound() { + return NBTReflectionUtil.getTileEntityNBTTagCompound(tile); + } + + protected void setCompound(Object compound) { + NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound); + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTType.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTType.java new file mode 100644 index 0000000..bb68b5a --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/NBTType.java @@ -0,0 +1,34 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +public enum NBTType { + NBTTagEnd(0), + NBTTagByte(1), + NBTTagShort(2), + NBTTagInt(3), + NBTTagLong(4), + NBTTagFloat(5), + NBTTagDouble(6), + NBTTagByteArray(7), + NBTTagIntArray(11), + NBTTagString(8), + NBTTagList(9), + NBTTagCompound(10); + + private final int id; + + NBTType(int i) { + id = i; + } + + public static NBTType valueOf(int id) { + for (NBTType t : values()) + if (t.getId() == id) + return t; + return NBTType.NBTTagEnd; + } + + public int getId() { + return id; + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ObjectCreator.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ObjectCreator.java new file mode 100644 index 0000000..02636a2 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ObjectCreator.java @@ -0,0 +1,28 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import java.lang.reflect.Constructor; + +public enum ObjectCreator { + NMS_NBTTAGCOMPOUND(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()), + NMS_BLOCKPOSITION(ClassWrapper.NMS_BLOCKPOSITION.getClazz(), int.class, int.class, int.class); + + private Constructor construct; + + ObjectCreator(Class clazz, Class... args) { + try { + construct = clazz.getConstructor(args); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public Object getInstance(Object... args) { + try { + return construct.newInstance(args); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ReflectionMethod.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ReflectionMethod.java new file mode 100644 index 0000000..c7b52a8 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/ReflectionMethod.java @@ -0,0 +1,128 @@ +package com.songoda.epicbuckets.utils.itemnbtapi; + +import com.songoda.epicbuckets.utils.itemnbtapi.utils.MinecraftVersion; +import org.bukkit.inventory.ItemStack; + +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Method; + +public enum ReflectionMethod { + + COMPOUND_SET_FLOAT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, float.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setFloat")), + COMPOUND_SET_STRING(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setString")), + COMPOUND_SET_INT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setInt")), + COMPOUND_SET_BYTEARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, byte[].class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setByteArray")), + COMPOUND_SET_INTARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, int[].class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setIntArray")), + COMPOUND_SET_LONG(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, long.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setLong")), + COMPOUND_SET_SHORT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, short.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setShort")), + COMPOUND_SET_BYTE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, byte.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setByte")), + COMPOUND_SET_DOUBLE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, double.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setDouble")), + COMPOUND_SET_BOOLEAN(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, boolean.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setBoolean")), + COMPOUND_ADD(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a")), //FIXME: No Spigot mapping! + + COMPOUND_GET_FLOAT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getFloat")), + COMPOUND_GET_STRING(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getString")), + COMPOUND_GET_INT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getInt")), + COMPOUND_GET_BYTEARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getByteArray")), + COMPOUND_GET_INTARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getIntArray")), + COMPOUND_GET_LONG(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getLong")), + COMPOUND_GET_SHORT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getShort")), + COMPOUND_GET_BYTE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getByte")), + COMPOUND_GET_DOUBLE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getDouble")), + COMPOUND_GET_BOOLEAN(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getBoolean")), + + COMPOUND_REMOVE_KEY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "remove")), + COMPOUND_HAS_KEY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "hasKey")), + COMPOUND_GET_TYPE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "b"), new Since(MinecraftVersion.MC1_9_R1, "d")), //FIXME: No Spigot mapping! + COMPOUND_GET_KEYS(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "c"), new Since(MinecraftVersion.MC1_13_R1, "getKeys")), + + LISTCOMPOUND_GET_KEYS(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "c"), new Since(MinecraftVersion.MC1_13_R1, "getKeys")), + LIST_REMOVE_KEY(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a"), new Since(MinecraftVersion.MC1_9_R1, "remove")), + LIST_SIZE(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "size")), + LIST_SET(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class, ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a"), new Since(MinecraftVersion.MC1_13_R1, "set")), + LEGACY_LIST_ADD(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_13_R2, new Since(MinecraftVersion.MC1_7_R4, "add")), + LIST_ADD(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class, ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "add")), + LIST_GET_STRING(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getString")), + LIST_GET(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get")), + + ITEMSTACK_SET_TAG(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setTag")), + ITEMSTACK_NMSCOPY(ClassWrapper.CRAFT_ITEMSTACK.getClazz(), new Class[]{ItemStack.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "asNMSCopy")), + ITEMSTACK_BUKKITMIRROR(ClassWrapper.CRAFT_ITEMSTACK.getClazz(), new Class[]{ClassWrapper.NMS_ITEMSTACK.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "asCraftMirror")), + + CRAFT_WORLD_GET_HANDLE(ClassWrapper.CRAFT_WORLD.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getHandle")), + NMS_WORLD_GET_TILEENTITY(ClassWrapper.NMS_WORLD.getClazz(), new Class[]{ClassWrapper.NMS_BLOCKPOSITION.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTileEntity")), + + TILEENTITY_GET_NBT(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "b"), new Since(MinecraftVersion.MC1_9_R1, "save")), + TILEENTITY_SET_NBT(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "a"), new Since(MinecraftVersion.MC1_12_R1, "load")), + + CRAFT_ENTITY_GET_HANDLE(ClassWrapper.CRAFT_ENTITY.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getHandle")), + NMS_ENTITY_SET_NBT(ClassWrapper.NMS_ENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "f")), //FIXME: No Spigot mapping! + NMS_ENTITY_GET_NBT(ClassWrapper.NMS_ENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "e"), new Since(MinecraftVersion.MC1_12_R1, "save")), + + NBTFILE_READ(ClassWrapper.NMS_NBTCOMPRESSEDSTREAMTOOLS.getClazz(), new Class[]{InputStream.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a")), //FIXME: No Spigot mapping! + NBTFILE_WRITE(ClassWrapper.NMS_NBTCOMPRESSEDSTREAMTOOLS.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), OutputStream.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a")), //FIXME: No Spigot mapping! + + + PARSE_NBT(ClassWrapper.NMS_MOJANGSONPARSER.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "parse")), + + ; + + private MinecraftVersion removedAfter; + private Since targetVersion; + private Method method; + private boolean loaded = false; + private boolean compatible = false; + + ReflectionMethod(Class targetClass, Class[] args, MinecraftVersion addedSince, MinecraftVersion removedAfter, Since... methodnames) { + this.removedAfter = removedAfter; + MinecraftVersion server = MinecraftVersion.getVersion(); + if (server.compareTo(addedSince) < 0 || (this.removedAfter != null && server.getVersionId() > this.removedAfter.getVersionId())) + return; + compatible = true; + Since target = methodnames[0]; + for (Since s : methodnames) { + if (s.version.getVersionId() <= server.getVersionId() && target.version.getVersionId() < s.version.getVersionId()) + target = s; + } + targetVersion = target; + try { + method = targetClass.getMethod(targetVersion.name, args); + method.setAccessible(true); + loaded = true; + } catch (NullPointerException | NoSuchMethodException | SecurityException ex) { + ex.printStackTrace(); + } + } + + ReflectionMethod(Class targetClass, Class[] args, MinecraftVersion addedSince, Since... methodnames) { + this(targetClass, args, addedSince, null, methodnames); + } + + public Object run(Object target, Object... args) { + try { + return method.invoke(target, args); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public boolean isLoaded() { + return loaded; + } + + public boolean isCompatible() { + return compatible; + } + + public static class Since { + public final MinecraftVersion version; + public final String name; + + public Since(MinecraftVersion version, String name) { + this.version = version; + this.name = name; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/utils/GsonWrapper.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/utils/GsonWrapper.java new file mode 100644 index 0000000..5c85128 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/utils/GsonWrapper.java @@ -0,0 +1,27 @@ +package com.songoda.epicbuckets.utils.itemnbtapi.utils; + +import com.google.gson.Gson; + +public class GsonWrapper { + + private static final Gson gson = new Gson(); + + public static String getString(Object obj) { + return gson.toJson(obj); + } + + public static T deserializeJson(String json, Class type) { + try { + if (json == null) { + return null; + } + + T obj = gson.fromJson(json, type); + return type.cast(obj); + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/utils/MinecraftVersion.java b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/utils/MinecraftVersion.java new file mode 100644 index 0000000..2e5ae66 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/itemnbtapi/utils/MinecraftVersion.java @@ -0,0 +1,63 @@ +package com.songoda.epicbuckets.utils.itemnbtapi.utils; + +import org.bukkit.Bukkit; + +public enum MinecraftVersion { + Unknown(Integer.MAX_VALUE),//Use the newest known mappings + MC1_7_R4(174), + MC1_8_R3(183), + MC1_9_R1(191), + MC1_9_R2(192), + MC1_10_R1(1101), + MC1_11_R1(1111), + MC1_12_R1(1121), + MC1_13_R1(1131), + MC1_13_R2(1132), + MC1_14_R1(1141); + + private static MinecraftVersion version; + private static Boolean hasGsonSupport; + + private final int versionId; + + MinecraftVersion(int versionId) { + this.versionId = versionId; + } + + public int getVersionId() { + return versionId; + } + + public static MinecraftVersion getVersion() { + if (version != null) { + return version; + } + final String ver = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + System.out.println("[NBTAPI] Found Spigot: " + ver + "! Trying to find NMS support"); + try { + version = MinecraftVersion.valueOf(ver.replace("v", "MC")); + } catch (IllegalArgumentException ex) { + version = MinecraftVersion.Unknown; + } + if (version != Unknown) { + System.out.println("[NBTAPI] NMS support '" + version.name() + "' loaded!"); + } else { + System.out.println("[NBTAPI] Wasn't able to find NMS Support! Some functions may not work!"); + } + return version; + } + + public static boolean hasGsonSupport() { + if (hasGsonSupport != null) { + return hasGsonSupport; + } + try { + System.out.println("Found Gson: " + Class.forName("com.google.gson.Gson")); + hasGsonSupport = true; + } catch (Exception ex) { + hasGsonSupport = false; + } + return hasGsonSupport; + } + +} \ No newline at end of file diff --git a/src/main/java/com/songoda/epicenchants/utils/locale/Locale.java b/src/main/java/com/songoda/epicenchants/utils/locale/Locale.java new file mode 100644 index 0000000..a12f68b --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/locale/Locale.java @@ -0,0 +1,302 @@ +package com.songoda.ultimateclaims.utils.locale; + +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Assists in the utilization of localization files. + * Created to be used by the Songoda Team. + * + * @author Brianna O'Keefe - Songoda + */ +public class Locale { + + private static final List LOCALES = new ArrayList<>(); + private static final Pattern NODE_PATTERN = Pattern.compile("(\\w+(?:\\.{1}\\w+)*)\\s*=\\s*\"(.*)\""); + private static final String FILE_EXTENSION = ".lang"; + private static JavaPlugin plugin; + private static File localeFolder; + + private final Map nodes = new HashMap<>(); + + private static String defaultLocale; + + private File file; + private String name; + + /** + * Instantiate the Locale class for future use + * + * @param name the name of the instantiated language + */ + private Locale(String name) { + if (plugin == null) + return; + + this.name = name; + + String fileName = name + FILE_EXTENSION; + this.file = new File(localeFolder, fileName); + + if (!this.reloadMessages()) return; + + plugin.getLogger().info("Loaded locale \"" + fileName + "\""); + } + + /** + * Initialize the class to load all existing language files and update them. + * This must be called before any other methods in this class as otherwise + * the methods will fail to invoke + * + * @param plugin the plugin instance + * @param defaultLocale the default language + */ + public Locale(JavaPlugin plugin, String defaultLocale) { + + Locale.plugin = plugin; + Locale.localeFolder = new File(plugin.getDataFolder(), "locales/"); + + if (!localeFolder.exists()) localeFolder.mkdirs(); + + //Save the default locale file. + Locale.defaultLocale = defaultLocale; + saveLocale(defaultLocale); + + for (File file : localeFolder.listFiles()) { + String fileName = file.getName(); + if (!fileName.endsWith(FILE_EXTENSION)) continue; + + String name = fileName.substring(0, fileName.lastIndexOf('.')); + + if (name.split("_").length != 2) continue; + if (localeLoaded(name)) continue; + + LOCALES.add(new Locale(name)); + } + } + + /** + * Save a locale file from the InputStream, to the locale folder + * + * @param fileName the name of the file to save + * @return true if the operation was successful, false otherwise + */ + public static boolean saveLocale(String fileName) { + return saveLocale(plugin.getResource(defaultLocale + FILE_EXTENSION), fileName); + } + + + /** + * Save a locale file from the InputStream, to the locale folder + * + * @param in file to save + * @param fileName the name of the file to save + * @return true if the operation was successful, false otherwise + */ + public static boolean saveLocale(InputStream in, String fileName) { + if (!localeFolder.exists()) localeFolder.mkdirs(); + + if (!fileName.endsWith(FILE_EXTENSION)) + fileName = (fileName.lastIndexOf(".") == -1 ? fileName : fileName.substring(0, fileName.lastIndexOf('.'))) + FILE_EXTENSION; + + File destinationFile = new File(localeFolder, fileName); + if (destinationFile.exists()) + return compareFiles(in, destinationFile); + + try (OutputStream outputStream = new FileOutputStream(destinationFile)) { + copy(in, outputStream); + + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + + if (fileName.split("_").length != 2) return false; + + LOCALES.add(new Locale(fileName)); + if (defaultLocale == null) defaultLocale = fileName; + return true; + } catch (IOException e) { + return false; + } + } + + // Write new changes to existing files, if any at all + private static boolean compareFiles(InputStream in, File existingFile) { + InputStream defaultFile = + in == null ? plugin.getResource((defaultLocale != null ? defaultLocale : "en_US") + FILE_EXTENSION) : in; + + boolean changed = false; + + List defaultLines, existingLines; + try (BufferedReader defaultReader = new BufferedReader(new InputStreamReader(defaultFile)); + BufferedReader existingReader = new BufferedReader(new FileReader(existingFile)); + BufferedWriter writer = new BufferedWriter(new FileWriter(existingFile, true))) { + defaultLines = defaultReader.lines().collect(Collectors.toList()); + existingLines = existingReader.lines().map(s -> s.split("\\s*=")[0]).collect(Collectors.toList()); + + for (String defaultValue : defaultLines) { + if (defaultValue.isEmpty() || defaultValue.startsWith("#")) continue; + + String key = defaultValue.split("\\s*=")[0]; + + if (!existingLines.contains(key)) { + if (!changed) { + writer.newLine(); + writer.newLine(); + // Leave a note alerting the user of the newly added messages. + writer.write("# New messages for " + plugin.getName() + " v" + plugin.getDescription().getVersion() + "."); + + // If changes were found outside of the default file leave a note explaining that. + if (in == null) { + writer.newLine(); + writer.write("# These translations were found untranslated, join"); + writer.newLine(); + writer.write("# our translation Discord https://discord.gg/f7fpZEf"); + writer.newLine(); + writer.write("# to request an official update!"); + } + } + + writer.newLine(); + writer.write(defaultValue); + + changed = true; + } + } + if (in != null && !changed) compareFiles(null, existingFile); + } catch (IOException e) { + return false; + } + + return changed; + } + + + /** + * Check whether a locale exists and is registered or not + * + * @param name the whole language tag (i.e. "en_US") + * @return true if it exists + */ + public static boolean localeLoaded(String name) { + for (Locale locale : LOCALES) + if (locale.getName().equals(name)) return true; + return false; + } + + + /** + * Get a locale by its entire proper name (i.e. "en_US") + * + * @param name the full name of the locale + * @return locale of the specified name + */ + public static Locale getLocale(String name) { + for (Locale locale : LOCALES) + if (locale.getName().equalsIgnoreCase(name)) return locale; + return null; + } + + /** + * Clear the previous message cache and load new messages directly from file + * + * @return reload messages from file + */ + public boolean reloadMessages() { + if (!this.file.exists()) { + plugin.getLogger().warning("Could not find file for locale \"" + this.name + "\""); + return false; + } + + this.nodes.clear(); // Clear previous data (if any) + + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + String line; + for (int lineNumber = 0; (line = reader.readLine()) != null; lineNumber++) { + if (line.trim().isEmpty() || line.startsWith("#") /* Comment */) continue; + + Matcher matcher = NODE_PATTERN.matcher(line); + if (!matcher.find()) { + System.err.println("Invalid locale syntax at (line=" + lineNumber + ")"); + continue; + } + + nodes.put(matcher.group(1), matcher.group(2)); + } + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * Supply the Message object with the plugins prefix. + * + * @param message message to be applied + * @return applied message + */ + private Message supplyPrefix(Message message) { + return message.setPrefix(this.nodes.getOrDefault("general.nametag.prefix", "[Plugin]")); + } + + /** + * Create a new unsaved Message + * + * @param message the message to create + * @return the created message + */ + public Message newMessage(String message) { + return supplyPrefix(new Message(message)); + } + + /** + * Get a message set for a specific node. + * + * @param node the node to get + * @return the message for the specified node + */ + public Message getMessage(String node) { + return this.getMessageOrDefault(node, node); + } + + /** + * Get a message set for a specific node + * + * @param node the node to get + * @param defaultValue the default value given that a value for the node was not found + * @return the message for the specified node. Default if none found + */ + public Message getMessageOrDefault(String node, String defaultValue) { + return supplyPrefix(new Message(this.nodes.getOrDefault(node, defaultValue))); + } + + /** + * Return the locale name (i.e. "en_US") + * + * @return the locale name + */ + public String getName() { + return name; + } + + private static void copy(InputStream input, OutputStream output) { + int n; + byte[] buffer = new byte[1024 * 4]; + + try { + while ((n = input.read(buffer)) != -1) { + output.write(buffer, 0, n); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/songoda/epicenchants/utils/locale/Message.java b/src/main/java/com/songoda/epicenchants/utils/locale/Message.java new file mode 100644 index 0000000..7ad2f6b --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/locale/Message.java @@ -0,0 +1,128 @@ +package com.songoda.ultimateclaims.utils.locale; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +/** + * The Message object. This holds the message to be sent + * as well as the plugins prefix so that they can both be + * easily manipulated then deployed + */ +public class Message { + + private String prefix = null; + private String message; + + /** + * create a new message + * + * @param message the message text + */ + public Message(String message) { + this.message = message; + } + + /** + * Format and send the held message to a player + * + * @param player player to send the message to + */ + public void sendMessage(Player player) { + player.sendMessage(this.getMessage()); + } + + /** + * Format and send the held message with the + * appended plugin prefix to a player + * + * @param player player to send the message to + */ + public void sendPrefixedMessage(Player player) { + player.sendMessage(this.getPrefixedMessage()); + } + + /** + * Format and send the held message to a player + * + * @param sender command sender to send the message to + */ + public void sendMessage(CommandSender sender) { + sender.sendMessage(this.getMessage()); + } + + /** + * Format and send the held message to a player as a title message + * + * @param sender command sender to send the message to + */ + public void sendTitle(CommandSender sender) { + if(sender instanceof Player) { + ((Player) sender).sendTitle("", this.getMessage(), 10, 20, 10); + } else { + sender.sendMessage(this.getMessage()); + } + } + + /** + * Format and send the held message with the + * appended plugin prefix to a command sender + * + * @param sender command sender to send the message to + */ + public void sendPrefixedMessage(CommandSender sender) { + sender.sendMessage(this.getPrefixedMessage()); + } + + /** + * Format the held message and append the plugins + * prefix + * + * @return the prefixed message + */ + public String getPrefixedMessage() { + return ChatColor.translateAlternateColorCodes('&',(prefix == null ? "" : this.prefix) + + " " + this.message); + } + + /** + * Get and format the held message + * + * @return the message + */ + public String getMessage() { + return ChatColor.translateAlternateColorCodes('&', this.message); + } + + /** + * Get the held message + * + * @return the message + */ + public String getUnformattedMessage() { + return this.message; + } + + /** + * Replace the provided placeholder with the + * provided object + * + * @param placeholder the placeholder to replace + * @param replacement the replacement object + * @return the modified Message + */ + public Message processPlaceholder(String placeholder, Object replacement) { + this.message = message.replace("%" + placeholder + "%", replacement.toString()); + return this; + } + + Message setPrefix(String prefix) { + this.prefix = prefix; + return this; + } + + @Override + public String toString() { + return this.message; + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicenchants/utils/objects/FastInv.java b/src/main/java/com/songoda/epicenchants/utils/objects/FastInv.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/utils/objects/FastInv.java rename to src/main/java/com/songoda/epicenchants/utils/objects/FastInv.java diff --git a/src/main/java/com/songoda/epicenchants/utils/objects/FileLocation.java b/src/main/java/com/songoda/epicenchants/utils/objects/FileLocation.java new file mode 100644 index 0000000..1364fb2 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/objects/FileLocation.java @@ -0,0 +1,4 @@ +package com.songoda.epicenchants.utils.objects; + +public class FIleLocation { +} diff --git a/core/src/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java b/src/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java rename to src/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java diff --git a/src/main/java/com/songoda/epicenchants/utils/settings/Category.java b/src/main/java/com/songoda/epicenchants/utils/settings/Category.java new file mode 100644 index 0000000..221b2fb --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/settings/Category.java @@ -0,0 +1,31 @@ +package com.songoda.ultimateclaims.utils.settings; + +public enum Category { + + MAIN("General settings and options."), + + INTERFACES("These settings allow you to alter the way interfaces look.", + "They are used in GUI's to make paterns, change them up then open up a", + "GUI to see how it works."), + + ENTITIES("Stacked Entity Settings."), + + ITEMS("Stacked Item Settings."), + + SPAWNERS("Stacked Spawner Settings."), + + DATABASE("Settings regarding the Database."), + + SYSTEM("System related settings."); + + private String[] comments; + + + Category(String... comments) { + this.comments = comments; + } + + public String[] getComments() { + return comments; + } +} \ No newline at end of file diff --git a/src/main/java/com/songoda/epicenchants/utils/settings/Setting.java b/src/main/java/com/songoda/epicenchants/utils/settings/Setting.java new file mode 100644 index 0000000..70ed8a9 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/settings/Setting.java @@ -0,0 +1,156 @@ +package com.songoda.ultimateclaims.utils.settings; + + +import com.songoda.ultimateclaims.UltimateClaims; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public enum Setting { + + POWERCELL_RECIPE("Main.PowerCell Recipe", + Arrays.asList("3:IRON_INGOT", "4:DIAMOND", "5:IRON_INGOT", + "12:DIAMOND", "13:IRON_INGOT", "14:DIAMOND", + "21:IRON_INGOT", "22:DIAMOND", "23:IRON_INGOT"), + "The recipe players will need to place into a chest", + "in order to create a powercell."), + + ITEM_VALUES("Main.PowerCell Item Values", + Arrays.asList("DIAMOND:120", "IRON_INGOT:30"), + "The value in minutes of each item put into the powercell."), + + ECONOMY_VALUE("Main.PowerCell Economy Value", 100, + "How much money should constitute one minute?"), + + MINIMUM_POWER("Main.Minimum PowerCell power", -30, + "The minimum amount of power allowed before a claim", + "auto dissolves."), + + POWERCELL_HOLOGRAMS("Main.Powercell Holograms", true, + "Should holograms be placed above powercells?"), + + CLAIMS_BOSSBAR("Main.Claims Use Boss Bar", false, + "Display a boss bar to players while they're in a claim?", + "Default behavior is to show a title on entry/exit."), + + CHUNKS_MUST_TOUCH("Main.Chunks Must Touch", true, + "Should chunks have to touch to be claimed?", + "This prevents people from claiming little pieces all over the place."), + + INVITE_TIMEOUT("Main.Invite Timeout", 30, + "The amount of time before an invite times out."), + + STARTING_POWER("Main.Starting Power", 10, + "The starting amount of power in minutes a claim gets.", + "This time should be used to create a powercell."), + + MAX_CHUNKS("Main.Max Chunks", 10, + "The maximum amount of chunks a claim can have."), + + MAX_MEMBERS("Main.Max Members", 10, + "The maximum amount of members a claim can have."), + + VAULT_ECONOMY("Economy.Use Vault Economy", true, + "Should Vault be used?"), + + RESERVE_ECONOMY("Economy.Use Reserve Economy", true, + "Should Reserve be used?"), + + PLAYER_POINTS_ECONOMY("Economy.Use Player Points Economy", false, + "Should PlayerPoints be used?"), + + GLASS_TYPE_1("Interfaces.Glass Type 1", 7), + GLASS_TYPE_2("Interfaces.Glass Type 2", 11), + GLASS_TYPE_3("Interfaces.Glass Type 3", 3), + + LANGUGE_MODE("System.Language Mode", "en_US", + "The enabled language file.", + "More language files (if available) can be found in the plugins data folder."), + + MYSQL_ENABLED("MySQL.Enabled", false, "Set to 'true' to use MySQL instead of SQLite for data storage."), + MYSQL_HOSTNAME("MySQL.Hostname", "localhost"), + MYSQL_PORT("MySQL.Port", 3306), + MYSQL_DATABASE("MySQL.Database", "your-database"), + MYSQL_USERNAME("MySQL.Username", "user"), + MYSQL_PASSWORD("MySQL.Password", "pass"), + MYSQL_USE_SSL("MySQL.Use SSL", false); + + private String setting; + private Object option; + private String[] comments; + + Setting(String setting, Object option, String... comments) { + this.setting = setting; + this.option = option; + this.comments = comments; + } + + Setting(String setting, Object option) { + this.setting = setting; + this.option = option; + this.comments = null; + } + + public static Setting getSetting(String setting) { + List settings = Arrays.stream(values()).filter(setting1 -> setting1.setting.equals(setting)).collect(Collectors.toList()); + if (settings.isEmpty()) return null; + return settings.get(0); + } + + public String getSetting() { + return setting; + } + + public Object getOption() { + return option; + } + + public String[] getComments() { + return comments; + } + + public List getIntegerList() { + return UltimateClaims.getInstance().getConfig().getIntegerList(setting); + } + + public List getStringList() { + return UltimateClaims.getInstance().getConfig().getStringList(setting); + } + + public boolean getBoolean() { + return UltimateClaims.getInstance().getConfig().getBoolean(setting); + } + + public int getInt() { + return UltimateClaims.getInstance().getConfig().getInt(setting); + } + + public long getLong() { + return UltimateClaims.getInstance().getConfig().getLong(setting); + } + + public String getString() { + return UltimateClaims.getInstance().getConfig().getString(setting); + } + + public char getChar() { + return UltimateClaims.getInstance().getConfig().getString(setting).charAt(0); + } + + public double getDouble() { + return UltimateClaims.getInstance().getConfig().getDouble(setting); + } + + public Material getMaterial() { + String materialStr = UltimateClaims.getInstance().getConfig().getString(setting); + Material material = Material.getMaterial(materialStr); + + if (material == null) { + System.out.println(String.format("Config value \"%s\" has an invalid material name: \"%s\"", setting, materialStr)); + } + + return material; + } +} \ No newline at end of file diff --git a/src/main/java/com/songoda/epicenchants/utils/settings/SettingsManager.java b/src/main/java/com/songoda/epicenchants/utils/settings/SettingsManager.java new file mode 100644 index 0000000..8dda56b --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/settings/SettingsManager.java @@ -0,0 +1,311 @@ +package com.songoda.ultimateclaims.utils.settings; + +import com.songoda.ultimateclaims.UltimateClaims; +import com.songoda.ultimateclaims.utils.Methods; +import com.songoda.ultimateclaims.utils.ServerVersion; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.io.*; +import java.util.*; + +/** + * Created by songoda on 6/4/2017. + */ +public class SettingsManager implements Listener { + + private final UltimateClaims plugin; + private Map cat = new HashMap<>(); + private Map current = new HashMap<>(); + + public SettingsManager(UltimateClaims plugin) { + this.plugin = plugin; + Bukkit.getPluginManager().registerEvents(this, plugin); + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + if (event.getView().getType() != InventoryType.CHEST) return; + ItemStack clickedItem = event.getCurrentItem(); + + if (event.getInventory() != event.getWhoClicked().getOpenInventory().getTopInventory() + || clickedItem == null || !clickedItem.hasItemMeta() + || !clickedItem.getItemMeta().hasDisplayName()) { + return; + } + + if (event.getView().getTitle().equals(plugin.getName() + " Settings Manager")) { + event.setCancelled(true); + if (clickedItem.getType().name().contains("STAINED_GLASS")) return; + + String type = ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName()); + this.cat.put((Player) event.getWhoClicked(), type); + this.openEditor((Player) event.getWhoClicked()); + } else if (event.getView().getTitle().equals(plugin.getName() + " Settings Editor")) { + event.setCancelled(true); + if (clickedItem.getType().name().contains("STAINED_GLASS")) return; + + Player player = (Player) event.getWhoClicked(); + + String key = cat.get(player) + "." + ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName()); + + if (plugin.getConfig().get(key).getClass().getName().equals("java.lang.Boolean")) { + this.plugin.getConfig().set(key, !plugin.getConfig().getBoolean(key)); + this.finishEditing(player); + } else { + this.editObject(player, key); + } + } + } + + @EventHandler + public void onChat(AsyncPlayerChatEvent event) { + Player player = event.getPlayer(); + if (!current.containsKey(player)) return; + + String value = current.get(player); + FileConfiguration config = plugin.getConfig(); + if (config.isLong(value)) { + config.set(value, Long.parseLong(event.getMessage())); + } else if (config.isInt(value)) { + config.set(value, Integer.parseInt(event.getMessage())); + } else if (config.isDouble(value)) { + config.set(value, Double.parseDouble(event.getMessage())); + } else if (config.isString(value)) { + config.set(value, event.getMessage()); + } + + Bukkit.getScheduler().scheduleSyncDelayedTask(UltimateClaims.getInstance(), () -> + this.finishEditing(player), 0L); + + event.setCancelled(true); + } + + private void finishEditing(Player player) { + this.current.remove(player); + this.saveConfig(); + this.openEditor(player); + } + + private void editObject(Player player, String current) { + this.current.put(player, ChatColor.stripColor(current)); + + player.closeInventory(); + player.sendMessage(""); + player.sendMessage(Methods.formatText("&7Please enter a value for &6" + current + "&7.")); + if (plugin.getConfig().isInt(current) || plugin.getConfig().isDouble(current)) { + player.sendMessage(Methods.formatText("&cUse only numbers.")); + } + player.sendMessage(""); + } + + public void openSettingsManager(Player player) { + Inventory inventory = Bukkit.createInventory(null, 27, plugin.getName() + " Settings Manager"); + ItemStack glass = Methods.getGlass(); + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, glass); + } + + int slot = 10; + for (String key : plugin.getConfig().getDefaultSection().getKeys(false)) { + ItemStack item = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.LEGACY_WOOL : Material.valueOf("WOOL"), 1, (byte) (slot - 9)); + ItemMeta meta = item.getItemMeta(); + meta.setLore(Collections.singletonList(Methods.formatText("&6Click To Edit This Category."))); + meta.setDisplayName(Methods.formatText("&f&l" + key)); + item.setItemMeta(meta); + inventory.setItem(slot, item); + slot++; + } + + player.openInventory(inventory); + } + + private void openEditor(Player player) { + Inventory inventory = Bukkit.createInventory(null, 54, plugin.getName() + " Settings Editor"); + FileConfiguration config = plugin.getConfig(); + + int slot = 0; + for (String key : config.getConfigurationSection(cat.get(player)).getKeys(true)) { + String fKey = cat.get(player) + "." + key; + ItemStack item = new ItemStack(Material.DIAMOND_HELMET); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(Methods.formatText("&6" + key)); + + List lore = new ArrayList<>(); + if (config.isBoolean(fKey)) { + item.setType(Material.LEVER); + lore.add(Methods.formatText(config.getBoolean(fKey) ? "&atrue" : "&cfalse")); + } else if (config.isString(fKey)) { + item.setType(Material.PAPER); + lore.add(Methods.formatText("&7" + config.getString(fKey))); + } else if (config.isInt(fKey)) { + item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH")); + lore.add(Methods.formatText("&7" + config.getInt(fKey))); + } else if (config.isLong(fKey)) { + item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH")); + lore.add(Methods.formatText("&7" + config.getLong(fKey))); + } else if (config.isDouble(fKey)) { + item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH")); + lore.add(Methods.formatText("&7" + config.getDouble(fKey))); + } + + Setting setting = Setting.getSetting(fKey); + + if (setting != null && setting.getComments() != null) { + lore.add(""); + + String comment = String.join(" ", setting.getComments()); + + int lastIndex = 0; + for (int n = 0; n < comment.length(); n++) { + if (n - lastIndex < 30) + continue; + + if (comment.charAt(n) == ' ') { + lore.add(Methods.formatText("&8" + comment.substring(lastIndex, n).trim())); + lastIndex = n; + } + } + + if (lastIndex - comment.length() < 30) + lore.add(Methods.formatText("&8" + comment.substring(lastIndex).trim())); + + } + + meta.setLore(lore); + item.setItemMeta(meta); + + inventory.setItem(slot, item); + slot++; + } + + player.openInventory(inventory); + } + + public void reloadConfig() { + plugin.reloadConfig(); + this.setupConfig(); + } + + public void setupConfig() { + FileConfiguration config = plugin.getConfig(); + + for (Setting setting : Setting.values()) { + config.addDefault(setting.getSetting(), setting.getOption()); + } + plugin.getConfig().options().copyDefaults(true); + saveConfig(); + } + + private void saveConfig() { + String dump = plugin.getConfig().saveToString(); + + StringBuilder config = new StringBuilder(); + + BufferedReader bufReader = new BufferedReader(new StringReader(dump)); + + try { + boolean first = true; + + String line; + int currentTab = 0; + String category = ""; + + while ((line = bufReader.readLine()) != null) { + if (line.trim().startsWith("#")) continue; + + int tabChange = line.length() - line.trim().length(); + if (currentTab != tabChange) { + category = category.contains(".") && tabChange != 0 ? category.substring(0, category.indexOf(".")) : ""; + currentTab = tabChange; + } + + if (line.endsWith(":")) { + bufReader.mark(1000); + String found = bufReader.readLine(); + bufReader.reset(); + + if (!found.trim().startsWith("-")) { + + String newCategory = line.substring(0, line.length() - 1).trim(); + + if (category.equals("")) + category = newCategory; + else + category += "." + newCategory; + + currentTab = tabChange + 2; + + if (!first) { + config.append("\n\n"); + } else { + first = false; + } + + if (!category.contains(".")) + config.append("#").append("\n"); + try { + Category categoryObj = Category.valueOf(category.toUpperCase() + .replace(" ", "_") + .replace(".", "_")); + + config.append(new String(new char[tabChange]).replace('\0', ' ')); + for (String l : categoryObj.getComments()) + config.append("# ").append(l).append("\n"); + } catch (IllegalArgumentException e) { + config.append("# ").append(category).append("\n"); + } + if (!category.contains(".")) + config.append("#").append("\n"); + + config.append(line).append("\n"); + + continue; + } + } + + if (line.trim().startsWith("-")) { + config.append(line).append("\n"); + continue; + } + + String key = category + "." + (line.split(":")[0].trim()); + for (Setting setting : Setting.values()) { + if (!setting.getSetting().equals(key) || setting.getComments() == null) continue; + config.append(" ").append("\n"); + for (String l : setting.getComments()) { + config.append(new String(new char[currentTab]).replace('\0', ' ')); + config.append("# ").append(l).append("\n"); + } + } + config.append(line).append("\n"); + } + } catch (IOException e) { + e.printStackTrace(); + } + + try { + if (!plugin.getDataFolder().exists()) + plugin.getDataFolder().mkdir(); + BufferedWriter writer = + new BufferedWriter(new FileWriter(new File(plugin.getDataFolder() + File.separator + "config.yml"))); + writer.write(config.toString()); + writer.flush(); + writer.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java b/src/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java rename to src/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java diff --git a/core/src/main/java/com/songoda/epicenchants/utils/single/Experience.java b/src/main/java/com/songoda/epicenchants/utils/single/Experience.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/utils/single/Experience.java rename to src/main/java/com/songoda/epicenchants/utils/single/Experience.java diff --git a/core/src/main/java/com/songoda/epicenchants/utils/single/GeneralUtils.java b/src/main/java/com/songoda/epicenchants/utils/single/GeneralUtils.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/utils/single/GeneralUtils.java rename to src/main/java/com/songoda/epicenchants/utils/single/GeneralUtils.java diff --git a/core/src/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java b/src/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java rename to src/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java diff --git a/core/src/main/java/com/songoda/epicenchants/utils/single/Placeholders.java b/src/main/java/com/songoda/epicenchants/utils/single/Placeholders.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/utils/single/Placeholders.java rename to src/main/java/com/songoda/epicenchants/utils/single/Placeholders.java diff --git a/core/src/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java b/src/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java similarity index 100% rename from core/src/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java rename to src/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java diff --git a/src/main/java/com/songoda/epicenchants/utils/updateModules/LocaleModule.java b/src/main/java/com/songoda/epicenchants/utils/updateModules/LocaleModule.java new file mode 100644 index 0000000..5c2da51 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/utils/updateModules/LocaleModule.java @@ -0,0 +1,32 @@ +package com.songoda.epicenchants.utils.updateModules; + +import com.songoda.epicenchants.EpicEnchants; +import com.songoda.update.Module; +import com.songoda.update.Plugin; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +public class LocaleModule implements Module { + + @Override + public void run(Plugin plugin) { + JSONObject json = plugin.getJson(); + try { + JSONArray files = (JSONArray) json.get("neededFiles"); + for (Object o : files) { + JSONObject file = (JSONObject) o; + + if (file.get("type").equals("locale")) { + InputStream in = new URL((String) file.get("link")).openStream(); + EpicEnchants.getInstance().getLocale().saveLocale(in, (String) file.get("name")); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java b/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java new file mode 100644 index 0000000..e54f636 --- /dev/null +++ b/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java @@ -0,0 +1,56 @@ +package com.songoda.epicenchants.wrappers; + +import com.songoda.epicenchants.objects.LeveledModifier; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class EnchantmentWrapper { + private LeveledModifier amplifier; + private Enchantment enchantment; + + EnchantmentWrapper(LeveledModifier amplifier, Enchantment enchantment) { + this.amplifier = amplifier; + this.enchantment = enchantment; + } + + public static EnchantmentWrapperBuilder builder() { + return new EnchantmentWrapperBuilder(); + } + + public int getAmplifier(int level, @NotNull Player user, @Nullable LivingEntity opponent) { + return (int) amplifier.get(level, 0, user, opponent); + } + + public Enchantment getEnchantment() { + return enchantment; + } + + public static class EnchantmentWrapperBuilder { + private LeveledModifier amplifier; + private Enchantment enchantment; + + EnchantmentWrapperBuilder() { + } + + public EnchantmentWrapperBuilder amplifier(LeveledModifier amplifier) { + this.amplifier = amplifier; + return this; + } + + public EnchantmentWrapperBuilder enchantment(Enchantment enchantment) { + this.enchantment = enchantment; + return this; + } + + public EnchantmentWrapper build() { + return new EnchantmentWrapper(amplifier, enchantment); + } + + public String toString() { + return "EnchantmentWrapper.EnchantmentWrapperBuilder(amplifier=" + this.amplifier + ", enchantment=" + this.enchantment + ")"; + } + } +} diff --git a/src/main/resources/en_US.lang b/src/main/resources/en_US.lang new file mode 100644 index 0000000..c409c2b --- /dev/null +++ b/src/main/resources/en_US.lang @@ -0,0 +1,57 @@ +#General Messages + +general.nametag.prefix = "&8[&6EpicEnchants&8]" + +#Command Messages +command.book.received = "&7You have been given a &6%enchant% &7book." +command.book.gave = "&7You gave &6%player% &7an &6%enchant% &7book." +command.book.maxlevel = "&cThe max level for &4%enchant% &cis &4%maxlevel%&c." +command.book.minlevel = "&cThe min level for &4$enchant% &cis &41&c." + +command.whitescroll.received = "&7You have been given a whitescroll." +command.whitescroll.gave = "&7You gave &6%player% &7a whitescroll." + +command.apply.invaliditem = "&cYou cannot apply &4%enchant% &cto this item." + +command.reload = "&7Configuration files reloaded." + +command.giveunknown = "&cUnknown item to give &4%unknown%&c." + +#Event Messages + +blackscroll.success = "&7Successfully blackscrolled &6%groupcolor%%enchant% %level%&7." +blackscroll.noenchants = "&cNo enchants to blackscroll." + +whitescroll.alreadyapplied = "&cThis item is already protected!" +whitescroll.applied = "&7This item is now protected!" + +enchanter.cannotafford = "&cYou cannot afford this purchase." +enchanter.success = "&7Purchased &6%group_color%%group_name% &7book for &6%exp_cost% experience&7." + +tinkerer.open = "&7Trading with the tinkerer." +tinkerer.cancelled = "&cCancelled." +tinkerer.accepted = "&7Accepted." +tinkerer.noitems = "&cThe tinkerer is not interested in any of your items..." +tinkerer.depositedall = "&7Deposited %amount% items." + +alchemist.maxtwoitems = "&cYou may only combine &42 &citems at once..." +alchemist.notinterested = "&cThe alchemist is not interested in any of your items..." +alchemist.maxlevelbook = "&cThe alchemist cannot combine max leveled books..." +alchemist.maxpercentagedust = "&cThe alchemist cannot combine 100% success rate dust..." +alchemist.highestgroupdust = "&cThe alchemist cannot accept dust of the highest tier." +alchemist.differentenchantment = "&cThe alchemist can only combine books with the same enchantments..." +alchemist.differentlevels = "&cThe alchemist can only combine books of the same level..." +alchemist.differentgroups = "&cThe alchemist can only combine dust of the same group..." +alchemist.cannotafford = "&cYou cannot afford this exchange..." +alchemist.success = "&7Exchanged for &6%expcost% &7experience." + +enchants.invalidmaterial = "&cYou can not apply &4%enchant% &cto that item..." +enchants.failure = "&4%enchant% %cfailed to apply..." +enchants.brokenfailure = "&4%enchant% &cfailed to apply and broke your item..." +enchants.conflict = "&cYou cannot apply this enchant as it conflicts with another enchant..." +enchants.maxedout = "&cYou already have that enchant maxed out on this item..." +enchants.alreadyapplied = "&cYou already have that enchant applied on this item." +enchants.protected = "&7This book would have broken your item, luckily it was protected!" +enchants.success = "&7You have successfully applied &6%enchant%&7." + +book.discover = "&7You examine the &6%group_color%%group_name% &7Enchantment Book, and discover &6%enchantformat%&7!" \ No newline at end of file diff --git a/core/src/main/resources/enchants/example-enchant.yml b/src/main/resources/enchants/example-enchant.yml similarity index 100% rename from core/src/main/resources/enchants/example-enchant.yml rename to src/main/resources/enchants/example-enchant.yml diff --git a/core/src/main/resources/groups.yml b/src/main/resources/groups.yml similarity index 100% rename from core/src/main/resources/groups.yml rename to src/main/resources/groups.yml diff --git a/core/src/main/resources/menus/groups/elite-menu.yml b/src/main/resources/menus/groups/elite-menu.yml similarity index 100% rename from core/src/main/resources/menus/groups/elite-menu.yml rename to src/main/resources/menus/groups/elite-menu.yml diff --git a/core/src/main/resources/menus/groups/legendary-menu.yml b/src/main/resources/menus/groups/legendary-menu.yml similarity index 100% rename from core/src/main/resources/menus/groups/legendary-menu.yml rename to src/main/resources/menus/groups/legendary-menu.yml diff --git a/core/src/main/resources/menus/groups/simple-menu.yml b/src/main/resources/menus/groups/simple-menu.yml similarity index 100% rename from core/src/main/resources/menus/groups/simple-menu.yml rename to src/main/resources/menus/groups/simple-menu.yml diff --git a/core/src/main/resources/menus/groups/ultimate-menu.yml b/src/main/resources/menus/groups/ultimate-menu.yml similarity index 100% rename from core/src/main/resources/menus/groups/ultimate-menu.yml rename to src/main/resources/menus/groups/ultimate-menu.yml diff --git a/core/src/main/resources/menus/groups/unique-menu.yml b/src/main/resources/menus/groups/unique-menu.yml similarity index 100% rename from core/src/main/resources/menus/groups/unique-menu.yml rename to src/main/resources/menus/groups/unique-menu.yml diff --git a/core/src/main/resources/menus/main-info-menu.yml b/src/main/resources/menus/main-info-menu.yml similarity index 100% rename from core/src/main/resources/menus/main-info-menu.yml rename to src/main/resources/menus/main-info-menu.yml diff --git a/core/src/main/resources/plugin.yml b/src/main/resources/plugin.yml similarity index 100% rename from core/src/main/resources/plugin.yml rename to src/main/resources/plugin.yml diff --git a/core/src/main/resources/version-dependent/legacy/items/dusts.yml b/src/main/resources/version-dependent/legacy/items/dusts.yml similarity index 100% rename from core/src/main/resources/version-dependent/legacy/items/dusts.yml rename to src/main/resources/version-dependent/legacy/items/dusts.yml diff --git a/core/src/main/resources/version-dependent/legacy/items/special-items.yml b/src/main/resources/version-dependent/legacy/items/special-items.yml similarity index 100% rename from core/src/main/resources/version-dependent/legacy/items/special-items.yml rename to src/main/resources/version-dependent/legacy/items/special-items.yml diff --git a/core/src/main/resources/version-dependent/legacy/menus/alchemist-menu.yml b/src/main/resources/version-dependent/legacy/menus/alchemist-menu.yml similarity index 100% rename from core/src/main/resources/version-dependent/legacy/menus/alchemist-menu.yml rename to src/main/resources/version-dependent/legacy/menus/alchemist-menu.yml diff --git a/core/src/main/resources/version-dependent/legacy/menus/enchanter-menu.yml b/src/main/resources/version-dependent/legacy/menus/enchanter-menu.yml similarity index 100% rename from core/src/main/resources/version-dependent/legacy/menus/enchanter-menu.yml rename to src/main/resources/version-dependent/legacy/menus/enchanter-menu.yml diff --git a/core/src/main/resources/version-dependent/legacy/menus/tinkerer-menu.yml b/src/main/resources/version-dependent/legacy/menus/tinkerer-menu.yml similarity index 100% rename from core/src/main/resources/version-dependent/legacy/menus/tinkerer-menu.yml rename to src/main/resources/version-dependent/legacy/menus/tinkerer-menu.yml diff --git a/core/src/main/resources/version-dependent/master/items/dusts.yml b/src/main/resources/version-dependent/master/items/dusts.yml similarity index 100% rename from core/src/main/resources/version-dependent/master/items/dusts.yml rename to src/main/resources/version-dependent/master/items/dusts.yml diff --git a/core/src/main/resources/version-dependent/master/items/special-items.yml b/src/main/resources/version-dependent/master/items/special-items.yml similarity index 100% rename from core/src/main/resources/version-dependent/master/items/special-items.yml rename to src/main/resources/version-dependent/master/items/special-items.yml diff --git a/core/src/main/resources/version-dependent/master/menus/alchemist-menu.yml b/src/main/resources/version-dependent/master/menus/alchemist-menu.yml similarity index 100% rename from core/src/main/resources/version-dependent/master/menus/alchemist-menu.yml rename to src/main/resources/version-dependent/master/menus/alchemist-menu.yml diff --git a/core/src/main/resources/version-dependent/master/menus/enchanter-menu.yml b/src/main/resources/version-dependent/master/menus/enchanter-menu.yml similarity index 100% rename from core/src/main/resources/version-dependent/master/menus/enchanter-menu.yml rename to src/main/resources/version-dependent/master/menus/enchanter-menu.yml diff --git a/core/src/main/resources/version-dependent/master/menus/tinkerer-menu.yml b/src/main/resources/version-dependent/master/menus/tinkerer-menu.yml similarity index 100% rename from core/src/main/resources/version-dependent/master/menus/tinkerer-menu.yml rename to src/main/resources/version-dependent/master/menus/tinkerer-menu.yml