From 4a4097e4475aaeeea07987e1a3ff585ee11d2e41 Mon Sep 17 00:00:00 2001 From: filoghost Date: Sun, 23 Aug 2020 15:00:44 +0200 Subject: [PATCH] Convert tabs to spaces --- api/pom.xml | 40 +- .../chestcommands/api/ChestCommandsAPI.java | 78 +- .../chestcommands/api/ClickHandler.java | 10 +- .../chestcommands/api/ClickResult.java | 4 +- .../chestcommands/api/ClickableIcon.java | 20 +- .../chestcommands/api/ConfigurableIcon.java | 71 +- .../me/filoghost/chestcommands/api/Icon.java | 4 +- .../me/filoghost/chestcommands/api/Menu.java | 38 +- .../filoghost/chestcommands/api/MenuView.java | 6 +- .../api/PlaceholderReplacer.java | 2 +- .../chestcommands/api/StaticIcon.java | 12 +- .../api/internal/BackendAPI.java | 44 +- plugin/pom.xml | 294 +++---- .../chestcommands/ChestCommands.java | 283 ++++--- .../chestcommands/DefaultBackendAPI.java | 66 +- .../filoghost/chestcommands/Permissions.java | 14 +- .../chestcommands/action/Action.java | 2 +- .../chestcommands/action/BroadcastAction.java | 18 +- .../action/ChangeServerAction.java | 18 +- .../action/ConsoleCommandAction.java | 16 +- .../chestcommands/action/DisabledAction.java | 16 +- .../chestcommands/action/DragonBarAction.java | 52 +- .../chestcommands/action/GiveItemAction.java | 20 +- .../chestcommands/action/GiveMoneyAction.java | 24 +- .../chestcommands/action/OpCommandAction.java | 28 +- .../chestcommands/action/OpenMenuAction.java | 44 +- .../chestcommands/action/PlaySoundAction.java | 73 +- .../action/PlayerCommandAction.java | 18 +- .../action/SendMessageAction.java | 18 +- .../attribute/ActionsAttribute.java | 47 +- .../attribute/AmountAttribute.java | 24 +- .../attribute/AttributeErrorHandler.java | 2 +- .../attribute/BannerColorAttribute.java | 18 +- .../attribute/BannerPatternsAttribute.java | 45 +- .../attribute/ClickPermissionAttribute.java | 18 +- .../ClickPermissionMessageAttribute.java | 18 +- .../attribute/DurabilityAttribute.java | 18 +- .../attribute/EnchantmentsAttribute.java | 47 +- .../attribute/ExpLevelsAttribute.java | 24 +- .../attribute/IconAttribute.java | 2 +- .../attribute/KeepOpenAttribute.java | 26 +- .../attribute/LeatherColorAttribute.java | 18 +- .../attribute/LoreAttribute.java | 39 +- .../attribute/MaterialAttribute.java | 20 +- .../attribute/NBTDataAttribute.java | 30 +- .../attribute/NameAttribute.java | 30 +- .../attribute/PositionAttribute.java | 26 +- .../attribute/PriceAttribute.java | 24 +- .../attribute/RequiredItemsAttribute.java | 49 +- .../attribute/SkullOwnerAttribute.java | 18 +- .../attribute/ViewPermissionAttribute.java | 18 +- .../chestcommands/command/CommandHandler.java | 200 ++--- .../chestcommands/config/ConfigManager.java | 169 ++-- .../config/CustomPlaceholders.java | 57 +- .../filoghost/chestcommands/config/Lang.java | 14 +- .../chestcommands/config/Settings.java | 18 +- .../chestcommands/hook/BarAPIHook.java | 38 +- .../chestcommands/hook/BungeeCordHook.java | 67 +- .../hook/PlaceholderAPIHook.java | 40 +- .../chestcommands/hook/PluginHook.java | 16 +- .../chestcommands/hook/VaultEconomyHook.java | 116 +-- .../icon/APIConfigurableIcon.java | 24 +- .../chestcommands/icon/APIStaticIcon.java | 54 +- .../icon/BaseConfigurableIcon.java | 481 ++++++------ .../chestcommands/icon/IconPermission.java | 76 +- .../icon/InternalConfigurableIcon.java | 285 ++++--- .../chestcommands/icon/RefreshableIcon.java | 6 +- .../icon/requirement/RequiredExpLevel.java | 50 +- .../icon/requirement/RequiredMoney.java | 62 +- .../icon/requirement/Requirement.java | 54 +- .../requirement/item/InventoryTakeHelper.java | 113 ++- .../icon/requirement/item/RemainingItem.java | 54 +- .../icon/requirement/item/RequiredItem.java | 76 +- .../icon/requirement/item/RequiredItems.java | 67 +- .../chestcommands/inventory/ArrayGrid.java | 28 +- .../inventory/DefaultMenuView.java | 80 +- .../chestcommands/inventory/Grid.java | 84 +- .../inventory/InventoryGrid.java | 32 +- .../inventory/MenuInventoryHolder.java | 36 +- .../chestcommands/legacy/Backup.java | 65 +- .../legacy/UpgradeExecutorException.java | 6 +- .../chestcommands/legacy/UpgradeList.java | 115 ++- .../legacy/UpgradesDoneRegistry.java | 79 +- .../legacy/UpgradesExecutor.java | 141 ++-- .../legacy/upgrade/RegexReplacer.java | 32 +- .../legacy/upgrade/RegexUpgradeTask.java | 119 ++- .../chestcommands/legacy/upgrade/Upgrade.java | 43 +- .../legacy/upgrade/UpgradeTask.java | 71 +- .../legacy/upgrade/UpgradeTaskException.java | 6 +- .../legacy/upgrade/YamlUpgradeTask.java | 83 +- .../legacy/v4_0/v4_0_LangUpgradeTask.java | 18 +- .../v4_0/v4_0_MenuNodeRenameUpgradeTask.java | 35 +- .../v4_0/v4_0_MenuReformatUpgradeTask.java | 251 +++--- .../v4_0/v4_0_PlaceholdersUpgradeTask.java | 137 ++-- .../legacy/v4_0/v4_0_SettingsUpgradeTask.java | 18 +- .../listener/CommandListener.java | 66 +- .../listener/InventoryListener.java | 113 ++- .../chestcommands/listener/JoinListener.java | 26 +- .../chestcommands/listener/SignListener.java | 172 ++-- .../chestcommands/logging/ErrorPrintInfo.java | 44 +- .../chestcommands/logging/Errors.java | 295 ++++--- .../logging/MessagePartJoiner.java | 107 ++- .../logging/PrintableErrorCollector.java | 113 ++- .../filoghost/chestcommands/menu/APIMenu.java | 20 +- .../chestcommands/menu/BaseMenu.java | 96 +-- .../chestcommands/menu/InternalMenu.java | 101 ++- .../chestcommands/menu/MenuManager.java | 187 +++-- .../chestcommands/parsing/ActionParser.java | 73 +- .../parsing/EnchantmentParser.java | 137 ++-- .../chestcommands/parsing/ItemMetaParser.java | 82 +- .../parsing/ItemStackParser.java | 112 +-- .../chestcommands/parsing/MaterialParser.java | 8 +- .../chestcommands/parsing/NumberParser.java | 96 +-- .../chestcommands/parsing/ParseException.java | 14 +- .../parsing/icon/AttributeType.java | 111 ++- .../parsing/icon/IconSettings.java | 91 ++- .../chestcommands/parsing/menu/ClickType.java | 46 +- .../parsing/menu/LoadedMenu.java | 49 +- .../parsing/menu/MenuOpenItem.java | 56 +- .../parsing/menu/MenuParser.java | 281 ++++--- .../parsing/menu/MenuSettings.java | 93 ++- .../parsing/menu/MenuSettingsNode.java | 20 +- .../placeholder/DefaultPlaceholder.java | 46 +- .../placeholder/PlaceholderCache.java | 29 +- .../placeholder/PlaceholderManager.java | 167 ++-- .../placeholder/PlaceholderRegistry.java | 61 +- .../placeholder/PlaceholderString.java | 60 +- .../placeholder/PlaceholderStringList.java | 77 +- .../placeholder/StaticPlaceholder.java | 24 +- .../placeholder/scanner/PlaceholderMatch.java | 119 ++- .../scanner/PlaceholderScanner.java | 136 ++-- .../chestcommands/task/TickingTask.java | 38 +- .../filoghost/chestcommands/util/Utils.java | 26 +- .../chestcommands/util/nbt/NBTByte.java | 76 +- .../chestcommands/util/nbt/NBTByteArray.java | 88 +-- .../chestcommands/util/nbt/NBTCompound.java | 740 +++++++++--------- .../chestcommands/util/nbt/NBTDouble.java | 76 +- .../chestcommands/util/nbt/NBTFloat.java | 76 +- .../chestcommands/util/nbt/NBTInt.java | 76 +- .../chestcommands/util/nbt/NBTIntArray.java | 106 +-- .../chestcommands/util/nbt/NBTList.java | 294 +++---- .../chestcommands/util/nbt/NBTLong.java | 76 +- .../chestcommands/util/nbt/NBTLongArray.java | 98 +-- .../chestcommands/util/nbt/NBTShort.java | 76 +- .../chestcommands/util/nbt/NBTString.java | 94 +-- .../chestcommands/util/nbt/NBTTag.java | 88 +-- .../chestcommands/util/nbt/NBTType.java | 306 ++++---- .../nbt/parser/MojangsonParseException.java | 28 +- .../util/nbt/parser/MojangsonParser.java | 619 ++++++++------- pom.xml | 392 +++++----- 150 files changed, 6083 insertions(+), 6128 deletions(-) diff --git a/api/pom.xml b/api/pom.xml index 3f1d8bf..42f4833 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -1,28 +1,28 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - - me.filoghost.chestcommands - chestcommands-parent - 4.0.0-SNAPSHOT - + + me.filoghost.chestcommands + chestcommands-parent + 4.0.0-SNAPSHOT + - chestcommands-api - ChestCommands API + chestcommands-api + ChestCommands API - - - org.bukkit - bukkit - + + + org.bukkit + bukkit + - - me.filoghost.fcommons - fcommons - provided - - + + me.filoghost.fcommons + fcommons + provided + + \ No newline at end of file diff --git a/api/src/main/java/me/filoghost/chestcommands/api/ChestCommandsAPI.java b/api/src/main/java/me/filoghost/chestcommands/api/ChestCommandsAPI.java index d06c065..6e2579f 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/ChestCommandsAPI.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/ChestCommandsAPI.java @@ -10,47 +10,47 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class ChestCommandsAPI { - - - private ChestCommandsAPI() {} - - - /** - * The API version is increased every time the API is modified. - * You can use it to require a minimum version, as features may - * be added (rarely removed) in future versions. - * - * @return the API version - */ - public static int getAPIVersion() { - return 1; - } - public static void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) { - BackendAPI.getImplementation().registerPlaceholder(plugin, identifier, placeholderReplacer); - } - + private ChestCommandsAPI() {} - /** - * Checks if a menu with a given file name was loaded by the plugin. - * - * @return if the menu was found - */ - public static boolean pluginMenuExists(String menuFileName) { - return BackendAPI.getImplementation().pluginMenuExists(menuFileName); - } - - /** - * Opens a menu loaded by ChestCommands to a player. - * NOTE: this method ignores permissions. - * - * @param player the player that will see the menu - * @param menuFileName the file name of the menu to open (with the .yml extension) - * @return if the menu was found and opened - */ - public static boolean openPluginMenu(Player player, String menuFileName) { - return BackendAPI.getImplementation().openPluginMenu(player, menuFileName); - } + /** + * The API version is increased every time the API is modified. + * You can use it to require a minimum version, as features may + * be added (rarely removed) in future versions. + * + * @return the API version + */ + public static int getAPIVersion() { + return 1; + } + + + public static void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) { + BackendAPI.getImplementation().registerPlaceholder(plugin, identifier, placeholderReplacer); + } + + + /** + * Checks if a menu with a given file name was loaded by the plugin. + * + * @return if the menu was found + */ + public static boolean pluginMenuExists(String menuFileName) { + return BackendAPI.getImplementation().pluginMenuExists(menuFileName); + } + + + /** + * Opens a menu loaded by ChestCommands to a player. + * NOTE: this method ignores permissions. + * + * @param player the player that will see the menu + * @param menuFileName the file name of the menu to open (with the .yml extension) + * @return if the menu was found and opened + */ + public static boolean openPluginMenu(Player player, String menuFileName) { + return BackendAPI.getImplementation().openPluginMenu(player, menuFileName); + } } diff --git a/api/src/main/java/me/filoghost/chestcommands/api/ClickHandler.java b/api/src/main/java/me/filoghost/chestcommands/api/ClickHandler.java index 4e0cb27..d84bee5 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/ClickHandler.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/ClickHandler.java @@ -10,10 +10,10 @@ import org.bukkit.entity.Player; @FunctionalInterface public interface ClickHandler { - /** - * @param player the player that clicked on the inventory - * @return true if the inventory should be closed, false otherwise - */ - ClickResult onClick(MenuView menuView, Player player); + /** + * @param player the player that clicked on the inventory + * @return true if the inventory should be closed, false otherwise + */ + ClickResult onClick(MenuView menuView, Player player); } diff --git a/api/src/main/java/me/filoghost/chestcommands/api/ClickResult.java b/api/src/main/java/me/filoghost/chestcommands/api/ClickResult.java index 62cfc6a..e029785 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/ClickResult.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/ClickResult.java @@ -7,7 +7,7 @@ package me.filoghost.chestcommands.api; public enum ClickResult { - KEEP_OPEN, - CLOSE + KEEP_OPEN, + CLOSE } diff --git a/api/src/main/java/me/filoghost/chestcommands/api/ClickableIcon.java b/api/src/main/java/me/filoghost/chestcommands/api/ClickableIcon.java index 639f71e..ce9c2e6 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/ClickableIcon.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/ClickableIcon.java @@ -9,17 +9,17 @@ import org.bukkit.entity.Player; public interface ClickableIcon extends Icon { - void setClickHandler(ClickHandler clickHandler); + void setClickHandler(ClickHandler clickHandler); - ClickHandler getClickHandler(); + ClickHandler getClickHandler(); - @Override - default ClickResult onClick(MenuView menuView, Player clicker) { - if (getClickHandler() != null) { - return getClickHandler().onClick(menuView, clicker); - } else { - return ClickResult.KEEP_OPEN; - } - } + @Override + default ClickResult onClick(MenuView menuView, Player clicker) { + if (getClickHandler() != null) { + return getClickHandler().onClick(menuView, clicker); + } else { + return ClickResult.KEEP_OPEN; + } + } } diff --git a/api/src/main/java/me/filoghost/chestcommands/api/ConfigurableIcon.java b/api/src/main/java/me/filoghost/chestcommands/api/ConfigurableIcon.java index e284d5d..3b2760b 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/ConfigurableIcon.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/ConfigurableIcon.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.api; +import java.util.List; +import java.util.Map; import me.filoghost.chestcommands.api.internal.BackendAPI; import org.bukkit.Color; import org.bukkit.DyeColor; @@ -12,67 +14,64 @@ import org.bukkit.Material; import org.bukkit.block.banner.Pattern; import org.bukkit.enchantments.Enchantment; -import java.util.List; -import java.util.Map; - public interface ConfigurableIcon extends ClickableIcon { - - static ConfigurableIcon create(Material material) { - return BackendAPI.getImplementation().createConfigurableIcon(material); - } - - void setMaterial(Material material); + + static ConfigurableIcon create(Material material) { + return BackendAPI.getImplementation().createConfigurableIcon(material); + } + + void setMaterial(Material material); - Material getMaterial(); + Material getMaterial(); - void setAmount(int amount); + void setAmount(int amount); - int getAmount(); + int getAmount(); - void setDurability(short durability); + void setDurability(short durability); - short getDurability(); + short getDurability(); - void setNBTData(String nbtData); + void setNBTData(String nbtData); - String getNBTData(); + String getNBTData(); - void setName(String name); - - String getName(); + void setName(String name); + + String getName(); - void setLore(String... lore); + void setLore(String... lore); - void setLore(List lore); + void setLore(List lore); - List getLore(); + List getLore(); - void setEnchantments(Map enchantments); + void setEnchantments(Map enchantments); - Map getEnchantments(); + Map getEnchantments(); - void addEnchantment(Enchantment enchantment); + void addEnchantment(Enchantment enchantment); - void addEnchantment(Enchantment enchantment, Integer level); + void addEnchantment(Enchantment enchantment, Integer level); - void removeEnchantment(Enchantment enchantment); + void removeEnchantment(Enchantment enchantment); - Color getLeatherColor(); + Color getLeatherColor(); - void setLeatherColor(Color leatherColor); + void setLeatherColor(Color leatherColor); - String getSkullOwner(); + String getSkullOwner(); - void setSkullOwner(String skullOwner); + void setSkullOwner(String skullOwner); - DyeColor getBannerColor(); + DyeColor getBannerColor(); - void setBannerColor(DyeColor bannerColor); + void setBannerColor(DyeColor bannerColor); - List getBannerPatterns(); + List getBannerPatterns(); - void setBannerPatterns(List bannerPatterns); + void setBannerPatterns(List bannerPatterns); - void setPlaceholdersEnabled(boolean enabled); + void setPlaceholdersEnabled(boolean enabled); } diff --git a/api/src/main/java/me/filoghost/chestcommands/api/Icon.java b/api/src/main/java/me/filoghost/chestcommands/api/Icon.java index 1ea8221..0acc811 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/Icon.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/Icon.java @@ -10,8 +10,8 @@ import org.bukkit.inventory.ItemStack; public interface Icon { - ItemStack render(Player viewer); + ItemStack render(Player viewer); - ClickResult onClick(MenuView menuView, Player clicker); + ClickResult onClick(MenuView menuView, Player clicker); } \ No newline at end of file diff --git a/api/src/main/java/me/filoghost/chestcommands/api/Menu.java b/api/src/main/java/me/filoghost/chestcommands/api/Menu.java index a338015..f278581 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/Menu.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/Menu.java @@ -10,29 +10,29 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public interface Menu { - - static Menu create(Plugin owner, String title, int rowCount) { - return BackendAPI.getImplementation().createMenu(owner, title, rowCount); - } - void setIcon(int row, int column, Icon icon); + static Menu create(Plugin owner, String title, int rowCount) { + return BackendAPI.getImplementation().createMenu(owner, title, rowCount); + } - Icon getIcon(int row, int column); + void setIcon(int row, int column, Icon icon); - String getTitle(); - - int getRowCount(); - - int getColumnCount(); + Icon getIcon(int row, int column); - /** - * Opens a view of the current menu configuration. - * Updating the menu doesn't automatically update all the views. - * - * @param player the player to which the menu will be displayed - */ - MenuView open(Player player); + String getTitle(); - void refreshMenuViews(); + int getRowCount(); + + int getColumnCount(); + + /** + * Opens a view of the current menu configuration. + * Updating the menu doesn't automatically update all the views. + * + * @param player the player to which the menu will be displayed + */ + MenuView open(Player player); + + void refreshMenuViews(); } \ No newline at end of file diff --git a/api/src/main/java/me/filoghost/chestcommands/api/MenuView.java b/api/src/main/java/me/filoghost/chestcommands/api/MenuView.java index c31a422..e62b9df 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/MenuView.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/MenuView.java @@ -9,10 +9,10 @@ import org.bukkit.entity.Player; public interface MenuView { - void refresh(); + void refresh(); - Player getViewer(); + Player getViewer(); - Menu getMenu(); + Menu getMenu(); } diff --git a/api/src/main/java/me/filoghost/chestcommands/api/PlaceholderReplacer.java b/api/src/main/java/me/filoghost/chestcommands/api/PlaceholderReplacer.java index 61b4b39..9b242a6 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/PlaceholderReplacer.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/PlaceholderReplacer.java @@ -9,6 +9,6 @@ import org.bukkit.entity.Player; public interface PlaceholderReplacer { - String getReplacement(Player player, String argument); + String getReplacement(Player player, String argument); } diff --git a/api/src/main/java/me/filoghost/chestcommands/api/StaticIcon.java b/api/src/main/java/me/filoghost/chestcommands/api/StaticIcon.java index c2f3b35..3cf0adc 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/StaticIcon.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/StaticIcon.java @@ -9,13 +9,13 @@ import me.filoghost.chestcommands.api.internal.BackendAPI; import org.bukkit.inventory.ItemStack; public interface StaticIcon extends ClickableIcon { - - static StaticIcon create(ItemStack itemStack) { - return BackendAPI.getImplementation().createStaticIcon(itemStack); - } + + static StaticIcon create(ItemStack itemStack) { + return BackendAPI.getImplementation().createStaticIcon(itemStack); + } - ItemStack getItemStack(); + ItemStack getItemStack(); - void setItemStack(ItemStack itemStack); + void setItemStack(ItemStack itemStack); } diff --git a/api/src/main/java/me/filoghost/chestcommands/api/internal/BackendAPI.java b/api/src/main/java/me/filoghost/chestcommands/api/internal/BackendAPI.java index b7a66af..24e6a1c 100644 --- a/api/src/main/java/me/filoghost/chestcommands/api/internal/BackendAPI.java +++ b/api/src/main/java/me/filoghost/chestcommands/api/internal/BackendAPI.java @@ -16,32 +16,32 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public abstract class BackendAPI { - - private static BackendAPI implementation; - - public static void setImplementation(BackendAPI implementation) { - Preconditions.notNull(implementation, "implementation"); - Preconditions.checkState(BackendAPI.implementation == null, "implementation already set"); + + private static BackendAPI implementation; + + public static void setImplementation(BackendAPI implementation) { + Preconditions.notNull(implementation, "implementation"); + Preconditions.checkState(BackendAPI.implementation == null, "implementation already set"); - BackendAPI.implementation = implementation; - } - - public static BackendAPI getImplementation() { - Preconditions.checkState(implementation != null, "no implementation set"); - - return implementation; - } - - public abstract boolean pluginMenuExists(String menuFileName); + BackendAPI.implementation = implementation; + } + + public static BackendAPI getImplementation() { + Preconditions.checkState(implementation != null, "no implementation set"); + + return implementation; + } + + public abstract boolean pluginMenuExists(String menuFileName); - public abstract boolean openPluginMenu(Player player, String menuFileName); + public abstract boolean openPluginMenu(Player player, String menuFileName); - public abstract Menu createMenu(Plugin owner, String title, int rows); - - public abstract ConfigurableIcon createConfigurableIcon(Material material); + public abstract Menu createMenu(Plugin owner, String title, int rows); + + public abstract ConfigurableIcon createConfigurableIcon(Material material); - public abstract StaticIcon createStaticIcon(ItemStack itemStack); + public abstract StaticIcon createStaticIcon(ItemStack itemStack); - public abstract void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer); + public abstract void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer); } diff --git a/plugin/pom.xml b/plugin/pom.xml index 2000575..1cb63bf 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -1,165 +1,165 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - - me.filoghost.chestcommands - chestcommands-parent - 4.0.0-SNAPSHOT - + + me.filoghost.chestcommands + chestcommands-parent + 4.0.0-SNAPSHOT + - chestcommands-plugin - ChestCommands Plugin + chestcommands-plugin + ChestCommands Plugin - - - org.bukkit - bukkit - + + + org.bukkit + bukkit + - - net.milkbowl.vault - VaultAPI - + + net.milkbowl.vault + VaultAPI + - - me.confuser - BarAPI - + + me.confuser + BarAPI + - - me.clip - placeholderapi - + + me.clip + placeholderapi + - - org.bstats - bstats-bukkit-lite - - - - me.filoghost.updatechecker - updatechecker - - - - ${project.groupId} - chestcommands-api - + + org.bstats + bstats-bukkit-lite + - - me.filoghost.fcommons - fcommons - - + + me.filoghost.updatechecker + updatechecker + - - - - src/main/resources - true - - - .. - - LICENSE.txt - THIRD-PARTY.txt - licenses/* - - - + + ${project.groupId} + chestcommands-api + - - - org.codehaus.mojo - build-helper-maven-plugin - - - - set-plugin-version - validate - - bsh-property - - - - pluginVersion - - - projectVersion = project.version; - buildNumber = System.getenv("BUILD_NUMBER"); + + me.filoghost.fcommons + fcommons + + - String pluginVersion; - if (buildNumber != null @and projectVersion.contains("SNAPSHOT")) { - pluginVersion = projectVersion + "-b" + buildNumber; - } else { - pluginVersion = projectVersion; - } + + + + src/main/resources + true + + + .. + + LICENSE.txt + THIRD-PARTY.txt + licenses/* + + + - print("Project version: " + projectVersion); - print("Build number: " + buildNumber); - print("Computed plugin version: " + pluginVersion); - - - - - + + + org.codehaus.mojo + build-helper-maven-plugin + + + + set-plugin-version + validate + + bsh-property + + + + pluginVersion + + + projectVersion = project.version; + buildNumber = System.getenv("BUILD_NUMBER"); - - org.apache.maven.plugins - maven-jar-plugin - - - - true - - - ${pluginVersion} - - - - + String pluginVersion; + if (buildNumber != null @and projectVersion.contains("SNAPSHOT")) { + pluginVersion = projectVersion + "-b" + buildNumber; + } else { + pluginVersion = projectVersion; + } - - org.apache.maven.plugins - maven-shade-plugin - - false - false - - - *:* - - META-INF/maven/ - - - - - - org.bstats.bukkit - me.filoghost.chestcommands.metrics - - - me.filoghost.updatechecker - me.filoghost.chestcommands.updater - - - me.filoghost.fcommons - me.filoghost.chestcommands.fcommons - - - - - - package - - shade - - - - - - + print("Project version: " + projectVersion); + print("Build number: " + buildNumber); + print("Computed plugin version: " + pluginVersion); + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + + + ${pluginVersion} + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + false + false + + + *:* + + META-INF/maven/ + + + + + + org.bstats.bukkit + me.filoghost.chestcommands.metrics + + + me.filoghost.updatechecker + me.filoghost.chestcommands.updater + + + me.filoghost.fcommons + me.filoghost.chestcommands.fcommons + + + + + + package + + shade + + + + + + \ No newline at end of file diff --git a/plugin/src/main/java/me/filoghost/chestcommands/ChestCommands.java b/plugin/src/main/java/me/filoghost/chestcommands/ChestCommands.java index 0aa94b4..5f00b2b 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/ChestCommands.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/ChestCommands.java @@ -5,6 +5,10 @@ */ package me.filoghost.chestcommands; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; import me.filoghost.chestcommands.api.internal.BackendAPI; import me.filoghost.chestcommands.command.CommandHandler; import me.filoghost.chestcommands.config.ConfigManager; @@ -39,185 +43,180 @@ import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - public class ChestCommands extends BaseJavaPlugin { - public static final String CHAT_PREFIX = ChatColor.DARK_GREEN + "[" + ChatColor.GREEN + "ChestCommands" + ChatColor.DARK_GREEN + "] " + ChatColor.GREEN; + public static final String CHAT_PREFIX = ChatColor.DARK_GREEN + "[" + ChatColor.GREEN + "ChestCommands" + ChatColor.DARK_GREEN + "] " + ChatColor.GREEN; - private static Plugin pluginInstance; - private static Path dataFolderPath; + private static Plugin pluginInstance; + private static Path dataFolderPath; - private static ConfigManager configManager; - private static MenuManager menuManager; - private static CustomPlaceholders placeholders; + private static ConfigManager configManager; + private static MenuManager menuManager; + private static CustomPlaceholders placeholders; - private static ErrorCollector lastLoadErrors; - private static String newVersion; + private static ErrorCollector lastLoadErrors; + private static String newVersion; - @Override - protected void onCheckedEnable() throws PluginEnableException { - if (!CommonsUtil.isClassLoaded("org.bukkit.inventory.ItemFlag")) { // ItemFlag was added in 1.8 - if (Bukkit.getVersion().contains("(MC: 1.8)")) { - throw new PluginEnableException("ChestCommands requires a more recent version of Bukkit 1.8 to run."); - } else { - throw new PluginEnableException("ChestCommands requires at least Bukkit 1.8 to run."); - } - } + @Override + protected void onCheckedEnable() throws PluginEnableException { + if (!CommonsUtil.isClassLoaded("org.bukkit.inventory.ItemFlag")) { // ItemFlag was added in 1.8 + if (Bukkit.getVersion().contains("(MC: 1.8)")) { + throw new PluginEnableException("ChestCommands requires a more recent version of Bukkit 1.8 to run."); + } else { + throw new PluginEnableException("ChestCommands requires at least Bukkit 1.8 to run."); + } + } - if (pluginInstance != null || System.getProperty("ChestCommandsLoaded") != null) { - Log.warning("Please do not use /reload or plugin reloaders. Use the command \"/cc reload\" instead."); - return; - } + if (pluginInstance != null || System.getProperty("ChestCommandsLoaded") != null) { + Log.warning("Please do not use /reload or plugin reloaders. Use the command \"/cc reload\" instead."); + return; + } - System.setProperty("ChestCommandsLoaded", "true"); + System.setProperty("ChestCommandsLoaded", "true"); - pluginInstance = this; - dataFolderPath = getDataFolder().toPath(); - Log.setLogger(getLogger()); - configManager = new ConfigManager(getDataFolderPath()); - menuManager = new MenuManager(); - placeholders = new CustomPlaceholders(); + pluginInstance = this; + dataFolderPath = getDataFolder().toPath(); + Log.setLogger(getLogger()); + configManager = new ConfigManager(getDataFolderPath()); + menuManager = new MenuManager(); + placeholders = new CustomPlaceholders(); - BackendAPI.setImplementation(new DefaultBackendAPI()); + BackendAPI.setImplementation(new DefaultBackendAPI()); - VaultEconomyHook.INSTANCE.setup(); - BarAPIHook.INSTANCE.setup(); - PlaceholderAPIHook.INSTANCE.setup(); - BungeeCordHook.INSTANCE.setup(); + VaultEconomyHook.INSTANCE.setup(); + BarAPIHook.INSTANCE.setup(); + PlaceholderAPIHook.INSTANCE.setup(); + BungeeCordHook.INSTANCE.setup(); - if (VaultEconomyHook.INSTANCE.isEnabled()) { - Log.info("Hooked Vault"); - } else { - Log.warning("Couldn't find Vault and a compatible economy plugin! Money-related features will not work."); - } + if (VaultEconomyHook.INSTANCE.isEnabled()) { + Log.info("Hooked Vault"); + } else { + Log.warning("Couldn't find Vault and a compatible economy plugin! Money-related features will not work."); + } - if (BarAPIHook.INSTANCE.isEnabled()) { - Log.info("Hooked BarAPI"); - } + if (BarAPIHook.INSTANCE.isEnabled()) { + Log.info("Hooked BarAPI"); + } - if (PlaceholderAPIHook.INSTANCE.isEnabled()) { - Log.info("Hooked PlaceholderAPI"); - } + if (PlaceholderAPIHook.INSTANCE.isEnabled()) { + Log.info("Hooked PlaceholderAPI"); + } - if (Settings.update_notifications) { - UpdateChecker.run(this, 56919, (String newVersion) -> { - ChestCommands.newVersion = newVersion; + if (Settings.update_notifications) { + UpdateChecker.run(this, 56919, (String newVersion) -> { + ChestCommands.newVersion = newVersion; - Log.info("Found a new version: " + newVersion + " (yours: v" + getDescription().getVersion() + ")"); - Log.info("Download the update on Bukkit Dev:"); - Log.info("https://dev.bukkit.org/projects/chest-commands"); - }); - } + Log.info("Found a new version: " + newVersion + " (yours: v" + getDescription().getVersion() + ")"); + Log.info("Download the update on Bukkit Dev:"); + Log.info("https://dev.bukkit.org/projects/chest-commands"); + }); + } - // Start bStats metrics - int pluginID = 3658; - new MetricsLite(this, pluginID); + // Start bStats metrics + int pluginID = 3658; + new MetricsLite(this, pluginID); - Bukkit.getPluginManager().registerEvents(new CommandListener(menuManager), this); - Bukkit.getPluginManager().registerEvents(new InventoryListener(menuManager), this); - Bukkit.getPluginManager().registerEvents(new JoinListener(), this); - Bukkit.getPluginManager().registerEvents(new SignListener(menuManager), this); + Bukkit.getPluginManager().registerEvents(new CommandListener(menuManager), this); + Bukkit.getPluginManager().registerEvents(new InventoryListener(menuManager), this); + Bukkit.getPluginManager().registerEvents(new JoinListener(), this); + Bukkit.getPluginManager().registerEvents(new SignListener(menuManager), this); - CommandFramework.register(this, new CommandHandler(menuManager, "chestcommands")); + CommandFramework.register(this, new CommandHandler(menuManager, "chestcommands")); - ErrorCollector errorCollector = load(); + ErrorCollector errorCollector = load(); - if (errorCollector.hasErrors()) { - errorCollector.logToConsole(); - Bukkit.getScheduler().runTaskLater(this, () -> { - Bukkit.getConsoleSender().sendMessage( - ChestCommands.CHAT_PREFIX + ChatColor.RED + "Encountered " + errorCollector.getErrorsCount() + " error(s) on load. " - + "Check previous console logs or run \"/chestcommands errors\" to see them again."); - }, 10L); - } + if (errorCollector.hasErrors()) { + errorCollector.logToConsole(); + Bukkit.getScheduler().runTaskLater(this, () -> { + Bukkit.getConsoleSender().sendMessage( + ChestCommands.CHAT_PREFIX + ChatColor.RED + "Encountered " + errorCollector.getErrorsCount() + " error(s) on load. " + + "Check previous console logs or run \"/chestcommands errors\" to see them again."); + }, 10L); + } - Bukkit.getScheduler().runTaskTimer(this, new TickingTask(), 1L, 1L); - } + Bukkit.getScheduler().runTaskTimer(this, new TickingTask(), 1L, 1L); + } - @Override - public void onDisable() { - closeAllMenus(); - } + @Override + public void onDisable() { + closeAllMenus(); + } - public static ErrorCollector load() { - ErrorCollector errorCollector = new PrintableErrorCollector(); - menuManager.clear(); - boolean isFreshInstall = !Files.isDirectory(configManager.getRootDataFolder()); - try { - Files.createDirectories(configManager.getRootDataFolder()); - } catch (IOException e) { - errorCollector.add(e, Errors.Config.createDataFolderIOException); - return errorCollector; - } + public static ErrorCollector load() { + ErrorCollector errorCollector = new PrintableErrorCollector(); + menuManager.clear(); + boolean isFreshInstall = !Files.isDirectory(configManager.getRootDataFolder()); + try { + Files.createDirectories(configManager.getRootDataFolder()); + } catch (IOException e) { + errorCollector.add(e, Errors.Config.createDataFolderIOException); + return errorCollector; + } - UpgradesExecutor upgradeExecutor = new UpgradesExecutor(configManager); + UpgradesExecutor upgradeExecutor = new UpgradesExecutor(configManager); - try { - boolean allUpgradesSuccessful = upgradeExecutor.run(isFreshInstall, errorCollector); - if (!allUpgradesSuccessful) { - errorCollector.add(Errors.Upgrade.failedSomeUpgrades); - } - } catch (UpgradeExecutorException e) { - errorCollector.add(e, Errors.Upgrade.genericExecutorError); - errorCollector.add(Errors.Upgrade.failedSomeUpgrades); - } + try { + boolean allUpgradesSuccessful = upgradeExecutor.run(isFreshInstall, errorCollector); + if (!allUpgradesSuccessful) { + errorCollector.add(Errors.Upgrade.failedSomeUpgrades); + } + } catch (UpgradeExecutorException e) { + errorCollector.add(e, Errors.Upgrade.genericExecutorError); + errorCollector.add(Errors.Upgrade.failedSomeUpgrades); + } - configManager.tryLoadSettings(errorCollector); - configManager.tryLoadLang(errorCollector); - placeholders = configManager.tryLoadCustomPlaceholders(errorCollector); - PlaceholderManager.setStaticPlaceholders(placeholders.getPlaceholders()); + configManager.tryLoadSettings(errorCollector); + configManager.tryLoadLang(errorCollector); + placeholders = configManager.tryLoadCustomPlaceholders(errorCollector); + PlaceholderManager.setStaticPlaceholders(placeholders.getPlaceholders()); - // Create the menu folder with the example menu - if (!Files.isDirectory(configManager.getMenusFolder())) { - ConfigLoader exampleMenuLoader = configManager.getConfigLoader(configManager.getMenusFolder().resolve("example.yml")); - configManager.tryCreateDefault(errorCollector, exampleMenuLoader); - } + // Create the menu folder with the example menu + if (!Files.isDirectory(configManager.getMenusFolder())) { + ConfigLoader exampleMenuLoader = configManager.getConfigLoader(configManager.getMenusFolder().resolve("example.yml")); + configManager.tryCreateDefault(errorCollector, exampleMenuLoader); + } - List loadedMenus = configManager.tryLoadMenus(errorCollector); - for (LoadedMenu loadedMenu : loadedMenus) { - menuManager.registerMenu(loadedMenu, errorCollector); - } + List loadedMenus = configManager.tryLoadMenus(errorCollector); + for (LoadedMenu loadedMenu : loadedMenus) { + menuManager.registerMenu(loadedMenu, errorCollector); + } - ChestCommands.lastLoadErrors = errorCollector; - return errorCollector; - } + ChestCommands.lastLoadErrors = errorCollector; + return errorCollector; + } - public static void closeAllMenus() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (MenuManager.getOpenMenuView(player) != null) { - player.closeInventory(); - } - } - } + public static void closeAllMenus() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (MenuManager.getOpenMenuView(player) != null) { + player.closeInventory(); + } + } + } - public static Plugin getPluginInstance() { - return pluginInstance; - } + public static Plugin getPluginInstance() { + return pluginInstance; + } - public static Path getDataFolderPath() { - return dataFolderPath; - } + public static Path getDataFolderPath() { + return dataFolderPath; + } - public static MenuManager getMenuManager() { - return menuManager; - } + public static MenuManager getMenuManager() { + return menuManager; + } - public static boolean hasNewVersion() { - return newVersion != null; - } + public static boolean hasNewVersion() { + return newVersion != null; + } - public static String getNewVersion() { - return newVersion; - } - - public static ErrorCollector getLastLoadErrors() { - return lastLoadErrors; - } + public static String getNewVersion() { + return newVersion; + } + + public static ErrorCollector getLastLoadErrors() { + return lastLoadErrors; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/DefaultBackendAPI.java b/plugin/src/main/java/me/filoghost/chestcommands/DefaultBackendAPI.java index 08eb595..0b54162 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/DefaultBackendAPI.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/DefaultBackendAPI.java @@ -23,46 +23,46 @@ import org.bukkit.plugin.Plugin; public class DefaultBackendAPI extends BackendAPI { - @Override - public boolean pluginMenuExists(String menuFileName) { - Preconditions.notNull(menuFileName, "menuFileName"); + @Override + public boolean pluginMenuExists(String menuFileName) { + Preconditions.notNull(menuFileName, "menuFileName"); - return ChestCommands.getMenuManager().getMenuByFileName(menuFileName) != null; - } + return ChestCommands.getMenuManager().getMenuByFileName(menuFileName) != null; + } - @Override - public boolean openPluginMenu(Player player, String menuFileName) { - Preconditions.notNull(player, "player"); - Preconditions.notNull(menuFileName, "menuFileName"); + @Override + public boolean openPluginMenu(Player player, String menuFileName) { + Preconditions.notNull(player, "player"); + Preconditions.notNull(menuFileName, "menuFileName"); - InternalMenu menu = ChestCommands.getMenuManager().getMenuByFileName(menuFileName); + InternalMenu menu = ChestCommands.getMenuManager().getMenuByFileName(menuFileName); - if (menu != null) { - menu.open(player); - return true; - } else { - return false; - } - } + if (menu != null) { + menu.open(player); + return true; + } else { + return false; + } + } - @Override - public ConfigurableIcon createConfigurableIcon(Material material) { - return new APIConfigurableIcon(material); - } + @Override + public ConfigurableIcon createConfigurableIcon(Material material) { + return new APIConfigurableIcon(material); + } - @Override - public Menu createMenu(Plugin owner, String title, int rows) { - return new APIMenu(owner, title, rows); - } + @Override + public Menu createMenu(Plugin owner, String title, int rows) { + return new APIMenu(owner, title, rows); + } - @Override - public StaticIcon createStaticIcon(ItemStack itemStack) { - return new APIStaticIcon(itemStack); - } + @Override + public StaticIcon createStaticIcon(ItemStack itemStack) { + return new APIStaticIcon(itemStack); + } - @Override - public void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) { - PlaceholderManager.registerPluginPlaceholder(plugin, identifier, placeholderReplacer); - } + @Override + public void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) { + PlaceholderManager.registerPluginPlaceholder(plugin, identifier, placeholderReplacer); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/Permissions.java b/plugin/src/main/java/me/filoghost/chestcommands/Permissions.java index 7ca067b..e1015e6 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/Permissions.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/Permissions.java @@ -7,14 +7,14 @@ package me.filoghost.chestcommands; public class Permissions { - public static final String + public static final String - BASE_PREFIX = "chestcommands.", - COMMAND_PREFIX = BASE_PREFIX + "command.", - OPEN_MENU_PREFIX = BASE_PREFIX + "open.", + BASE_PREFIX = "chestcommands.", + COMMAND_PREFIX = BASE_PREFIX + "command.", + OPEN_MENU_PREFIX = BASE_PREFIX + "open.", - UPDATE_NOTIFICATIONS = BASE_PREFIX + "update", - SEE_ERRORS = BASE_PREFIX + "errors", - SIGN_CREATE = BASE_PREFIX + "sign"; + UPDATE_NOTIFICATIONS = BASE_PREFIX + "update", + SEE_ERRORS = BASE_PREFIX + "errors", + SIGN_CREATE = BASE_PREFIX + "sign"; } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/Action.java b/plugin/src/main/java/me/filoghost/chestcommands/action/Action.java index f0554ed..f5c6222 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/Action.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/Action.java @@ -9,6 +9,6 @@ import org.bukkit.entity.Player; public interface Action { - void execute(Player player); + void execute(Player player); } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/BroadcastAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/BroadcastAction.java index c8b458b..eee556a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/BroadcastAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/BroadcastAction.java @@ -11,16 +11,16 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class BroadcastAction implements Action { - - private final PlaceholderString message; + + private final PlaceholderString message; - public BroadcastAction(String serializedAction) { - message = PlaceholderString.of(Colors.addColors(serializedAction)); - } + public BroadcastAction(String serializedAction) { + message = PlaceholderString.of(Colors.addColors(serializedAction)); + } - @Override - public void execute(Player player) { - Bukkit.broadcastMessage(message.getValue(player)); - } + @Override + public void execute(Player player) { + Bukkit.broadcastMessage(message.getValue(player)); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/ChangeServerAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/ChangeServerAction.java index 1cecda7..01d31fb 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/ChangeServerAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/ChangeServerAction.java @@ -11,15 +11,15 @@ import org.bukkit.entity.Player; public class ChangeServerAction implements Action { - private final PlaceholderString targetServer; - - public ChangeServerAction(String serializedAction) { - targetServer = PlaceholderString.of(serializedAction); - } + private final PlaceholderString targetServer; + + public ChangeServerAction(String serializedAction) { + targetServer = PlaceholderString.of(serializedAction); + } - @Override - public void execute(Player player) { - BungeeCordHook.connect(player, targetServer.getValue(player)); - } + @Override + public void execute(Player player) { + BungeeCordHook.connect(player, targetServer.getValue(player)); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/ConsoleCommandAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/ConsoleCommandAction.java index 3ce2660..09d16d7 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/ConsoleCommandAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/ConsoleCommandAction.java @@ -11,15 +11,15 @@ import org.bukkit.entity.Player; public class ConsoleCommandAction implements Action { - private final PlaceholderString command; + private final PlaceholderString command; - public ConsoleCommandAction(String serializedAction) { - command = PlaceholderString.of(serializedAction); - } + public ConsoleCommandAction(String serializedAction) { + command = PlaceholderString.of(serializedAction); + } - @Override - public void execute(Player player) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.getValue(player)); - } + @Override + public void execute(Player player) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.getValue(player)); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/DisabledAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/DisabledAction.java index 52a0c47..4838a04 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/DisabledAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/DisabledAction.java @@ -9,15 +9,15 @@ import org.bukkit.entity.Player; public class DisabledAction implements Action { - private final String errorMessage; + private final String errorMessage; - public DisabledAction(String errorMessage) { - this.errorMessage = errorMessage; - } + public DisabledAction(String errorMessage) { + this.errorMessage = errorMessage; + } - @Override - public void execute(Player player) { - player.sendMessage(errorMessage); - } + @Override + public void execute(Player player) { + player.sendMessage(errorMessage); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/DragonBarAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/DragonBarAction.java index 45503ec..764cb28 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/DragonBarAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/DragonBarAction.java @@ -16,35 +16,35 @@ import org.bukkit.entity.Player; public class DragonBarAction implements Action { - private final PlaceholderString message; - private final int seconds; + private final PlaceholderString message; + private final int seconds; - public DragonBarAction(String serialiazedAction) throws ParseException { - String message; + public DragonBarAction(String serialiazedAction) throws ParseException { + String message; - String[] split = Strings.trimmedSplit(serialiazedAction, "\\|", 2); // Max of 2 pieces - if (split.length > 1) { - try { - seconds = NumberParser.getStrictlyPositiveInteger(split[0]); - message = split[1]; - } catch (ParseException e) { - throw new ParseException(Errors.Parsing.invalidBossBarTime(split[0]), e); - } - } else { - seconds = 1; - message = serialiazedAction; - } + String[] split = Strings.trimmedSplit(serialiazedAction, "\\|", 2); // Max of 2 pieces + if (split.length > 1) { + try { + seconds = NumberParser.getStrictlyPositiveInteger(split[0]); + message = split[1]; + } catch (ParseException e) { + throw new ParseException(Errors.Parsing.invalidBossBarTime(split[0]), e); + } + } else { + seconds = 1; + message = serialiazedAction; + } - this.message = PlaceholderString.of(Colors.addColors(message)); - } + this.message = PlaceholderString.of(Colors.addColors(message)); + } - @Override - public void execute(Player player) { - if (BarAPIHook.INSTANCE.isEnabled()) { - BarAPIHook.setMessage(player, message.getValue(player), seconds); - } else { - player.sendMessage(Errors.User.configurationError("BarAPI plugin not found")); - } - } + @Override + public void execute(Player player) { + if (BarAPIHook.INSTANCE.isEnabled()) { + BarAPIHook.setMessage(player, message.getValue(player), seconds); + } else { + player.sendMessage(Errors.User.configurationError("BarAPI plugin not found")); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/GiveItemAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/GiveItemAction.java index 0b98bd4..25548d0 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/GiveItemAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/GiveItemAction.java @@ -12,17 +12,17 @@ import org.bukkit.inventory.ItemStack; public class GiveItemAction implements Action { - private final ItemStack itemToGive; + private final ItemStack itemToGive; - public GiveItemAction(String serializedAction) throws ParseException { - ItemStackParser reader = new ItemStackParser(serializedAction, true); - reader.checkNotAir(); - itemToGive = reader.createStack(); - } + public GiveItemAction(String serializedAction) throws ParseException { + ItemStackParser reader = new ItemStackParser(serializedAction, true); + reader.checkNotAir(); + itemToGive = reader.createStack(); + } - @Override - public void execute(Player player) { - player.getInventory().addItem(itemToGive.clone()); - } + @Override + public void execute(Player player) { + player.getInventory().addItem(itemToGive.clone()); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/GiveMoneyAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/GiveMoneyAction.java index c53e7c7..ac1cfdf 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/GiveMoneyAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/GiveMoneyAction.java @@ -13,19 +13,19 @@ import org.bukkit.entity.Player; public class GiveMoneyAction implements Action { - private final double moneyToGive; + private final double moneyToGive; - public GiveMoneyAction(String serializedAction) throws ParseException { - moneyToGive = NumberParser.getStrictlyPositiveDouble(serializedAction); - } + public GiveMoneyAction(String serializedAction) throws ParseException { + moneyToGive = NumberParser.getStrictlyPositiveDouble(serializedAction); + } - @Override - public void execute(Player player) { - if (VaultEconomyHook.INSTANCE.isEnabled()) { - VaultEconomyHook.giveMoney(player, moneyToGive); - } else { - player.sendMessage(Errors.User.configurationError("Vault with a compatible economy plugin not found")); - } - } + @Override + public void execute(Player player) { + if (VaultEconomyHook.INSTANCE.isEnabled()) { + VaultEconomyHook.giveMoney(player, moneyToGive); + } else { + player.sendMessage(Errors.User.configurationError("Vault with a compatible economy plugin not found")); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/OpCommandAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/OpCommandAction.java index 1da8b27..9d2b2a7 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/OpCommandAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/OpCommandAction.java @@ -10,21 +10,21 @@ import org.bukkit.entity.Player; public class OpCommandAction implements Action { - private final PlaceholderString command; + private final PlaceholderString command; - public OpCommandAction(String serializedAction) { - command = PlaceholderString.of(serializedAction); - } + public OpCommandAction(String serializedAction) { + command = PlaceholderString.of(serializedAction); + } - @Override - public void execute(Player player) { - if (player.isOp()) { - player.chat("/" + command.getValue(player)); - } else { - player.setOp(true); - player.chat("/" + command.getValue(player)); - player.setOp(false); - } - } + @Override + public void execute(Player player) { + if (player.isOp()) { + player.chat("/" + command.getValue(player)); + } else { + player.setOp(true); + player.chat("/" + command.getValue(player)); + player.setOp(false); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/OpenMenuAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/OpenMenuAction.java index 0f17da5..5caa988 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/OpenMenuAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/OpenMenuAction.java @@ -14,29 +14,29 @@ import org.bukkit.entity.Player; public class OpenMenuAction implements Action { - private final PlaceholderString targetMenu; - - public OpenMenuAction(String serializedAction) { - targetMenu = PlaceholderString.of(serializedAction); - } + private final PlaceholderString targetMenu; + + public OpenMenuAction(String serializedAction) { + targetMenu = PlaceholderString.of(serializedAction); + } - @Override - public void execute(final Player player) { - String menuName = targetMenu.getValue(player); - final InternalMenu menu = ChestCommands.getMenuManager().getMenuByFileName(menuName); - - if (menu != null) { - /* - * Delay the task, since this action is executed in ClickInventoryEvent - * and opening another inventory in the same moment is not a good idea. - */ - Bukkit.getScheduler().runTask(ChestCommands.getPluginInstance(), () -> { - menu.openCheckingPermission(player); - }); + @Override + public void execute(final Player player) { + String menuName = targetMenu.getValue(player); + final InternalMenu menu = ChestCommands.getMenuManager().getMenuByFileName(menuName); + + if (menu != null) { + /* + * Delay the task, since this action is executed in ClickInventoryEvent + * and opening another inventory in the same moment is not a good idea. + */ + Bukkit.getScheduler().runTask(ChestCommands.getPluginInstance(), () -> { + menu.openCheckingPermission(player); + }); - } else { - player.sendMessage(Errors.User.configurationError("couldn't find the menu \"" + menuName + "\"")); - } - } + } else { + player.sendMessage(Errors.User.configurationError("couldn't find the menu \"" + menuName + "\"")); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/PlaySoundAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/PlaySoundAction.java index cbeb53c..ad1618a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/PlaySoundAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/PlaySoundAction.java @@ -5,6 +5,7 @@ */ package me.filoghost.chestcommands.action; +import java.util.Optional; import me.filoghost.chestcommands.logging.Errors; import me.filoghost.chestcommands.parsing.NumberParser; import me.filoghost.chestcommands.parsing.ParseException; @@ -13,49 +14,47 @@ import me.filoghost.fcommons.collection.Registry; import org.bukkit.Sound; import org.bukkit.entity.Player; -import java.util.Optional; - public class PlaySoundAction implements Action { - - private static final Registry SOUNDS_REGISTRY = Registry.fromEnumValues(Sound.class); + + private static final Registry SOUNDS_REGISTRY = Registry.fromEnumValues(Sound.class); - private final Sound sound; - private final float pitch; - private final float volume; + private final Sound sound; + private final float pitch; + private final float volume; - public PlaySoundAction(String serializedAction) throws ParseException { - String[] split = Strings.trimmedSplit(serializedAction, ",", 3); + public PlaySoundAction(String serializedAction) throws ParseException { + String[] split = Strings.trimmedSplit(serializedAction, ",", 3); - Optional sound = SOUNDS_REGISTRY.find(split[0]); - if (!sound.isPresent()) { - throw new ParseException(Errors.Parsing.unknownSound(split[0])); - } - this.sound = sound.get(); + Optional sound = SOUNDS_REGISTRY.find(split[0]); + if (!sound.isPresent()) { + throw new ParseException(Errors.Parsing.unknownSound(split[0])); + } + this.sound = sound.get(); - if (split.length > 1) { - try { - pitch = NumberParser.getFloat(split[1]); - } catch (ParseException e) { - throw new ParseException(Errors.Parsing.invalidSoundPitch(split[1]), e); - } - } else { - pitch = 1.0f; - } + if (split.length > 1) { + try { + pitch = NumberParser.getFloat(split[1]); + } catch (ParseException e) { + throw new ParseException(Errors.Parsing.invalidSoundPitch(split[1]), e); + } + } else { + pitch = 1.0f; + } - if (split.length > 2) { - try { - volume = NumberParser.getFloat(split[2]); - } catch (ParseException e) { - throw new ParseException(Errors.Parsing.invalidSoundVolume(split[2]), e); - } - } else { - volume = 1.0f; - } - } + if (split.length > 2) { + try { + volume = NumberParser.getFloat(split[2]); + } catch (ParseException e) { + throw new ParseException(Errors.Parsing.invalidSoundVolume(split[2]), e); + } + } else { + volume = 1.0f; + } + } - @Override - public void execute(Player player) { - player.playSound(player.getLocation(), sound, volume, pitch); - } + @Override + public void execute(Player player) { + player.playSound(player.getLocation(), sound, volume, pitch); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/PlayerCommandAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/PlayerCommandAction.java index 883da09..fc43ed7 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/PlayerCommandAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/PlayerCommandAction.java @@ -9,16 +9,16 @@ import me.filoghost.chestcommands.placeholder.PlaceholderString; import org.bukkit.entity.Player; public class PlayerCommandAction implements Action { - - private final PlaceholderString command; - public PlayerCommandAction(String serializedAction) { - command = PlaceholderString.of(serializedAction); - } + private final PlaceholderString command; - @Override - public void execute(Player player) { - player.chat('/' + command.getValue(player)); - } + public PlayerCommandAction(String serializedAction) { + command = PlaceholderString.of(serializedAction); + } + + @Override + public void execute(Player player) { + player.chat('/' + command.getValue(player)); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/action/SendMessageAction.java b/plugin/src/main/java/me/filoghost/chestcommands/action/SendMessageAction.java index 4762727..98c72a7 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/action/SendMessageAction.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/action/SendMessageAction.java @@ -10,16 +10,16 @@ import me.filoghost.fcommons.Colors; import org.bukkit.entity.Player; public class SendMessageAction implements Action { - - private final PlaceholderString message; + + private final PlaceholderString message; - public SendMessageAction(String serializedAction) { - message = PlaceholderString.of(Colors.addColors(serializedAction)); - } + public SendMessageAction(String serializedAction) { + message = PlaceholderString.of(Colors.addColors(serializedAction)); + } - @Override - public void execute(Player player) { - player.sendMessage(message.getValue(player)); - } + @Override + public void execute(Player player) { + player.sendMessage(message.getValue(player)); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ActionsAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ActionsAttribute.java index 3297af5..3e6cd97 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ActionsAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ActionsAttribute.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.attribute; +import java.util.ArrayList; +import java.util.List; import me.filoghost.chestcommands.action.Action; import me.filoghost.chestcommands.action.DisabledAction; import me.filoghost.chestcommands.icon.InternalConfigurableIcon; @@ -12,34 +14,31 @@ import me.filoghost.chestcommands.logging.Errors; import me.filoghost.chestcommands.parsing.ActionParser; import me.filoghost.chestcommands.parsing.ParseException; -import java.util.ArrayList; -import java.util.List; - public class ActionsAttribute implements IconAttribute { - private final List actions; + private final List actions; - public ActionsAttribute(List serializedActions, AttributeErrorHandler errorHandler) { - actions = new ArrayList<>(); + public ActionsAttribute(List serializedActions, AttributeErrorHandler errorHandler) { + actions = new ArrayList<>(); - for (String serializedAction : serializedActions) { - if (serializedAction == null || serializedAction.isEmpty()) { - continue; // Skip - } + for (String serializedAction : serializedActions) { + if (serializedAction == null || serializedAction.isEmpty()) { + continue; // Skip + } - try { - actions.add(ActionParser.parse(serializedAction)); - } catch (ParseException e) { - actions.add(new DisabledAction(Errors.User.configurationError( - "an action linked to clicking this icon was not executed because it was not valid"))); - errorHandler.onListElementError(serializedAction, e); - } - } - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setClickActions(actions); - } + try { + actions.add(ActionParser.parse(serializedAction)); + } catch (ParseException e) { + actions.add(new DisabledAction(Errors.User.configurationError( + "an action linked to clicking this icon was not executed because it was not valid"))); + errorHandler.onListElementError(serializedAction, e); + } + } + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setClickActions(actions); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/AmountAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/AmountAttribute.java index 7879b9e..c1a2e38 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/AmountAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/AmountAttribute.java @@ -11,18 +11,18 @@ import me.filoghost.chestcommands.parsing.ParseException; public class AmountAttribute implements IconAttribute { - private final int amount; + private final int amount; - public AmountAttribute(int amount, AttributeErrorHandler errorHandler) throws ParseException { - if (amount < 0) { - throw new ParseException(Errors.Parsing.zeroOrPositive); - } - this.amount = amount; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setAmount(amount); - } + public AmountAttribute(int amount, AttributeErrorHandler errorHandler) throws ParseException { + if (amount < 0) { + throw new ParseException(Errors.Parsing.zeroOrPositive); + } + this.amount = amount; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setAmount(amount); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/AttributeErrorHandler.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/AttributeErrorHandler.java index f61ed3d..0867bd8 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/AttributeErrorHandler.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/AttributeErrorHandler.java @@ -9,6 +9,6 @@ import me.filoghost.chestcommands.parsing.ParseException; public interface AttributeErrorHandler { - void onListElementError(String listElement, ParseException e); + void onListElementError(String listElement, ParseException e); } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/BannerColorAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/BannerColorAttribute.java index 0f73c75..37d473e 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/BannerColorAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/BannerColorAttribute.java @@ -12,15 +12,15 @@ import org.bukkit.DyeColor; public class BannerColorAttribute implements IconAttribute { - private final DyeColor dyeColor; + private final DyeColor dyeColor; - public BannerColorAttribute(String serializedDyeColor, AttributeErrorHandler errorHandler) throws ParseException { - this.dyeColor = ItemMetaParser.parseDyeColor(serializedDyeColor); - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setBannerColor(dyeColor); - } + public BannerColorAttribute(String serializedDyeColor, AttributeErrorHandler errorHandler) throws ParseException { + this.dyeColor = ItemMetaParser.parseDyeColor(serializedDyeColor); + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setBannerColor(dyeColor); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/BannerPatternsAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/BannerPatternsAttribute.java index 3cddeea..af784fb 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/BannerPatternsAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/BannerPatternsAttribute.java @@ -5,39 +5,38 @@ */ package me.filoghost.chestcommands.attribute; +import java.util.ArrayList; +import java.util.List; import me.filoghost.chestcommands.icon.InternalConfigurableIcon; import me.filoghost.chestcommands.parsing.ItemMetaParser; import me.filoghost.chestcommands.parsing.ParseException; import org.bukkit.block.banner.Pattern; -import java.util.ArrayList; -import java.util.List; - public class BannerPatternsAttribute implements IconAttribute { - private final List patterns; + private final List patterns; - public BannerPatternsAttribute(List serializedPatterns, AttributeErrorHandler errorHandler) { - patterns = new ArrayList<>(); + public BannerPatternsAttribute(List serializedPatterns, AttributeErrorHandler errorHandler) { + patterns = new ArrayList<>(); - for (String serializedPattern : serializedPatterns) { - if (serializedPattern == null || serializedPattern.isEmpty()) { - continue; // Skip - } + for (String serializedPattern : serializedPatterns) { + if (serializedPattern == null || serializedPattern.isEmpty()) { + continue; // Skip + } - try { - Pattern pattern = ItemMetaParser.parseBannerPattern(serializedPattern); - patterns.add(pattern); - } catch (ParseException e) { - errorHandler.onListElementError(serializedPattern, e); - } - } + try { + Pattern pattern = ItemMetaParser.parseBannerPattern(serializedPattern); + patterns.add(pattern); + } catch (ParseException e) { + errorHandler.onListElementError(serializedPattern, e); + } + } - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setBannerPatterns(patterns); - } + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setBannerPatterns(patterns); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ClickPermissionAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ClickPermissionAttribute.java index 4c26176..541b5d6 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ClickPermissionAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ClickPermissionAttribute.java @@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon; public class ClickPermissionAttribute implements IconAttribute { - private final String clickPermission; + private final String clickPermission; - public ClickPermissionAttribute(String clickPermission, AttributeErrorHandler errorHandler) { - this.clickPermission = clickPermission; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setClickPermission(clickPermission); - } + public ClickPermissionAttribute(String clickPermission, AttributeErrorHandler errorHandler) { + this.clickPermission = clickPermission; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setClickPermission(clickPermission); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ClickPermissionMessageAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ClickPermissionMessageAttribute.java index 3b734ed..fa35226 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ClickPermissionMessageAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ClickPermissionMessageAttribute.java @@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon; public class ClickPermissionMessageAttribute implements IconAttribute { - private final String clickPermissionMessage; + private final String clickPermissionMessage; - public ClickPermissionMessageAttribute(String clickPermissionMessage, AttributeErrorHandler errorHandler) { - this.clickPermissionMessage = clickPermissionMessage; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setNoClickPermissionMessage(clickPermissionMessage); - } + public ClickPermissionMessageAttribute(String clickPermissionMessage, AttributeErrorHandler errorHandler) { + this.clickPermissionMessage = clickPermissionMessage; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setNoClickPermissionMessage(clickPermissionMessage); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/DurabilityAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/DurabilityAttribute.java index 1de4fc1..ccabb3a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/DurabilityAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/DurabilityAttribute.java @@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon; public class DurabilityAttribute implements IconAttribute { - private final short durability; + private final short durability; - public DurabilityAttribute(short durability, AttributeErrorHandler errorHandler) { - this.durability = durability; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setDurability(durability); - } + public DurabilityAttribute(short durability, AttributeErrorHandler errorHandler) { + this.durability = durability; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setDurability(durability); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/EnchantmentsAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/EnchantmentsAttribute.java index bd115ab..e7fc018 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/EnchantmentsAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/EnchantmentsAttribute.java @@ -5,39 +5,38 @@ */ package me.filoghost.chestcommands.attribute; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import me.filoghost.chestcommands.icon.InternalConfigurableIcon; import me.filoghost.chestcommands.parsing.EnchantmentParser; import me.filoghost.chestcommands.parsing.ParseException; import org.bukkit.enchantments.Enchantment; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class EnchantmentsAttribute implements IconAttribute { - private final Map enchantments; + private final Map enchantments; - public EnchantmentsAttribute(List serializedEnchantments, AttributeErrorHandler errorHandler) { - enchantments = new HashMap<>(); + public EnchantmentsAttribute(List serializedEnchantments, AttributeErrorHandler errorHandler) { + enchantments = new HashMap<>(); - for (String serializedEnchantment : serializedEnchantments) { - if (serializedEnchantment == null || serializedEnchantment.isEmpty()) { - continue; // Skip - } + for (String serializedEnchantment : serializedEnchantments) { + if (serializedEnchantment == null || serializedEnchantment.isEmpty()) { + continue; // Skip + } - try { - EnchantmentParser.EnchantmentDetails enchantment = EnchantmentParser.parseEnchantment(serializedEnchantment); - enchantments.put(enchantment.getEnchantment(), enchantment.getLevel()); - } catch (ParseException e) { - errorHandler.onListElementError(serializedEnchantment, e); - } - } - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setEnchantments(enchantments); - } + try { + EnchantmentParser.EnchantmentDetails enchantment = EnchantmentParser.parseEnchantment(serializedEnchantment); + enchantments.put(enchantment.getEnchantment(), enchantment.getLevel()); + } catch (ParseException e) { + errorHandler.onListElementError(serializedEnchantment, e); + } + } + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setEnchantments(enchantments); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ExpLevelsAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ExpLevelsAttribute.java index c7fe465..f0ed5f4 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ExpLevelsAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ExpLevelsAttribute.java @@ -11,18 +11,18 @@ import me.filoghost.chestcommands.parsing.ParseException; public class ExpLevelsAttribute implements IconAttribute { - private final int expLevels; + private final int expLevels; - public ExpLevelsAttribute(int expLevels, AttributeErrorHandler errorHandler) throws ParseException { - if (expLevels < 0) { - throw new ParseException(Errors.Parsing.zeroOrPositive); - } - this.expLevels = expLevels; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setRequiredExpLevel(expLevels); - } + public ExpLevelsAttribute(int expLevels, AttributeErrorHandler errorHandler) throws ParseException { + if (expLevels < 0) { + throw new ParseException(Errors.Parsing.zeroOrPositive); + } + this.expLevels = expLevels; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setRequiredExpLevel(expLevels); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/IconAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/IconAttribute.java index f3ca62e..3353db2 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/IconAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/IconAttribute.java @@ -9,5 +9,5 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon; public interface IconAttribute { - void apply(InternalConfigurableIcon icon); + void apply(InternalConfigurableIcon icon); } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/KeepOpenAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/KeepOpenAttribute.java index 3ec66aa..08da7d6 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/KeepOpenAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/KeepOpenAttribute.java @@ -10,19 +10,19 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon; public class KeepOpenAttribute implements IconAttribute { - private final ClickResult clickResult; + private final ClickResult clickResult; - public KeepOpenAttribute(boolean keepOpen, AttributeErrorHandler errorHandler) { - if (keepOpen) { - this.clickResult = ClickResult.KEEP_OPEN; - } else { - this.clickResult = ClickResult.CLOSE; - } - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setClickResult(clickResult); - } + public KeepOpenAttribute(boolean keepOpen, AttributeErrorHandler errorHandler) { + if (keepOpen) { + this.clickResult = ClickResult.KEEP_OPEN; + } else { + this.clickResult = ClickResult.CLOSE; + } + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setClickResult(clickResult); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/LeatherColorAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/LeatherColorAttribute.java index 1d1a3bf..2b60ffa 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/LeatherColorAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/LeatherColorAttribute.java @@ -12,15 +12,15 @@ import org.bukkit.Color; public class LeatherColorAttribute implements IconAttribute { - private final Color color; + private final Color color; - public LeatherColorAttribute(String serializedColor, AttributeErrorHandler errorHandler) throws ParseException { - this.color = ItemMetaParser.parseRGBColor(serializedColor); - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setLeatherColor(color); - } + public LeatherColorAttribute(String serializedColor, AttributeErrorHandler errorHandler) throws ParseException { + this.color = ItemMetaParser.parseRGBColor(serializedColor); + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setLeatherColor(color); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/LoreAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/LoreAttribute.java index 0d52530..14c8504 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/LoreAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/LoreAttribute.java @@ -5,34 +5,33 @@ */ package me.filoghost.chestcommands.attribute; +import java.util.List; import me.filoghost.chestcommands.config.Settings; import me.filoghost.chestcommands.icon.InternalConfigurableIcon; import me.filoghost.fcommons.Colors; import me.filoghost.fcommons.collection.CollectionUtils; -import java.util.List; - public class LoreAttribute implements IconAttribute { - private final List lore; - - public LoreAttribute(List lore, AttributeErrorHandler errorHandler) { - this.lore = colorLore(lore); - } + private final List lore; + + public LoreAttribute(List lore, AttributeErrorHandler errorHandler) { + this.lore = colorLore(lore); + } - private List colorLore(List input) { - return CollectionUtils.transform(input, line -> { - if (!line.isEmpty()) { - return Settings.default_color__lore + Colors.addColors(line); - } else { - return line; - } - }); - } + private List colorLore(List input) { + return CollectionUtils.transform(input, line -> { + if (!line.isEmpty()) { + return Settings.default_color__lore + Colors.addColors(line); + } else { + return line; + } + }); + } - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setLore(lore); - } + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setLore(lore); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/MaterialAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/MaterialAttribute.java index 989545f..a16c590 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/MaterialAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/MaterialAttribute.java @@ -11,16 +11,16 @@ import me.filoghost.chestcommands.parsing.ParseException; import org.bukkit.Material; public class MaterialAttribute implements IconAttribute { - - private final Material material; - public MaterialAttribute(String serializedMaterial, AttributeErrorHandler errorHandler) throws ParseException { - this.material = MaterialParser.parseMaterial(serializedMaterial); - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setMaterial(material); - } + private final Material material; + + public MaterialAttribute(String serializedMaterial, AttributeErrorHandler errorHandler) throws ParseException { + this.material = MaterialParser.parseMaterial(serializedMaterial); + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setMaterial(material); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/NBTDataAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/NBTDataAttribute.java index 184d3ae..d26c5ef 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/NBTDataAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/NBTDataAttribute.java @@ -12,22 +12,22 @@ import me.filoghost.chestcommands.util.nbt.parser.MojangsonParser; public class NBTDataAttribute implements IconAttribute { - private final String nbtData; + private final String nbtData; - public NBTDataAttribute(String nbtData, AttributeErrorHandler errorHandler) throws ParseException { - try { - // Check that NBT syntax is valid before applying it to the icon - MojangsonParser.parse(nbtData); - } catch (MojangsonParseException e) { - throw new ParseException(e.getMessage()); - } + public NBTDataAttribute(String nbtData, AttributeErrorHandler errorHandler) throws ParseException { + try { + // Check that NBT syntax is valid before applying it to the icon + MojangsonParser.parse(nbtData); + } catch (MojangsonParseException e) { + throw new ParseException(e.getMessage()); + } - this.nbtData = nbtData; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setNBTData(nbtData); - } + this.nbtData = nbtData; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setNBTData(nbtData); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/NameAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/NameAttribute.java index da83f45..f66fea3 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/NameAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/NameAttribute.java @@ -11,23 +11,23 @@ import me.filoghost.fcommons.Colors; public class NameAttribute implements IconAttribute { - private final String name; + private final String name; - public NameAttribute(String name, AttributeErrorHandler errorHandler) { - this.name = colorName(name); - } + public NameAttribute(String name, AttributeErrorHandler errorHandler) { + this.name = colorName(name); + } - private String colorName(String name) { - if (!name.isEmpty()) { - return Settings.default_color__name + Colors.addColors(name); - } else { - return name; - } - } + private String colorName(String name) { + if (!name.isEmpty()) { + return Settings.default_color__name + Colors.addColors(name); + } else { + return name; + } + } - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setName(name); - } + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setName(name); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/PositionAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/PositionAttribute.java index 4e87842..a1f68f7 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/PositionAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/PositionAttribute.java @@ -8,19 +8,19 @@ package me.filoghost.chestcommands.attribute; import me.filoghost.chestcommands.icon.InternalConfigurableIcon; public class PositionAttribute implements IconAttribute { - - private final int position; + + private final int position; - public PositionAttribute(int position, AttributeErrorHandler errorHandler) { - this.position = position; - } - - public int getPosition() { - return position; - } + public PositionAttribute(int position, AttributeErrorHandler errorHandler) { + this.position = position; + } + + public int getPosition() { + return position; + } - @Override - public void apply(InternalConfigurableIcon icon) { - // Position has no effect on the icon itself - } + @Override + public void apply(InternalConfigurableIcon icon) { + // Position has no effect on the icon itself + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/PriceAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/PriceAttribute.java index 17b0e86..d2225f1 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/PriceAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/PriceAttribute.java @@ -11,18 +11,18 @@ import me.filoghost.chestcommands.parsing.ParseException; public class PriceAttribute implements IconAttribute { - private final double price; + private final double price; - public PriceAttribute(double price, AttributeErrorHandler errorHandler) throws ParseException { - if (price < 0) { - throw new ParseException(Errors.Parsing.zeroOrPositive); - } - this.price = price; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setRequiredMoney(price); - } + public PriceAttribute(double price, AttributeErrorHandler errorHandler) throws ParseException { + if (price < 0) { + throw new ParseException(Errors.Parsing.zeroOrPositive); + } + this.price = price; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setRequiredMoney(price); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/RequiredItemsAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/RequiredItemsAttribute.java index a24b49b..4c73ab3 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/RequiredItemsAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/RequiredItemsAttribute.java @@ -5,39 +5,38 @@ */ package me.filoghost.chestcommands.attribute; +import java.util.ArrayList; +import java.util.List; import me.filoghost.chestcommands.icon.InternalConfigurableIcon; import me.filoghost.chestcommands.icon.requirement.item.RequiredItem; import me.filoghost.chestcommands.parsing.ItemStackParser; import me.filoghost.chestcommands.parsing.ParseException; -import java.util.ArrayList; -import java.util.List; - public class RequiredItemsAttribute implements IconAttribute { - private final List requiredItems; + private final List requiredItems; - public RequiredItemsAttribute(List serializedRequiredItems, AttributeErrorHandler errorHandler) { - requiredItems = new ArrayList<>(); + public RequiredItemsAttribute(List serializedRequiredItems, AttributeErrorHandler errorHandler) { + requiredItems = new ArrayList<>(); - for (String serializedItem : serializedRequiredItems) { - try { - ItemStackParser itemReader = new ItemStackParser(serializedItem, true); - itemReader.checkNotAir(); - RequiredItem requiredItem = new RequiredItem(itemReader.getMaterial(), itemReader.getAmount()); - if (itemReader.hasExplicitDurability()) { - requiredItem.setRestrictiveDurability(itemReader.getDurability()); - } - requiredItems.add(requiredItem); - } catch (ParseException e) { - errorHandler.onListElementError(serializedItem, e); - } - } - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setRequiredItems(requiredItems); - } + for (String serializedItem : serializedRequiredItems) { + try { + ItemStackParser itemReader = new ItemStackParser(serializedItem, true); + itemReader.checkNotAir(); + RequiredItem requiredItem = new RequiredItem(itemReader.getMaterial(), itemReader.getAmount()); + if (itemReader.hasExplicitDurability()) { + requiredItem.setRestrictiveDurability(itemReader.getDurability()); + } + requiredItems.add(requiredItem); + } catch (ParseException e) { + errorHandler.onListElementError(serializedItem, e); + } + } + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setRequiredItems(requiredItems); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/SkullOwnerAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/SkullOwnerAttribute.java index e756492..3a5b706 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/SkullOwnerAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/SkullOwnerAttribute.java @@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon; public class SkullOwnerAttribute implements IconAttribute { - private final String skullOwner; + private final String skullOwner; - public SkullOwnerAttribute(String skullOwner, AttributeErrorHandler errorHandler) { - this.skullOwner = skullOwner; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setSkullOwner(skullOwner); - } + public SkullOwnerAttribute(String skullOwner, AttributeErrorHandler errorHandler) { + this.skullOwner = skullOwner; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setSkullOwner(skullOwner); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ViewPermissionAttribute.java b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ViewPermissionAttribute.java index c6262cd..0e7f681 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/attribute/ViewPermissionAttribute.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/attribute/ViewPermissionAttribute.java @@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon; public class ViewPermissionAttribute implements IconAttribute { - private final String viewPermission; + private final String viewPermission; - public ViewPermissionAttribute(String viewPermission, AttributeErrorHandler errorHandler) { - this.viewPermission = viewPermission; - } - - @Override - public void apply(InternalConfigurableIcon icon) { - icon.setViewPermission(viewPermission); - } + public ViewPermissionAttribute(String viewPermission, AttributeErrorHandler errorHandler) { + this.viewPermission = viewPermission; + } + + @Override + public void apply(InternalConfigurableIcon icon) { + icon.setViewPermission(viewPermission); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/command/CommandHandler.java b/plugin/src/main/java/me/filoghost/chestcommands/command/CommandHandler.java index 1a1fd98..72c5b3c 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/command/CommandHandler.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/command/CommandHandler.java @@ -20,130 +20,130 @@ import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; public class CommandHandler extends CommandFramework { - - private final MenuManager menuManager; - - public CommandHandler(MenuManager menuManager, String label) { - super(label); - this.menuManager = menuManager; - } + + private final MenuManager menuManager; + + public CommandHandler(MenuManager menuManager, String label) { + super(label); + this.menuManager = menuManager; + } - @SuppressWarnings("deprecation") - @Override - public void execute(CommandSender sender, String label, String[] args) { - if (args.length == 0) { - // This info is accessible to anyone. Please don't remove it, remember that Chest Commands is developed for free - sender.sendMessage(ChestCommands.CHAT_PREFIX); - sender.sendMessage(ChatColor.GREEN + "Version: " + ChatColor.GRAY + ChestCommands.getPluginInstance().getDescription().getVersion()); - sender.sendMessage(ChatColor.GREEN + "Developer: " + ChatColor.GRAY + "filoghost"); - sender.sendMessage(ChatColor.GREEN + "Commands: " + ChatColor.GRAY + "/" + label + " help"); - return; - } + @SuppressWarnings("deprecation") + @Override + public void execute(CommandSender sender, String label, String[] args) { + if (args.length == 0) { + // This info is accessible to anyone. Please don't remove it, remember that Chest Commands is developed for free + sender.sendMessage(ChestCommands.CHAT_PREFIX); + sender.sendMessage(ChatColor.GREEN + "Version: " + ChatColor.GRAY + ChestCommands.getPluginInstance().getDescription().getVersion()); + sender.sendMessage(ChatColor.GREEN + "Developer: " + ChatColor.GRAY + "filoghost"); + sender.sendMessage(ChatColor.GREEN + "Commands: " + ChatColor.GRAY + "/" + label + " help"); + return; + } - if (args[0].equalsIgnoreCase("help")) { - checkCommandPermission(sender, "help"); - sender.sendMessage(ChestCommands.CHAT_PREFIX + "Commands:"); - sender.sendMessage(ChatColor.WHITE + "/" + label + " reload" + ChatColor.GRAY + " - Reloads the plugin."); - sender.sendMessage(ChatColor.WHITE + "/" + label + " errors" + ChatColor.GRAY + " - Displays the last load errors on the console."); - sender.sendMessage(ChatColor.WHITE + "/" + label + " list" + ChatColor.GRAY + " - Lists the loaded menus."); - sender.sendMessage(ChatColor.WHITE + "/" + label + " open [player]" + ChatColor.GRAY + " - Opens a menu for a player."); - return; - } + if (args[0].equalsIgnoreCase("help")) { + checkCommandPermission(sender, "help"); + sender.sendMessage(ChestCommands.CHAT_PREFIX + "Commands:"); + sender.sendMessage(ChatColor.WHITE + "/" + label + " reload" + ChatColor.GRAY + " - Reloads the plugin."); + sender.sendMessage(ChatColor.WHITE + "/" + label + " errors" + ChatColor.GRAY + " - Displays the last load errors on the console."); + sender.sendMessage(ChatColor.WHITE + "/" + label + " list" + ChatColor.GRAY + " - Lists the loaded menus."); + sender.sendMessage(ChatColor.WHITE + "/" + label + " open [player]" + ChatColor.GRAY + " - Opens a menu for a player."); + return; + } - if (args[0].equalsIgnoreCase("errors")) { - checkCommandPermission(sender, "errors"); - ErrorCollector errorCollector = ChestCommands.getLastLoadErrors(); + if (args[0].equalsIgnoreCase("errors")) { + checkCommandPermission(sender, "errors"); + ErrorCollector errorCollector = ChestCommands.getLastLoadErrors(); - if (errorCollector.hasErrors()) { - errorCollector.logToConsole(); - sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Last time the plugin loaded, " + errorCollector.getErrorsCount() + " error(s) were found."); - if (!(sender instanceof ConsoleCommandSender)) { - sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Errors were printed on the console."); - } - } else { - sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.GREEN + "Last plugin load was successful, no errors logged."); - } - return; - } + if (errorCollector.hasErrors()) { + errorCollector.logToConsole(); + sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Last time the plugin loaded, " + errorCollector.getErrorsCount() + " error(s) were found."); + if (!(sender instanceof ConsoleCommandSender)) { + sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Errors were printed on the console."); + } + } else { + sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.GREEN + "Last plugin load was successful, no errors logged."); + } + return; + } - if (args[0].equalsIgnoreCase("reload")) { - checkCommandPermission(sender, "reload"); + if (args[0].equalsIgnoreCase("reload")) { + checkCommandPermission(sender, "reload"); - ChestCommands.closeAllMenus(); + ChestCommands.closeAllMenus(); - ErrorCollector errorCollector = ChestCommands.load(); + ErrorCollector errorCollector = ChestCommands.load(); - if (!errorCollector.hasErrors()) { - sender.sendMessage(ChestCommands.CHAT_PREFIX + "Plugin reloaded."); - } else { - errorCollector.logToConsole(); - sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Plugin reloaded with " + errorCollector.getErrorsCount() + " error(s)."); - if (!(sender instanceof ConsoleCommandSender)) { - sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Please check the console."); - } - } - return; - } + if (!errorCollector.hasErrors()) { + sender.sendMessage(ChestCommands.CHAT_PREFIX + "Plugin reloaded."); + } else { + errorCollector.logToConsole(); + sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Plugin reloaded with " + errorCollector.getErrorsCount() + " error(s)."); + if (!(sender instanceof ConsoleCommandSender)) { + sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Please check the console."); + } + } + return; + } - if (args[0].equalsIgnoreCase("open")) { - checkCommandPermission(sender, "open"); - CommandValidate.minLength(args, 2, "Usage: /" + label + " open [player]"); + if (args[0].equalsIgnoreCase("open")) { + checkCommandPermission(sender, "open"); + CommandValidate.minLength(args, 2, "Usage: /" + label + " open [player]"); - Player target; + Player target; - if (sender instanceof Player) { - if (args.length > 2) { - checkCommandPermission(sender, "open.others"); - target = Bukkit.getPlayerExact(args[2]); - } else { - target = (Player) sender; - } - } else { - CommandValidate.minLength(args, 3, "You must specify a player from the console."); - target = Bukkit.getPlayerExact(args[2]); - } + if (sender instanceof Player) { + if (args.length > 2) { + checkCommandPermission(sender, "open.others"); + target = Bukkit.getPlayerExact(args[2]); + } else { + target = (Player) sender; + } + } else { + CommandValidate.minLength(args, 3, "You must specify a player from the console."); + target = Bukkit.getPlayerExact(args[2]); + } - CommandValidate.notNull(target, "That player is not online."); + CommandValidate.notNull(target, "That player is not online."); - String menuName = Utils.addYamlExtension(args[1]); - InternalMenu menu = menuManager.getMenuByFileName(menuName); - CommandValidate.notNull(menu, "The menu \"" + menuName + "\" was not found."); + String menuName = Utils.addYamlExtension(args[1]); + InternalMenu menu = menuManager.getMenuByFileName(menuName); + CommandValidate.notNull(menu, "The menu \"" + menuName + "\" was not found."); - if (!sender.hasPermission(menu.getOpenPermission())) { - menu.sendNoOpenPermissionMessage(sender); - return; - } + if (!sender.hasPermission(menu.getOpenPermission())) { + menu.sendNoOpenPermissionMessage(sender); + return; + } - if (sender.getName().equalsIgnoreCase(target.getName())) { - sender.sendMessage(ChatColor.GREEN + "Opening the menu " + menuName + "."); - } else { - sender.sendMessage(ChatColor.GREEN + "Opening the menu " + menuName + " to " + target.getName() + "."); - } + if (sender.getName().equalsIgnoreCase(target.getName())) { + sender.sendMessage(ChatColor.GREEN + "Opening the menu " + menuName + "."); + } else { + sender.sendMessage(ChatColor.GREEN + "Opening the menu " + menuName + " to " + target.getName() + "."); + } - menu.open(target); - return; - } + menu.open(target); + return; + } - if (args[0].equalsIgnoreCase("list")) { - checkCommandPermission(sender, "list"); - sender.sendMessage(ChestCommands.CHAT_PREFIX + "Loaded menus:"); - for (String file : menuManager.getMenuFileNames()) { - sender.sendMessage(ChatColor.GRAY + "- " + ChatColor.WHITE + file); - } + if (args[0].equalsIgnoreCase("list")) { + checkCommandPermission(sender, "list"); + sender.sendMessage(ChestCommands.CHAT_PREFIX + "Loaded menus:"); + for (String file : menuManager.getMenuFileNames()) { + sender.sendMessage(ChatColor.GRAY + "- " + ChatColor.WHITE + file); + } - return; - } + return; + } - sender.sendMessage(ChatColor.RED + "Unknown sub-command \"" + args[0] + "\"."); - } + sender.sendMessage(ChatColor.RED + "Unknown sub-command \"" + args[0] + "\"."); + } - private void checkCommandPermission(CommandSender sender, String commandPermission) { - CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_PREFIX + commandPermission), "You don't have permission."); - } + private void checkCommandPermission(CommandSender sender, String commandPermission) { + CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_PREFIX + commandPermission), "You don't have permission."); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/config/ConfigManager.java b/plugin/src/main/java/me/filoghost/chestcommands/config/ConfigManager.java index ea0a152..a014712 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/config/ConfigManager.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/config/ConfigManager.java @@ -5,6 +5,15 @@ */ package me.filoghost.chestcommands.config; +import java.io.IOException; +import java.nio.file.FileVisitOption; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; import me.filoghost.chestcommands.logging.Errors; import me.filoghost.chestcommands.parsing.menu.LoadedMenu; import me.filoghost.chestcommands.parsing.menu.MenuParser; @@ -16,110 +25,100 @@ import me.filoghost.fcommons.config.exception.ConfigException; import me.filoghost.fcommons.config.mapped.MappedConfigLoader; import me.filoghost.fcommons.logging.ErrorCollector; -import java.io.IOException; -import java.nio.file.FileVisitOption; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - public class ConfigManager extends BaseConfigManager { - private final MappedConfigLoader settingsConfigLoader; - private final ConfigLoader placeholdersConfigLoader; - private final MappedConfigLoader langConfigLoader; + private final MappedConfigLoader settingsConfigLoader; + private final ConfigLoader placeholdersConfigLoader; + private final MappedConfigLoader langConfigLoader; - public ConfigManager(Path rootDataFolder) { - super(rootDataFolder); + public ConfigManager(Path rootDataFolder) { + super(rootDataFolder); - settingsConfigLoader = getMappedConfigLoader("config.yml", Settings::new); - placeholdersConfigLoader = getConfigLoader("custom-placeholders.yml"); - langConfigLoader = getMappedConfigLoader("lang.yml", Lang::new); - } + settingsConfigLoader = getMappedConfigLoader("config.yml", Settings::new); + placeholdersConfigLoader = getConfigLoader("custom-placeholders.yml"); + langConfigLoader = getMappedConfigLoader("lang.yml", Lang::new); + } - public void tryLoadSettings(ErrorCollector errorCollector) { - try { - settingsConfigLoader.init(); - } catch (ConfigException e) { - logConfigInitException(errorCollector, settingsConfigLoader.getFile(), e); - } - } + public void tryLoadSettings(ErrorCollector errorCollector) { + try { + settingsConfigLoader.init(); + } catch (ConfigException e) { + logConfigInitException(errorCollector, settingsConfigLoader.getFile(), e); + } + } - public void tryLoadLang(ErrorCollector errorCollector) { - try { - langConfigLoader.init(); - } catch (ConfigException e) { - logConfigInitException(errorCollector, langConfigLoader.getFile(), e); - } - } + public void tryLoadLang(ErrorCollector errorCollector) { + try { + langConfigLoader.init(); + } catch (ConfigException e) { + logConfigInitException(errorCollector, langConfigLoader.getFile(), e); + } + } - public CustomPlaceholders tryLoadCustomPlaceholders(ErrorCollector errorCollector) { - CustomPlaceholders placeholders = new CustomPlaceholders(); + public CustomPlaceholders tryLoadCustomPlaceholders(ErrorCollector errorCollector) { + CustomPlaceholders placeholders = new CustomPlaceholders(); - try { - Config placeholdersConfig = placeholdersConfigLoader.init(); - placeholders.load(placeholdersConfig, errorCollector); - } catch (ConfigException t) { - logConfigInitException(errorCollector, placeholdersConfigLoader.getFile(), t); - } + try { + Config placeholdersConfig = placeholdersConfigLoader.init(); + placeholders.load(placeholdersConfig, errorCollector); + } catch (ConfigException t) { + logConfigInitException(errorCollector, placeholdersConfigLoader.getFile(), t); + } - return placeholders; - } + return placeholders; + } - public void tryCreateDefault(ErrorCollector errorCollector, ConfigLoader configLoader) { - try { - configLoader.createDefault(); - } catch (ConfigException e) { - logConfigInitException(errorCollector, configLoader.getFile(), e); - } - } + public void tryCreateDefault(ErrorCollector errorCollector, ConfigLoader configLoader) { + try { + configLoader.createDefault(); + } catch (ConfigException e) { + logConfigInitException(errorCollector, configLoader.getFile(), e); + } + } - public Path getMenusFolder() { - return rootDataFolder.resolve("menu"); - } + public Path getMenusFolder() { + return rootDataFolder.resolve("menu"); + } - public List getMenuFiles() throws IOException { - Preconditions.checkState(Files.isDirectory(getMenusFolder()), "menus folder doesn't exist"); + public List getMenuFiles() throws IOException { + Preconditions.checkState(Files.isDirectory(getMenusFolder()), "menus folder doesn't exist"); - try (Stream paths = Files.walk(getMenusFolder(), FileVisitOption.FOLLOW_LINKS)) { - return paths.filter(this::isYamlFile).collect(Collectors.toList()); - } - } + try (Stream paths = Files.walk(getMenusFolder(), FileVisitOption.FOLLOW_LINKS)) { + return paths.filter(this::isYamlFile).collect(Collectors.toList()); + } + } - private void logConfigInitException(ErrorCollector errorCollector, Path file, ConfigException e) { - errorCollector.add(e, Errors.Config.initException(file)); - } + private void logConfigInitException(ErrorCollector errorCollector, Path file, ConfigException e) { + errorCollector.add(e, Errors.Config.initException(file)); + } - public List tryLoadMenus(ErrorCollector errorCollector) { - List loadedMenus = new ArrayList<>(); - List menuFiles; + public List tryLoadMenus(ErrorCollector errorCollector) { + List loadedMenus = new ArrayList<>(); + List menuFiles; - try { - menuFiles = getMenuFiles(); - } catch (IOException e) { - errorCollector.add(e, Errors.Config.menuListIOException(getMenusFolder())); - return Collections.emptyList(); - } + try { + menuFiles = getMenuFiles(); + } catch (IOException e) { + errorCollector.add(e, Errors.Config.menuListIOException(getMenusFolder())); + return Collections.emptyList(); + } - for (Path menuFile : menuFiles) { - ConfigLoader menuConfigLoader = new ConfigLoader(rootDataFolder, menuFile); + for (Path menuFile : menuFiles) { + ConfigLoader menuConfigLoader = new ConfigLoader(rootDataFolder, menuFile); - try { - Config menuConfig = menuConfigLoader.load(); - loadedMenus.add(MenuParser.loadMenu(menuConfig, errorCollector)); - } catch (ConfigException e) { - logConfigInitException(errorCollector, menuConfigLoader.getFile(), e); - } - } + try { + Config menuConfig = menuConfigLoader.load(); + loadedMenus.add(MenuParser.loadMenu(menuConfig, errorCollector)); + } catch (ConfigException e) { + logConfigInitException(errorCollector, menuConfigLoader.getFile(), e); + } + } - return loadedMenus; - } + return loadedMenus; + } - private boolean isYamlFile(Path path) { - return Files.isRegularFile(path) && path.getFileName().toString().toLowerCase().endsWith(".yml"); - } + private boolean isYamlFile(Path path) { + return Files.isRegularFile(path) && path.getFileName().toString().toLowerCase().endsWith(".yml"); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/config/CustomPlaceholders.java b/plugin/src/main/java/me/filoghost/chestcommands/config/CustomPlaceholders.java index 3b6696d..ef8b033 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/config/CustomPlaceholders.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/config/CustomPlaceholders.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.config; +import java.util.ArrayList; +import java.util.List; import me.filoghost.chestcommands.logging.Errors; import me.filoghost.chestcommands.placeholder.StaticPlaceholder; import me.filoghost.fcommons.Colors; @@ -12,43 +14,40 @@ import me.filoghost.fcommons.config.Config; import me.filoghost.fcommons.config.ConfigSection; import me.filoghost.fcommons.logging.ErrorCollector; -import java.util.ArrayList; -import java.util.List; - public class CustomPlaceholders { - private final List placeholders = new ArrayList<>(); + private final List placeholders = new ArrayList<>(); - public void load(Config config, ErrorCollector errorCollector) { - placeholders.clear(); + public void load(Config config, ErrorCollector errorCollector) { + placeholders.clear(); - ConfigSection placeholdersSection = config.getConfigSection("placeholders"); - if (placeholdersSection == null) { - return; - } + ConfigSection placeholdersSection = config.getConfigSection("placeholders"); + if (placeholdersSection == null) { + return; + } - for (String placeholder : placeholdersSection.getKeys()) { - String replacement = Colors.addColors(placeholdersSection.getString(placeholder)); - if (replacement == null) { - return; - } + for (String placeholder : placeholdersSection.getKeys()) { + String replacement = Colors.addColors(placeholdersSection.getString(placeholder)); + if (replacement == null) { + return; + } - if (placeholder.length() == 0) { - errorCollector.add(Errors.Config.emptyPlaceholder(config.getSourceFile())); - continue; - } + if (placeholder.length() == 0) { + errorCollector.add(Errors.Config.emptyPlaceholder(config.getSourceFile())); + continue; + } - if (placeholder.length() > 100) { - errorCollector.add(Errors.Config.tooLongPlaceholder(config.getSourceFile(), placeholder)); - continue; - } + if (placeholder.length() > 100) { + errorCollector.add(Errors.Config.tooLongPlaceholder(config.getSourceFile(), placeholder)); + continue; + } - placeholders.add(new StaticPlaceholder(placeholder, replacement)); - } - } + placeholders.add(new StaticPlaceholder(placeholder, replacement)); + } + } - public List getPlaceholders() { - return placeholders; - } + public List getPlaceholders() { + return placeholders; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/config/Lang.java b/plugin/src/main/java/me/filoghost/chestcommands/config/Lang.java index 1a2b326..bde5587 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/config/Lang.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/config/Lang.java @@ -14,12 +14,12 @@ import me.filoghost.fcommons.config.mapped.modifier.ChatColors; @IncludeStatic public class Lang extends MappedConfig { - public static String no_open_permission = "&cYou don't have permission &e{permission} &cto use this menu."; - public static String default_no_icon_permission = "&cYou don't have permission for this icon."; - public static String no_required_item = "&cYou must have &e{amount}x {material} &c(durability: {durability}) for this."; - public static String no_money = "&cYou need {money}$ for this."; - public static String no_exp = "&cYou need {levels} XP levels for this."; - public static String menu_not_found = "&cMenu not found! " + Errors.User.notifyStaffRequest; - public static String any = "any"; // Used in no_required_item when durability is not restrictive + public static String no_open_permission = "&cYou don't have permission &e{permission} &cto use this menu."; + public static String default_no_icon_permission = "&cYou don't have permission for this icon."; + public static String no_required_item = "&cYou must have &e{amount}x {material} &c(durability: {durability}) for this."; + public static String no_money = "&cYou need {money}$ for this."; + public static String no_exp = "&cYou need {levels} XP levels for this."; + public static String menu_not_found = "&cMenu not found! " + Errors.User.notifyStaffRequest; + public static String any = "any"; // Used in no_required_item when durability is not restrictive } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/config/Settings.java b/plugin/src/main/java/me/filoghost/chestcommands/config/Settings.java index 2ca3ec0..1293638 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/config/Settings.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/config/Settings.java @@ -13,15 +13,15 @@ import me.filoghost.fcommons.config.mapped.modifier.ChatColors; @IncludeStatic public class Settings extends MappedConfig { - public static String default_color__name = "&f"; - public static String default_color__lore = "&7"; - public static boolean update_notifications = true; - public static int anti_click_spam_delay = 200; + public static String default_color__name = "&f"; + public static String default_color__lore = "&7"; + public static boolean update_notifications = true; + public static int anti_click_spam_delay = 200; - public Settings() { - setHeader( - "ChestCommands main configuration file.", - "Documentation: https://filoghost.me/docs/chest-commands"); - } + public Settings() { + setHeader( + "ChestCommands main configuration file.", + "Documentation: https://filoghost.me/docs/chest-commands"); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/hook/BarAPIHook.java b/plugin/src/main/java/me/filoghost/chestcommands/hook/BarAPIHook.java index 70739d7..c5a4b96 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/hook/BarAPIHook.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/hook/BarAPIHook.java @@ -11,25 +11,25 @@ import org.bukkit.entity.Player; public enum BarAPIHook implements PluginHook { - INSTANCE; - - private boolean enabled; + INSTANCE; - @Override - public void setup() { - enabled = Bukkit.getPluginManager().getPlugin("BarAPI") != null; - } - - @Override - public boolean isEnabled() { - return enabled; - } - - @SuppressWarnings("deprecation") - public static void setMessage(Player player, String message, int seconds) { - INSTANCE.checkEnabledState(); - - BarAPI.setMessage(player, message, seconds); - } + private boolean enabled; + + @Override + public void setup() { + enabled = Bukkit.getPluginManager().getPlugin("BarAPI") != null; + } + + @Override + public boolean isEnabled() { + return enabled; + } + + @SuppressWarnings("deprecation") + public static void setMessage(Player player, String message, int seconds) { + INSTANCE.checkEnabledState(); + + BarAPI.setMessage(player, message, seconds); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/hook/BungeeCordHook.java b/plugin/src/main/java/me/filoghost/chestcommands/hook/BungeeCordHook.java index 07214af..f64d728 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/hook/BungeeCordHook.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/hook/BungeeCordHook.java @@ -5,50 +5,49 @@ */ package me.filoghost.chestcommands.hook; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; import me.filoghost.chestcommands.ChestCommands; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; - public enum BungeeCordHook implements PluginHook { - - INSTANCE; - @Override - public void setup() { - if (!Bukkit.getMessenger().isOutgoingChannelRegistered(ChestCommands.getPluginInstance(), "BungeeCord")) { - Bukkit.getMessenger().registerOutgoingPluginChannel(ChestCommands.getPluginInstance(), "BungeeCord"); - } - } + INSTANCE; - @Override - public boolean isEnabled() { - return true; - } - - public static void connect(Player player, String server) { - INSTANCE.checkEnabledState(); - - if (server.length() == 0) { - player.sendMessage(ChatColor.RED + "Target server was an empty string, cannot connect to it."); - return; - } + @Override + public void setup() { + if (!Bukkit.getMessenger().isOutgoingChannelRegistered(ChestCommands.getPluginInstance(), "BungeeCord")) { + Bukkit.getMessenger().registerOutgoingPluginChannel(ChestCommands.getPluginInstance(), "BungeeCord"); + } + } - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream); + @Override + public boolean isEnabled() { + return true; + } - try { - dataOutputStream.writeUTF("Connect"); - dataOutputStream.writeUTF(server); // Target Server - } catch (IOException ex) { - throw new AssertionError(); - } + public static void connect(Player player, String server) { + INSTANCE.checkEnabledState(); - player.sendPluginMessage(ChestCommands.getPluginInstance(), "BungeeCord", byteArrayOutputStream.toByteArray()); - } + if (server.length() == 0) { + player.sendMessage(ChatColor.RED + "Target server was an empty string, cannot connect to it."); + return; + } + + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream); + + try { + dataOutputStream.writeUTF("Connect"); + dataOutputStream.writeUTF(server); // Target Server + } catch (IOException ex) { + throw new AssertionError(); + } + + player.sendPluginMessage(ChestCommands.getPluginInstance(), "BungeeCord", byteArrayOutputStream.toByteArray()); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/hook/PlaceholderAPIHook.java b/plugin/src/main/java/me/filoghost/chestcommands/hook/PlaceholderAPIHook.java index 2712847..a1c360a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/hook/PlaceholderAPIHook.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/hook/PlaceholderAPIHook.java @@ -11,30 +11,30 @@ import org.bukkit.entity.Player; public enum PlaceholderAPIHook implements PluginHook { - INSTANCE; - - private boolean enabled; + INSTANCE; - @Override - public void setup() { - enabled = Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null; - } + private boolean enabled; - @Override - public boolean isEnabled() { - return enabled; - } + @Override + public void setup() { + enabled = Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null; + } - public static boolean hasPlaceholders(String message) { - INSTANCE.checkEnabledState(); - - return PlaceholderAPI.containsPlaceholders(message); - } + @Override + public boolean isEnabled() { + return enabled; + } - public static String setPlaceholders(String message, Player viewer) { - INSTANCE.checkEnabledState(); + public static boolean hasPlaceholders(String message) { + INSTANCE.checkEnabledState(); - return PlaceholderAPI.setPlaceholders(viewer, message); - } + return PlaceholderAPI.containsPlaceholders(message); + } + + public static String setPlaceholders(String message, Player viewer) { + INSTANCE.checkEnabledState(); + + return PlaceholderAPI.setPlaceholders(viewer, message); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/hook/PluginHook.java b/plugin/src/main/java/me/filoghost/chestcommands/hook/PluginHook.java index dd59fdf..50a040a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/hook/PluginHook.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/hook/PluginHook.java @@ -9,13 +9,13 @@ import me.filoghost.fcommons.Preconditions; public interface PluginHook { - - void setup(); - - boolean isEnabled(); - - default void checkEnabledState() { - Preconditions.checkState(isEnabled(), "Plugin hook " + getClass().getSimpleName() + " is not enabled"); - } + + void setup(); + + boolean isEnabled(); + + default void checkEnabledState() { + Preconditions.checkState(isEnabled(), "Plugin hook " + getClass().getSimpleName() + " is not enabled"); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/hook/VaultEconomyHook.java b/plugin/src/main/java/me/filoghost/chestcommands/hook/VaultEconomyHook.java index ab6637c..b9bc36a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/hook/VaultEconomyHook.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/hook/VaultEconomyHook.java @@ -14,72 +14,72 @@ import org.bukkit.plugin.RegisteredServiceProvider; public enum VaultEconomyHook implements PluginHook { - INSTANCE; - - private Economy economy; + INSTANCE; + + private Economy economy; - @Override - public void setup() { - economy = null; - - if (Bukkit.getPluginManager().getPlugin("Vault") == null) { - return; - } - - RegisteredServiceProvider economyServiceProvider = Bukkit.getServicesManager().getRegistration(Economy.class); - if (economyServiceProvider == null) { - return; - } - - economy = economyServiceProvider.getProvider(); - } + @Override + public void setup() { + economy = null; + + if (Bukkit.getPluginManager().getPlugin("Vault") == null) { + return; + } + + RegisteredServiceProvider economyServiceProvider = Bukkit.getServicesManager().getRegistration(Economy.class); + if (economyServiceProvider == null) { + return; + } + + economy = economyServiceProvider.getProvider(); + } - @Override - public boolean isEnabled() { - return economy != null; - } + @Override + public boolean isEnabled() { + return economy != null; + } - public static double getMoney(Player player) { - INSTANCE.checkEnabledState(); - return INSTANCE.economy.getBalance(player, player.getWorld().getName()); - } + public static double getMoney(Player player) { + INSTANCE.checkEnabledState(); + return INSTANCE.economy.getBalance(player, player.getWorld().getName()); + } - public static boolean hasMoney(Player player, double minimum) { - INSTANCE.checkEnabledState(); - checkPositiveAmount(minimum); + public static boolean hasMoney(Player player, double minimum) { + INSTANCE.checkEnabledState(); + checkPositiveAmount(minimum); - double balance = INSTANCE.economy.getBalance(player, player.getWorld().getName()); - return balance >= minimum; - } + double balance = INSTANCE.economy.getBalance(player, player.getWorld().getName()); + return balance >= minimum; + } - /** - * @return true if the operation was successful. - */ - public static boolean takeMoney(Player player, double amount) { - INSTANCE.checkEnabledState(); - checkPositiveAmount(amount); + /** + * @return true if the operation was successful. + */ + public static boolean takeMoney(Player player, double amount) { + INSTANCE.checkEnabledState(); + checkPositiveAmount(amount); - EconomyResponse response = INSTANCE.economy.withdrawPlayer(player, player.getWorld().getName(), amount); - return response.transactionSuccess(); - } + EconomyResponse response = INSTANCE.economy.withdrawPlayer(player, player.getWorld().getName(), amount); + return response.transactionSuccess(); + } - public static boolean giveMoney(Player player, double amount) { - INSTANCE.checkEnabledState(); - checkPositiveAmount(amount); + public static boolean giveMoney(Player player, double amount) { + INSTANCE.checkEnabledState(); + checkPositiveAmount(amount); - EconomyResponse response = INSTANCE.economy.depositPlayer(player, player.getWorld().getName(), amount); - return response.transactionSuccess(); - } - - private static void checkPositiveAmount(double amount) { - Preconditions.checkArgument(amount >= 0.0, "amount cannot be negative"); - } + EconomyResponse response = INSTANCE.economy.depositPlayer(player, player.getWorld().getName(), amount); + return response.transactionSuccess(); + } + + private static void checkPositiveAmount(double amount) { + Preconditions.checkArgument(amount >= 0.0, "amount cannot be negative"); + } - public static String formatMoney(double amount) { - if (INSTANCE.economy != null) { - return INSTANCE.economy.format(amount); - } else { - return Double.toString(amount); - } - } + public static String formatMoney(double amount) { + if (INSTANCE.economy != null) { + return INSTANCE.economy.format(amount); + } else { + return Double.toString(amount); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/APIConfigurableIcon.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/APIConfigurableIcon.java index 8bf5295..61cd6b1 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/APIConfigurableIcon.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/APIConfigurableIcon.java @@ -11,20 +11,20 @@ import org.bukkit.Material; public class APIConfigurableIcon extends BaseConfigurableIcon implements ConfigurableIcon { - private ClickHandler clickHandler; + private ClickHandler clickHandler; - public APIConfigurableIcon(Material material) { - super(material); - } + public APIConfigurableIcon(Material material) { + super(material); + } - @Override - public void setClickHandler(ClickHandler clickHandler) { - this.clickHandler = clickHandler; - } + @Override + public void setClickHandler(ClickHandler clickHandler) { + this.clickHandler = clickHandler; + } - @Override - public ClickHandler getClickHandler() { - return clickHandler; - } + @Override + public ClickHandler getClickHandler() { + return clickHandler; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/APIStaticIcon.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/APIStaticIcon.java index ab51e80..76c31cb 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/APIStaticIcon.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/APIStaticIcon.java @@ -13,38 +13,38 @@ import org.bukkit.inventory.ItemStack; public class APIStaticIcon implements StaticIcon { - private ItemStack itemStack; - private ClickHandler clickHandler; + private ItemStack itemStack; + private ClickHandler clickHandler; - public APIStaticIcon(ItemStack itemStack) { - Preconditions.notNull(itemStack, "itemStack"); - this.itemStack = itemStack; - } + public APIStaticIcon(ItemStack itemStack) { + Preconditions.notNull(itemStack, "itemStack"); + this.itemStack = itemStack; + } - @Override - public ItemStack getItemStack() { - return itemStack; - } + @Override + public ItemStack getItemStack() { + return itemStack; + } - @Override - public void setItemStack(ItemStack itemStack) { - Preconditions.notNull(itemStack, "itemStack"); - this.itemStack = itemStack; - } + @Override + public void setItemStack(ItemStack itemStack) { + Preconditions.notNull(itemStack, "itemStack"); + this.itemStack = itemStack; + } - @Override - public ClickHandler getClickHandler() { - return clickHandler; - } + @Override + public ClickHandler getClickHandler() { + return clickHandler; + } - @Override - public void setClickHandler(ClickHandler clickHandler) { - this.clickHandler = clickHandler; - } + @Override + public void setClickHandler(ClickHandler clickHandler) { + this.clickHandler = clickHandler; + } - @Override - public ItemStack render(Player viewer) { - return itemStack; - } + @Override + public ItemStack render(Player viewer) { + return itemStack; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/BaseConfigurableIcon.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/BaseConfigurableIcon.java index c4373e1..f72b74f 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/BaseConfigurableIcon.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/BaseConfigurableIcon.java @@ -5,6 +5,11 @@ */ package me.filoghost.chestcommands.icon; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import me.filoghost.chestcommands.api.Icon; import me.filoghost.chestcommands.placeholder.PlaceholderString; import me.filoghost.chestcommands.placeholder.PlaceholderStringList; @@ -28,298 +33,292 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.SkullMeta; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public abstract class BaseConfigurableIcon implements Icon { - private Material material; - private int amount; - private short durability; + private Material material; + private int amount; + private short durability; - private String nbtData; - private PlaceholderString name; - private PlaceholderStringList lore; - private Map enchantments; - private Color leatherColor; - private PlaceholderString skullOwner; - private DyeColor bannerColor; - private List bannerPatterns; - private boolean placeholdersEnabled; - - protected ItemStack cachedRendering; // Cache the rendered item when possible and if state hasn't changed + private String nbtData; + private PlaceholderString name; + private PlaceholderStringList lore; + private Map enchantments; + private Color leatherColor; + private PlaceholderString skullOwner; + private DyeColor bannerColor; + private List bannerPatterns; + private boolean placeholdersEnabled; - public BaseConfigurableIcon(Material material) { - this.material = material; - this.amount = 1; - } + protected ItemStack cachedRendering; // Cache the rendered item when possible and if state hasn't changed - protected boolean shouldCacheRendering() { - if (placeholdersEnabled && hasDynamicPlaceholders()) { - return false; - } else { - return true; - } - } + public BaseConfigurableIcon(Material material) { + this.material = material; + this.amount = 1; + } - private boolean hasDynamicPlaceholders() { - return (name != null && name.hasDynamicPlaceholders()) - || (lore != null && lore.hasDynamicPlaceholders()) - || (skullOwner != null && skullOwner.hasDynamicPlaceholders()); - } + protected boolean shouldCacheRendering() { + if (placeholdersEnabled && hasDynamicPlaceholders()) { + return false; + } else { + return true; + } + } - public void setMaterial(Material material) { - this.material = material; - cachedRendering = null; - } + private boolean hasDynamicPlaceholders() { + return (name != null && name.hasDynamicPlaceholders()) + || (lore != null && lore.hasDynamicPlaceholders()) + || (skullOwner != null && skullOwner.hasDynamicPlaceholders()); + } - public Material getMaterial() { - return material; - } + public void setMaterial(Material material) { + this.material = material; + cachedRendering = null; + } - public void setAmount(int amount) { - Preconditions.checkArgument(amount > 0, "amount must be greater than 0"); - this.amount = Math.min(amount, 127); - cachedRendering = null; - } + public Material getMaterial() { + return material; + } - public int getAmount() { - return amount; - } + public void setAmount(int amount) { + Preconditions.checkArgument(amount > 0, "amount must be greater than 0"); + this.amount = Math.min(amount, 127); + cachedRendering = null; + } - public void setDurability(short durability) { - Preconditions.checkArgument(durability >= 0, "durability must be 0 or greater"); - this.durability = durability; - cachedRendering = null; - } + public int getAmount() { + return amount; + } - public short getDurability() { - return durability; - } + public void setDurability(short durability) { + Preconditions.checkArgument(durability >= 0, "durability must be 0 or greater"); + this.durability = durability; + cachedRendering = null; + } - public void setNBTData(String nbtData) { - if (nbtData != null) { - try { - MojangsonParser.parse(nbtData); - } catch (MojangsonParseException e) { - throw new IllegalArgumentException("invalid nbtData", e); - } - } - this.nbtData = nbtData; - cachedRendering = null; - } + public short getDurability() { + return durability; + } - public String getNBTData() { - return nbtData; - } + public void setNBTData(String nbtData) { + if (nbtData != null) { + try { + MojangsonParser.parse(nbtData); + } catch (MojangsonParseException e) { + throw new IllegalArgumentException("invalid nbtData", e); + } + } + this.nbtData = nbtData; + cachedRendering = null; + } - public void setName(String name) { - this.name = PlaceholderString.of(name); - cachedRendering = null; - } + public String getNBTData() { + return nbtData; + } - public String getName() { - if (name != null) { - return name.getOriginalValue(); - } else { - return null; - } - } + public void setName(String name) { + this.name = PlaceholderString.of(name); + cachedRendering = null; + } - public void setLore(String... lore) { - if (lore != null) { - setLore(Arrays.asList(lore)); - } - } + public String getName() { + if (name != null) { + return name.getOriginalValue(); + } else { + return null; + } + } - public void setLore(List lore) { - if (lore != null) { - this.lore = new PlaceholderStringList(CollectionUtils.replaceNulls(lore, "")); - } else { - this.lore = null; - } - cachedRendering = null; - } + public void setLore(String... lore) { + if (lore != null) { + setLore(Arrays.asList(lore)); + } + } - public List getLore() { - if (lore != null) { - return new ArrayList<>(lore.getOriginalValue()); - } else { - return null; - } - } + public void setLore(List lore) { + if (lore != null) { + this.lore = new PlaceholderStringList(CollectionUtils.replaceNulls(lore, "")); + } else { + this.lore = null; + } + cachedRendering = null; + } - public void setEnchantments(Map enchantments) { - this.enchantments = CollectionUtils.copy(enchantments); - cachedRendering = null; - } + public List getLore() { + if (lore != null) { + return new ArrayList<>(lore.getOriginalValue()); + } else { + return null; + } + } - public Map getEnchantments() { - return CollectionUtils.copy(enchantments); - } + public void setEnchantments(Map enchantments) { + this.enchantments = CollectionUtils.copy(enchantments); + cachedRendering = null; + } - public void addEnchantment(Enchantment enchantment) { - addEnchantment(enchantment, 1); - } + public Map getEnchantments() { + return CollectionUtils.copy(enchantments); + } - public void addEnchantment(Enchantment enchantment, Integer level) { - if (enchantments == null) { - enchantments = new HashMap<>(); - } - enchantments.put(enchantment, level); - cachedRendering = null; - } + public void addEnchantment(Enchantment enchantment) { + addEnchantment(enchantment, 1); + } - public void removeEnchantment(Enchantment enchantment) { - if (enchantments == null) { - return; - } - enchantments.remove(enchantment); - cachedRendering = null; - } + public void addEnchantment(Enchantment enchantment, Integer level) { + if (enchantments == null) { + enchantments = new HashMap<>(); + } + enchantments.put(enchantment, level); + cachedRendering = null; + } - public Color getLeatherColor() { - return leatherColor; - } + public void removeEnchantment(Enchantment enchantment) { + if (enchantments == null) { + return; + } + enchantments.remove(enchantment); + cachedRendering = null; + } - public void setLeatherColor(Color leatherColor) { - this.leatherColor = leatherColor; - cachedRendering = null; - } + public Color getLeatherColor() { + return leatherColor; + } - public String getSkullOwner() { - if (skullOwner != null) { - return skullOwner.getOriginalValue(); - } else { - return null; - } - } + public void setLeatherColor(Color leatherColor) { + this.leatherColor = leatherColor; + cachedRendering = null; + } - public void setSkullOwner(String skullOwner) { - this.skullOwner = PlaceholderString.of(skullOwner); - cachedRendering = null; - } + public String getSkullOwner() { + if (skullOwner != null) { + return skullOwner.getOriginalValue(); + } else { + return null; + } + } - public DyeColor getBannerColor() { - return bannerColor; - } + public void setSkullOwner(String skullOwner) { + this.skullOwner = PlaceholderString.of(skullOwner); + cachedRendering = null; + } - public void setBannerColor(DyeColor bannerColor) { - this.bannerColor = bannerColor; - cachedRendering = null; - } + public DyeColor getBannerColor() { + return bannerColor; + } - public List getBannerPatterns() { - return CollectionUtils.copy(bannerPatterns); - } + public void setBannerColor(DyeColor bannerColor) { + this.bannerColor = bannerColor; + cachedRendering = null; + } - public void setBannerPatterns(List bannerPatterns) { - this.bannerPatterns = CollectionUtils.copy(bannerPatterns); - cachedRendering = null; - } + public List getBannerPatterns() { + return CollectionUtils.copy(bannerPatterns); + } - public void setPlaceholdersEnabled(boolean placeholdersEnabled) { - this.placeholdersEnabled = placeholdersEnabled; - cachedRendering = null; - } + public void setBannerPatterns(List bannerPatterns) { + this.bannerPatterns = CollectionUtils.copy(bannerPatterns); + cachedRendering = null; + } - public String renderName(Player viewer) { - if (name == null) { - return null; - } - if (!placeholdersEnabled) { - return name.getOriginalValue(); - } + public void setPlaceholdersEnabled(boolean placeholdersEnabled) { + this.placeholdersEnabled = placeholdersEnabled; + cachedRendering = null; + } - String name = this.name.getValue(viewer); + public String renderName(Player viewer) { + if (name == null) { + return null; + } + if (!placeholdersEnabled) { + return name.getOriginalValue(); + } - if (name.isEmpty()) { - // Add a color to display the name empty - return ChatColor.WHITE.toString(); - } else { - return name; - } - } + String name = this.name.getValue(viewer); - public List renderLore(Player viewer) { - if (lore == null) { - return null; - } - if (!placeholdersEnabled) { - return lore.getOriginalValue(); - } + if (name.isEmpty()) { + // Add a color to display the name empty + return ChatColor.WHITE.toString(); + } else { + return name; + } + } - return lore.getValue(viewer); - } + public List renderLore(Player viewer) { + if (lore == null) { + return null; + } + if (!placeholdersEnabled) { + return lore.getOriginalValue(); + } - @Override - @SuppressWarnings("deprecation") - public ItemStack render(Player viewer) { - if (shouldCacheRendering() && cachedRendering != null) { - // Performance: return a cached item - return cachedRendering; - } + return lore.getValue(viewer); + } - ItemStack itemStack = new ItemStack(material, amount, durability); + @Override + @SuppressWarnings("deprecation") + public ItemStack render(Player viewer) { + if (shouldCacheRendering() && cachedRendering != null) { + // Performance: return a cached item + return cachedRendering; + } - // First try to apply NBT data - if (nbtData != null) { - try { - // Note: this method should not throw any exception. It should log directly to the console - Bukkit.getUnsafe().modifyItemStack(itemStack, nbtData); - } catch (Throwable t) { - this.nbtData = null; - Log.warning("Could not apply NBT data to an item.", t); - } - } + ItemStack itemStack = new ItemStack(material, amount, durability); - // Then apply data from config nodes, overwriting NBT data if there are conflicting values - ItemMeta itemMeta = itemStack.getItemMeta(); + // First try to apply NBT data + if (nbtData != null) { + try { + // Note: this method should not throw any exception. It should log directly to the console + Bukkit.getUnsafe().modifyItemStack(itemStack, nbtData); + } catch (Throwable t) { + this.nbtData = null; + Log.warning("Could not apply NBT data to an item.", t); + } + } - if (itemMeta != null) { - itemMeta.setDisplayName(renderName(viewer)); - itemMeta.setLore(renderLore(viewer)); + // Then apply data from config nodes, overwriting NBT data if there are conflicting values + ItemMeta itemMeta = itemStack.getItemMeta(); - if (leatherColor != null && itemMeta instanceof LeatherArmorMeta) { - ((LeatherArmorMeta) itemMeta).setColor(leatherColor); - } + if (itemMeta != null) { + itemMeta.setDisplayName(renderName(viewer)); + itemMeta.setLore(renderLore(viewer)); - if (skullOwner != null && itemMeta instanceof SkullMeta) { - String skullOwner = this.skullOwner.getValue(viewer); - ((SkullMeta) itemMeta).setOwner(skullOwner); - } + if (leatherColor != null && itemMeta instanceof LeatherArmorMeta) { + ((LeatherArmorMeta) itemMeta).setColor(leatherColor); + } - if (itemMeta instanceof BannerMeta) { - BannerMeta bannerMeta = (BannerMeta) itemMeta; - if (bannerColor != null) { - bannerMeta.setBaseColor(bannerColor); - } - if (bannerPatterns != null) { - ((BannerMeta) itemMeta).setPatterns(bannerPatterns); - } - } + if (skullOwner != null && itemMeta instanceof SkullMeta) { + String skullOwner = this.skullOwner.getValue(viewer); + ((SkullMeta) itemMeta).setOwner(skullOwner); + } - // Hide all text details (damage, enchantments, potions, etc,) - if (itemMeta.getItemFlags().isEmpty()) { - itemMeta.addItemFlags(ItemFlag.values()); - } + if (itemMeta instanceof BannerMeta) { + BannerMeta bannerMeta = (BannerMeta) itemMeta; + if (bannerColor != null) { + bannerMeta.setBaseColor(bannerColor); + } + if (bannerPatterns != null) { + ((BannerMeta) itemMeta).setPatterns(bannerPatterns); + } + } - itemStack.setItemMeta(itemMeta); - } + // Hide all text details (damage, enchantments, potions, etc,) + if (itemMeta.getItemFlags().isEmpty()) { + itemMeta.addItemFlags(ItemFlag.values()); + } - if (enchantments != null) { - enchantments.forEach(itemStack::addUnsafeEnchantment); - } + itemStack.setItemMeta(itemMeta); + } + + if (enchantments != null) { + enchantments.forEach(itemStack::addUnsafeEnchantment); + } - if (shouldCacheRendering()) { - cachedRendering = itemStack; - } + if (shouldCacheRendering()) { + cachedRendering = itemStack; + } - return itemStack; - } + return itemStack; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/IconPermission.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/IconPermission.java index fa02c66..b0082f6 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/IconPermission.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/IconPermission.java @@ -9,47 +9,47 @@ import me.filoghost.fcommons.Strings; import org.bukkit.entity.Player; public class IconPermission { - - private final String permission; - private final boolean negated; + + private final String permission; + private final boolean negated; - public IconPermission(String permission) { - if (permission != null) { - permission = permission.trim(); - } - - if (Strings.isEmpty(permission)) { - this.permission = null; - negated = false; - } else { - if (permission.startsWith("-")) { - this.permission = permission.substring(1); - negated = true; - } else { - this.permission = permission; - negated = false; - } - } - } - - private boolean hasPermission(Player player) { - if (isEmpty()) { - return true; - } + public IconPermission(String permission) { + if (permission != null) { + permission = permission.trim(); + } + + if (Strings.isEmpty(permission)) { + this.permission = null; + negated = false; + } else { + if (permission.startsWith("-")) { + this.permission = permission.substring(1); + negated = true; + } else { + this.permission = permission; + negated = false; + } + } + } + + private boolean hasPermission(Player player) { + if (isEmpty()) { + return true; + } - if (negated) { - return !player.hasPermission(permission); - } else { - return player.hasPermission(permission); - } - } + if (negated) { + return !player.hasPermission(permission); + } else { + return player.hasPermission(permission); + } + } - public boolean isEmpty() { - return this.permission == null; - } + public boolean isEmpty() { + return this.permission == null; + } - public static boolean hasPermission(Player player, IconPermission permission) { - return permission == null || permission.hasPermission(player); - } + public static boolean hasPermission(Player player, IconPermission permission) { + return permission == null || permission.hasPermission(player); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/InternalConfigurableIcon.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/InternalConfigurableIcon.java index 38d4c89..02b4bdf 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/InternalConfigurableIcon.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/InternalConfigurableIcon.java @@ -6,6 +6,7 @@ package me.filoghost.chestcommands.icon; import com.google.common.collect.ImmutableList; +import java.util.List; import me.filoghost.chestcommands.action.Action; import me.filoghost.chestcommands.action.OpenMenuAction; import me.filoghost.chestcommands.api.ClickResult; @@ -23,170 +24,168 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import java.util.List; - public class InternalConfigurableIcon extends BaseConfigurableIcon implements RefreshableIcon { - private IconPermission viewPermission; - private IconPermission clickPermission; - private String noClickPermissionMessage; + private IconPermission viewPermission; + private IconPermission clickPermission; + private String noClickPermissionMessage; - private RequiredMoney requiredMoney; - private RequiredExpLevel requiredExpLevel; - private RequiredItems requiredItems; + private RequiredMoney requiredMoney; + private RequiredExpLevel requiredExpLevel; + private RequiredItems requiredItems; - private ImmutableList clickActions; - private ClickResult clickResult; + private ImmutableList clickActions; + private ClickResult clickResult; - public InternalConfigurableIcon(Material material) { - super(material); - setPlaceholdersEnabled(true); - this.clickResult = ClickResult.CLOSE; - } + public InternalConfigurableIcon(Material material) { + super(material); + setPlaceholdersEnabled(true); + this.clickResult = ClickResult.CLOSE; + } - public boolean canViewIcon(Player player) { - return IconPermission.hasPermission(player, viewPermission); - } - - public boolean hasViewPermission() { - return viewPermission != null && !viewPermission.isEmpty(); - } + public boolean canViewIcon(Player player) { + return IconPermission.hasPermission(player, viewPermission); + } + + public boolean hasViewPermission() { + return viewPermission != null && !viewPermission.isEmpty(); + } - public void setClickPermission(String permission) { - this.clickPermission = new IconPermission(permission); - } - - public void setNoClickPermissionMessage(String noClickPermissionMessage) { - this.noClickPermissionMessage = noClickPermissionMessage; - } - - public void setViewPermission(String viewPermission) { - this.viewPermission = new IconPermission(viewPermission); - } + public void setClickPermission(String permission) { + this.clickPermission = new IconPermission(permission); + } + + public void setNoClickPermissionMessage(String noClickPermissionMessage) { + this.noClickPermissionMessage = noClickPermissionMessage; + } + + public void setViewPermission(String viewPermission) { + this.viewPermission = new IconPermission(viewPermission); + } - public void setRequiredMoney(double requiredMoney) { - if (requiredMoney > 0.0) { - this.requiredMoney = new RequiredMoney(requiredMoney); - } else { - this.requiredMoney = null; - } - } + public void setRequiredMoney(double requiredMoney) { + if (requiredMoney > 0.0) { + this.requiredMoney = new RequiredMoney(requiredMoney); + } else { + this.requiredMoney = null; + } + } - public void setRequiredExpLevel(int requiredLevels) { - if (requiredLevels > 0) { - this.requiredExpLevel = new RequiredExpLevel(requiredLevels); - } else { - this.requiredExpLevel = null; - } - } + public void setRequiredExpLevel(int requiredLevels) { + if (requiredLevels > 0) { + this.requiredExpLevel = new RequiredExpLevel(requiredLevels); + } else { + this.requiredExpLevel = null; + } + } - public void setRequiredItems(List requiredItems) { - if (requiredItems != null) { - this.requiredItems = new RequiredItems(requiredItems); - } else { - this.requiredItems = null; - } - } + public void setRequiredItems(List requiredItems) { + if (requiredItems != null) { + this.requiredItems = new RequiredItems(requiredItems); + } else { + this.requiredItems = null; + } + } - public void setClickActions(List clickActions) { - this.clickActions = CollectionUtils.immutableCopy(clickActions); - } - - - @Override - public ItemStack render(Player viewer) { - if (canViewIcon(viewer)) { - return super.render(viewer); - } else { - return null; - } - } + public void setClickActions(List clickActions) { + this.clickActions = CollectionUtils.immutableCopy(clickActions); + } + + + @Override + public ItemStack render(Player viewer) { + if (canViewIcon(viewer)) { + return super.render(viewer); + } else { + return null; + } + } - @Override - protected boolean shouldCacheRendering() { - return super.shouldCacheRendering() && !hasViewPermission(); - } + @Override + protected boolean shouldCacheRendering() { + return super.shouldCacheRendering() && !hasViewPermission(); + } - public void setClickResult(ClickResult clickResult) { - Preconditions.notNull(clickResult, "clickResult"); - this.clickResult = clickResult; - } + public void setClickResult(ClickResult clickResult) { + Preconditions.notNull(clickResult, "clickResult"); + this.clickResult = clickResult; + } - @Override - public ClickResult onClick(MenuView menuView, Player player) { - if (!IconPermission.hasPermission(player, viewPermission)) { - return ClickResult.KEEP_OPEN; - } + @Override + public ClickResult onClick(MenuView menuView, Player player) { + if (!IconPermission.hasPermission(player, viewPermission)) { + return ClickResult.KEEP_OPEN; + } - if (!IconPermission.hasPermission(player, clickPermission)) { - if (noClickPermissionMessage != null) { - player.sendMessage(noClickPermissionMessage); - } else { - player.sendMessage(Lang.default_no_icon_permission); - } - return clickResult; - } + if (!IconPermission.hasPermission(player, clickPermission)) { + if (noClickPermissionMessage != null) { + player.sendMessage(noClickPermissionMessage); + } else { + player.sendMessage(Lang.default_no_icon_permission); + } + return clickResult; + } - // Check all the requirements - Requirement[] requirements = {requiredMoney, requiredExpLevel, requiredItems}; - boolean hasAllRequirements = Requirement.hasAllCosts(player, requirements); - if (!hasAllRequirements) { - return clickResult; - } + // Check all the requirements + Requirement[] requirements = {requiredMoney, requiredExpLevel, requiredItems}; + boolean hasAllRequirements = Requirement.hasAllCosts(player, requirements); + if (!hasAllRequirements) { + return clickResult; + } - // If all requirements are satisfied, take their cost - boolean takenAllCosts = Requirement.takeAllCosts(player, requirements); - if (!takenAllCosts) { - return clickResult; - } - - boolean hasOpenMenuAction = false; - - if (clickActions != null) { - for (Action action : clickActions) { - action.execute(player); - - if (action instanceof OpenMenuAction) { - hasOpenMenuAction = true; - } - } - } + // If all requirements are satisfied, take their cost + boolean takenAllCosts = Requirement.takeAllCosts(player, requirements); + if (!takenAllCosts) { + return clickResult; + } + + boolean hasOpenMenuAction = false; + + if (clickActions != null) { + for (Action action : clickActions) { + action.execute(player); + + if (action instanceof OpenMenuAction) { + hasOpenMenuAction = true; + } + } + } - // Update the menu after taking requirement costs and executing all actions - menuView.refresh(); - - // Force menu to stay open if actions open another menu - if (hasOpenMenuAction) { - return ClickResult.KEEP_OPEN; - } else { - return clickResult; - } - } + // Update the menu after taking requirement costs and executing all actions + menuView.refresh(); + + // Force menu to stay open if actions open another menu + if (hasOpenMenuAction) { + return ClickResult.KEEP_OPEN; + } else { + return clickResult; + } + } - @Override - public ItemStack updateRendering(Player viewer, ItemStack currentRendering) { - if (currentRendering != null && shouldCacheRendering()) { - // Internal icons do not change, no need to update if the item is already rendered - return currentRendering; - } + @Override + public ItemStack updateRendering(Player viewer, ItemStack currentRendering) { + if (currentRendering != null && shouldCacheRendering()) { + // Internal icons do not change, no need to update if the item is already rendered + return currentRendering; + } - if (!canViewIcon(viewer)) { - // Hide the current item - return null; - } + if (!canViewIcon(viewer)) { + // Hide the current item + return null; + } - if (currentRendering == null) { - // Render item normally - return render(viewer); - } else { - // Internal icons are loaded and then never change, we can safely update only name and lore (for performance) - ItemMeta meta = currentRendering.getItemMeta(); - meta.setDisplayName(renderName(viewer)); - meta.setLore(renderLore(viewer)); - currentRendering.setItemMeta(meta); - return currentRendering; - } - } + if (currentRendering == null) { + // Render item normally + return render(viewer); + } else { + // Internal icons are loaded and then never change, we can safely update only name and lore (for performance) + ItemMeta meta = currentRendering.getItemMeta(); + meta.setDisplayName(renderName(viewer)); + meta.setLore(renderLore(viewer)); + currentRendering.setItemMeta(meta); + return currentRendering; + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/RefreshableIcon.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/RefreshableIcon.java index 81d8a04..22d615a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/RefreshableIcon.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/RefreshableIcon.java @@ -9,7 +9,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public interface RefreshableIcon { - - ItemStack updateRendering(Player viewer, ItemStack currentRendering); - + + ItemStack updateRendering(Player viewer, ItemStack currentRendering); + } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/RequiredExpLevel.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/RequiredExpLevel.java index e2b2d0c..e774d63 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/RequiredExpLevel.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/RequiredExpLevel.java @@ -11,32 +11,32 @@ import org.bukkit.entity.Player; public class RequiredExpLevel implements Requirement { - private final int levels; - - public RequiredExpLevel(int levels) { - Preconditions.checkArgument(levels > 0, "levels must be positive"); - this.levels = levels; - } + private final int levels; - @Override - public boolean hasCost(Player player) { - if (player.getLevel() < levels) { - player.sendMessage(Lang.no_exp.replace("{levels}", Integer.toString(levels))); - return false; - } - - return true; - } + public RequiredExpLevel(int levels) { + Preconditions.checkArgument(levels > 0, "levels must be positive"); + this.levels = levels; + } - @Override - public boolean takeCost(Player player) { - int newLevel = player.getLevel() - levels; - if (newLevel < 0) { - newLevel = 0; - } - - player.setLevel(newLevel); - return true; - } + @Override + public boolean hasCost(Player player) { + if (player.getLevel() < levels) { + player.sendMessage(Lang.no_exp.replace("{levels}", Integer.toString(levels))); + return false; + } + + return true; + } + + @Override + public boolean takeCost(Player player) { + int newLevel = player.getLevel() - levels; + if (newLevel < 0) { + newLevel = 0; + } + + player.setLevel(newLevel); + return true; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/RequiredMoney.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/RequiredMoney.java index 7a60e5f..6750368 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/RequiredMoney.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/RequiredMoney.java @@ -13,39 +13,39 @@ import org.bukkit.entity.Player; public class RequiredMoney implements Requirement { - private final double moneyAmount; - - public RequiredMoney(double moneyAmount) { - Preconditions.checkArgument(moneyAmount > 0.0, "money amount must be positive"); - this.moneyAmount = moneyAmount; - } + private final double moneyAmount; - @Override - public boolean hasCost(Player player) { - if (!VaultEconomyHook.INSTANCE.isEnabled()) { - player.sendMessage(Errors.User.configurationError( - "the item has a price, but Vault with a compatible economy plugin was not found. " - + "For security, the action has been blocked")); - return false; - } + public RequiredMoney(double moneyAmount) { + Preconditions.checkArgument(moneyAmount > 0.0, "money amount must be positive"); + this.moneyAmount = moneyAmount; + } - if (!VaultEconomyHook.hasMoney(player, moneyAmount)) { - player.sendMessage(Lang.no_money.replace("{money}", VaultEconomyHook.formatMoney(moneyAmount))); - return false; - } - - return true; - } + @Override + public boolean hasCost(Player player) { + if (!VaultEconomyHook.INSTANCE.isEnabled()) { + player.sendMessage(Errors.User.configurationError( + "the item has a price, but Vault with a compatible economy plugin was not found. " + + "For security, the action has been blocked")); + return false; + } - @Override - public boolean takeCost(Player player) { - boolean success = VaultEconomyHook.takeMoney(player, moneyAmount); - - if (!success) { - player.sendMessage(Errors.User.configurationError("a money transaction couldn't be executed")); - } - - return success; - } + if (!VaultEconomyHook.hasMoney(player, moneyAmount)) { + player.sendMessage(Lang.no_money.replace("{money}", VaultEconomyHook.formatMoney(moneyAmount))); + return false; + } + + return true; + } + + @Override + public boolean takeCost(Player player) { + boolean success = VaultEconomyHook.takeMoney(player, moneyAmount); + + if (!success) { + player.sendMessage(Errors.User.configurationError("a money transaction couldn't be executed")); + } + + return success; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/Requirement.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/Requirement.java index 1915e16..dc64695 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/Requirement.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/Requirement.java @@ -8,32 +8,32 @@ package me.filoghost.chestcommands.icon.requirement; import org.bukkit.entity.Player; public interface Requirement { - - boolean hasCost(Player player); - - boolean takeCost(Player player); - - static boolean hasAllCosts(Player player, Requirement... requirements) { - for (Requirement requirement : requirements) { - if (requirement != null && !requirement.hasCost(player)) { - return false; - } - } - - return true; - } - - static boolean takeAllCosts(Player player, Requirement... requirements) { - for (Requirement requirement : requirements) { - if (requirement != null) { - boolean success = requirement.takeCost(player); - if (!success) { - return false; - } - } - } - - return true; - } + + boolean hasCost(Player player); + + boolean takeCost(Player player); + + static boolean hasAllCosts(Player player, Requirement... requirements) { + for (Requirement requirement : requirements) { + if (requirement != null && !requirement.hasCost(player)) { + return false; + } + } + + return true; + } + + static boolean takeAllCosts(Player player, Requirement... requirements) { + for (Requirement requirement : requirements) { + if (requirement != null) { + boolean success = requirement.takeCost(player); + if (!success) { + return false; + } + } + } + + return true; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/InventoryTakeHelper.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/InventoryTakeHelper.java index 34bf770..b9a5c36 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/InventoryTakeHelper.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/InventoryTakeHelper.java @@ -5,80 +5,79 @@ */ package me.filoghost.chestcommands.icon.requirement.item; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; import me.filoghost.fcommons.MaterialsHelper; import me.filoghost.fcommons.Preconditions; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - public class InventoryTakeHelper { - private final PlayerInventory inventory; - private final List remainingItems; + private final PlayerInventory inventory; + private final List remainingItems; - private boolean success; + private boolean success; - public InventoryTakeHelper(PlayerInventory inventory) { - this.inventory = inventory; - this.remainingItems = new ArrayList<>(); + public InventoryTakeHelper(PlayerInventory inventory) { + this.inventory = inventory; + this.remainingItems = new ArrayList<>(); - for (int slotIndex = 0; slotIndex < inventory.getSize(); slotIndex++) { - ItemStack item = inventory.getItem(slotIndex); - if (item != null && !MaterialsHelper.isAir(item.getType())) { - remainingItems.add(new RemainingItem(slotIndex, item)); - } - } - } + for (int slotIndex = 0; slotIndex < inventory.getSize(); slotIndex++) { + ItemStack item = inventory.getItem(slotIndex); + if (item != null && !MaterialsHelper.isAir(item.getType())) { + remainingItems.add(new RemainingItem(slotIndex, item)); + } + } + } - public boolean prepareTakeItems(List requiredItems) { - List missingItems = new ArrayList<>(); + public boolean prepareTakeItems(List requiredItems) { + List missingItems = new ArrayList<>(); - // Sort required items: check required items with a restrictive durability first - List sortedRequiredItems = requiredItems.stream() - .sorted(Comparator.comparing(RequiredItem::hasRestrictiveDurability).reversed()) - .collect(Collectors.toList()); + // Sort required items: check required items with a restrictive durability first + List sortedRequiredItems = requiredItems.stream() + .sorted(Comparator.comparing(RequiredItem::hasRestrictiveDurability).reversed()) + .collect(Collectors.toList()); - for (RequiredItem requiredItem : sortedRequiredItems) { - int remainingRequiredAmount = requiredItem.getAmount(); + for (RequiredItem requiredItem : sortedRequiredItems) { + int remainingRequiredAmount = requiredItem.getAmount(); - for (RemainingItem remainingItem : remainingItems) { - if (remainingItem.getAmount() > 0 && requiredItem.isMatchingType(remainingItem)) { - int takenAmount = remainingItem.subtract(remainingRequiredAmount); - remainingRequiredAmount -= takenAmount; - if (remainingRequiredAmount == 0) { - break; - } - } - } + for (RemainingItem remainingItem : remainingItems) { + if (remainingItem.getAmount() > 0 && requiredItem.isMatchingType(remainingItem)) { + int takenAmount = remainingItem.subtract(remainingRequiredAmount); + remainingRequiredAmount -= takenAmount; + if (remainingRequiredAmount == 0) { + break; + } + } + } - // Couldn't take the required amount of an item - if (remainingRequiredAmount > 0) { - missingItems.add(requiredItem); - } - } + // Couldn't take the required amount of an item + if (remainingRequiredAmount > 0) { + missingItems.add(requiredItem); + } + } - success = missingItems.isEmpty(); - return success; - } + success = missingItems.isEmpty(); + return success; + } - public void applyTakeItems() { - Preconditions.checkState(success, "items take preparation was not run or successful"); + public void applyTakeItems() { + Preconditions.checkState(success, "items take preparation was not run or successful"); - for (RemainingItem remainingItem : remainingItems) { - int slotIndex = remainingItem.getSlotIndex(); - ItemStack inventoryItem = inventory.getItem(slotIndex); - if (remainingItem.getAmount() != inventoryItem.getAmount()) { - if (remainingItem.getAmount() > 0) { - inventoryItem.setAmount(remainingItem.getAmount()); - } else { - inventory.setItem(slotIndex, null); - } - } - } - } + for (RemainingItem remainingItem : remainingItems) { + int slotIndex = remainingItem.getSlotIndex(); + ItemStack inventoryItem = inventory.getItem(slotIndex); + if (remainingItem.getAmount() != inventoryItem.getAmount()) { + if (remainingItem.getAmount() > 0) { + inventoryItem.setAmount(remainingItem.getAmount()); + } else { + inventory.setItem(slotIndex, null); + } + } + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RemainingItem.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RemainingItem.java index 1944628..d4ad100 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RemainingItem.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RemainingItem.java @@ -10,39 +10,39 @@ import org.bukkit.inventory.ItemStack; public class RemainingItem { - private final int slotIndex; - private final Material material; - private final short durability; - private int amount; + private final int slotIndex; + private final Material material; + private final short durability; + private int amount; - public RemainingItem(int slotIndex, ItemStack item) { - this.slotIndex = slotIndex; - this.material = item.getType(); - this.durability = item.getDurability(); - this.amount = item.getAmount(); - } + public RemainingItem(int slotIndex, ItemStack item) { + this.slotIndex = slotIndex; + this.material = item.getType(); + this.durability = item.getDurability(); + this.amount = item.getAmount(); + } - public int getSlotIndex() { - return slotIndex; - } + public int getSlotIndex() { + return slotIndex; + } - public Material getMaterial() { - return material; - } + public Material getMaterial() { + return material; + } - public short getDurability() { - return durability; - } + public short getDurability() { + return durability; + } - public int getAmount() { - return amount; - } + public int getAmount() { + return amount; + } - public int subtract(int minusAmount) { - int subtractedAmount = Math.min(minusAmount, this.amount); + public int subtract(int minusAmount) { + int subtractedAmount = Math.min(minusAmount, this.amount); - this.amount -= subtractedAmount; - return subtractedAmount; - } + this.amount -= subtractedAmount; + return subtractedAmount; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RequiredItem.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RequiredItem.java index 57b9f1c..01a6d6a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RequiredItem.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RequiredItem.java @@ -10,51 +10,51 @@ import org.bukkit.Material; public class RequiredItem { - private final Material material; - private final int amount; - private short durability; - private boolean isDurabilityRestrictive = false; + private final Material material; + private final int amount; + private short durability; + private boolean isDurabilityRestrictive = false; - public RequiredItem(Material material, int amount) { - Preconditions.checkArgumentNotAir(material, "material"); + public RequiredItem(Material material, int amount) { + Preconditions.checkArgumentNotAir(material, "material"); - this.material = material; - this.amount = amount; - } + this.material = material; + this.amount = amount; + } - public Material getMaterial() { - return material; - } + public Material getMaterial() { + return material; + } - public int getAmount() { - return amount; - } + public int getAmount() { + return amount; + } - public short getDurability() { - return durability; - } + public short getDurability() { + return durability; + } - public void setRestrictiveDurability(short durability) { - Preconditions.checkArgument(durability >= 0, "durability must be 0 or greater"); + public void setRestrictiveDurability(short durability) { + Preconditions.checkArgument(durability >= 0, "durability must be 0 or greater"); - this.durability = durability; - isDurabilityRestrictive = true; - } + this.durability = durability; + isDurabilityRestrictive = true; + } - public boolean hasRestrictiveDurability() { - return isDurabilityRestrictive; - } + public boolean hasRestrictiveDurability() { + return isDurabilityRestrictive; + } - public boolean isMatchingType(RemainingItem item) { - return item != null && item.getMaterial() == material && isMatchingDurability(item.getDurability()); - } - - private boolean isMatchingDurability(short durability) { - if (isDurabilityRestrictive) { - return this.durability == durability; - } else { - return true; - } - } - + public boolean isMatchingType(RemainingItem item) { + return item != null && item.getMaterial() == material && isMatchingDurability(item.getDurability()); + } + + private boolean isMatchingDurability(short durability) { + if (isDurabilityRestrictive) { + return this.durability == durability; + } else { + return true; + } + } + } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RequiredItems.java b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RequiredItems.java index ce696f2..a63e48a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RequiredItems.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/icon/requirement/item/RequiredItems.java @@ -6,49 +6,48 @@ package me.filoghost.chestcommands.icon.requirement.item; import com.google.common.collect.ImmutableList; +import java.util.List; import me.filoghost.chestcommands.config.Lang; import me.filoghost.chestcommands.icon.requirement.Requirement; import me.filoghost.chestcommands.util.Utils; import org.bukkit.entity.Player; -import java.util.List; - public class RequiredItems implements Requirement { - private final List items; - - public RequiredItems(List items) { - this.items = ImmutableList.copyOf(items); - } + private final List items; + + public RequiredItems(List items) { + this.items = ImmutableList.copyOf(items); + } - @Override - public boolean hasCost(Player player) { - InventoryTakeHelper inventoryTakeHelper = new InventoryTakeHelper(player.getInventory()); - boolean hasItems = inventoryTakeHelper.prepareTakeItems(items); + @Override + public boolean hasCost(Player player) { + InventoryTakeHelper inventoryTakeHelper = new InventoryTakeHelper(player.getInventory()); + boolean hasItems = inventoryTakeHelper.prepareTakeItems(items); - if (!hasItems) { - for (RequiredItem item : items) { - player.sendMessage(Lang.no_required_item - .replace("{material}", Utils.formatEnum(item.getMaterial())) - .replace("{amount}", Integer.toString(item.getAmount())) - .replace("{durability}", item.hasRestrictiveDurability() ? Short.toString(item.getDurability()) : Lang.any)); - } - } - - return hasItems; - } + if (!hasItems) { + for (RequiredItem item : items) { + player.sendMessage(Lang.no_required_item + .replace("{material}", Utils.formatEnum(item.getMaterial())) + .replace("{amount}", Integer.toString(item.getAmount())) + .replace("{durability}", item.hasRestrictiveDurability() ? Short.toString(item.getDurability()) : Lang.any)); + } + } + + return hasItems; + } - @Override - public boolean takeCost(Player player) { - InventoryTakeHelper inventoryTakeHelper = new InventoryTakeHelper(player.getInventory()); - boolean hasItems = inventoryTakeHelper.prepareTakeItems(items); + @Override + public boolean takeCost(Player player) { + InventoryTakeHelper inventoryTakeHelper = new InventoryTakeHelper(player.getInventory()); + boolean hasItems = inventoryTakeHelper.prepareTakeItems(items); - if (!hasItems) { - return false; - } - - inventoryTakeHelper.applyTakeItems(); - return true; - } - + if (!hasItems) { + return false; + } + + inventoryTakeHelper.applyTakeItems(); + return true; + } + } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/inventory/ArrayGrid.java b/plugin/src/main/java/me/filoghost/chestcommands/inventory/ArrayGrid.java index 29fa339..dc65b52 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/inventory/ArrayGrid.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/inventory/ArrayGrid.java @@ -7,22 +7,22 @@ package me.filoghost.chestcommands.inventory; public class ArrayGrid extends Grid { - private final T[] elements; + private final T[] elements; - @SuppressWarnings("unchecked") - public ArrayGrid(int rows, int columns) { - super(rows, columns); - this.elements = (T[]) new Object[getSize()]; - } + @SuppressWarnings("unchecked") + public ArrayGrid(int rows, int columns) { + super(rows, columns); + this.elements = (T[]) new Object[getSize()]; + } - @Override - protected T getByIndex0(int ordinalIndex) { - return elements[ordinalIndex]; - } + @Override + protected T getByIndex0(int ordinalIndex) { + return elements[ordinalIndex]; + } - @Override - protected void setByIndex0(int ordinalIndex, T element) { - elements[ordinalIndex] = element; - } + @Override + protected void setByIndex0(int ordinalIndex, T element) { + elements[ordinalIndex] = element; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/inventory/DefaultMenuView.java b/plugin/src/main/java/me/filoghost/chestcommands/inventory/DefaultMenuView.java index 89f0a9b..2dfb4fe 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/inventory/DefaultMenuView.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/inventory/DefaultMenuView.java @@ -17,53 +17,53 @@ import org.bukkit.inventory.ItemStack; */ public class DefaultMenuView implements MenuView { - private final BaseMenu menu; - private final InventoryGrid bukkitInventory; - private final Player viewer; + private final BaseMenu menu; + private final InventoryGrid bukkitInventory; + private final Player viewer; - public DefaultMenuView(BaseMenu menu, Player viewer) { - this.menu = menu; - this.viewer = viewer; - this.bukkitInventory = new InventoryGrid(new MenuInventoryHolder(this), menu.getRowCount(), menu.getTitle()); - refresh(); - } + public DefaultMenuView(BaseMenu menu, Player viewer) { + this.menu = menu; + this.viewer = viewer; + this.bukkitInventory = new InventoryGrid(new MenuInventoryHolder(this), menu.getRowCount(), menu.getTitle()); + refresh(); + } - @Override - public void refresh() { - for (int i = 0; i < menu.getIcons().getSize(); i++) { - Icon icon = menu.getIcons().getByIndex(i); + @Override + public void refresh() { + for (int i = 0; i < menu.getIcons().getSize(); i++) { + Icon icon = menu.getIcons().getByIndex(i); - if (icon == null) { - bukkitInventory.setByIndex(i, null); - } else if (icon instanceof RefreshableIcon) { - ItemStack newItemStack = ((RefreshableIcon) icon).updateRendering(viewer, bukkitInventory.getByIndex(i)); - bukkitInventory.setByIndex(i, newItemStack); - } else { - bukkitInventory.setByIndex(i, icon.render(viewer)); - } - } - } + if (icon == null) { + bukkitInventory.setByIndex(i, null); + } else if (icon instanceof RefreshableIcon) { + ItemStack newItemStack = ((RefreshableIcon) icon).updateRendering(viewer, bukkitInventory.getByIndex(i)); + bukkitInventory.setByIndex(i, newItemStack); + } else { + bukkitInventory.setByIndex(i, icon.render(viewer)); + } + } + } - public void open(Player viewer) { - viewer.openInventory(bukkitInventory.getInventory()); - } + public void open(Player viewer) { + viewer.openInventory(bukkitInventory.getInventory()); + } - public Icon getIcon(int slot) { - if (slot < 0 || slot >= bukkitInventory.getSize()) { - return null; - } + public Icon getIcon(int slot) { + if (slot < 0 || slot >= bukkitInventory.getSize()) { + return null; + } - return menu.getIcons().getByIndex(slot); - } + return menu.getIcons().getByIndex(slot); + } - @Override - public BaseMenu getMenu() { - return menu; - } + @Override + public BaseMenu getMenu() { + return menu; + } - @Override - public Player getViewer() { - return viewer; - } + @Override + public Player getViewer() { + return viewer; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/inventory/Grid.java b/plugin/src/main/java/me/filoghost/chestcommands/inventory/Grid.java index feb1d35..3ac0df2 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/inventory/Grid.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/inventory/Grid.java @@ -24,57 +24,57 @@ import me.filoghost.fcommons.Preconditions; * */ public abstract class Grid { - - private final int rows, columns, size; + + private final int rows, columns, size; - public Grid(int rows, int columns) { - this.rows = rows; - this.columns = columns; - this.size = rows * columns; - } + public Grid(int rows, int columns) { + this.rows = rows; + this.columns = columns; + this.size = rows * columns; + } - public final void set(int row, int column, T element) { - setByIndex(toOrdinalIndex(row, column), element); - } + public final void set(int row, int column, T element) { + setByIndex(toOrdinalIndex(row, column), element); + } - public final T get(int row, int column) { - return getByIndex(toOrdinalIndex(row, column)); - } - - public final T getByIndex(int ordinalIndex) { - Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex"); - return getByIndex0(ordinalIndex); - } + public final T get(int row, int column) { + return getByIndex(toOrdinalIndex(row, column)); + } + + public final T getByIndex(int ordinalIndex) { + Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex"); + return getByIndex0(ordinalIndex); + } - protected abstract T getByIndex0(int ordinalIndex); + protected abstract T getByIndex0(int ordinalIndex); - public final void setByIndex(int ordinalIndex, T element) { - Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex"); - setByIndex0(ordinalIndex, element); - } + public final void setByIndex(int ordinalIndex, T element) { + Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex"); + setByIndex0(ordinalIndex, element); + } - protected abstract void setByIndex0(int ordinalIndex, T element); + protected abstract void setByIndex0(int ordinalIndex, T element); - private int toOrdinalIndex(int row, int column) { - Preconditions.checkIndex(row, getRows(), "row"); - Preconditions.checkIndex(column, getColumns(), "column"); + private int toOrdinalIndex(int row, int column) { + Preconditions.checkIndex(row, getRows(), "row"); + Preconditions.checkIndex(column, getColumns(), "column"); - int ordinalIndex = row * getColumns() + column; - Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex"); - return ordinalIndex; - } - - public int getRows() { - return rows; - } - - public int getColumns() { - return columns; - } + int ordinalIndex = row * getColumns() + column; + Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex"); + return ordinalIndex; + } + + public int getRows() { + return rows; + } + + public int getColumns() { + return columns; + } - public int getSize() { - return size; - } + public int getSize() { + return size; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/inventory/InventoryGrid.java b/plugin/src/main/java/me/filoghost/chestcommands/inventory/InventoryGrid.java index 1616cbc..0710134 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/inventory/InventoryGrid.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/inventory/InventoryGrid.java @@ -11,25 +11,25 @@ import org.bukkit.inventory.ItemStack; public class InventoryGrid extends Grid { - private final Inventory inventory; + private final Inventory inventory; - public InventoryGrid(MenuInventoryHolder inventoryHolder, int rows, String title) { - super(rows, 9); - this.inventory = Bukkit.createInventory(inventoryHolder, getSize(), title); - } + public InventoryGrid(MenuInventoryHolder inventoryHolder, int rows, String title) { + super(rows, 9); + this.inventory = Bukkit.createInventory(inventoryHolder, getSize(), title); + } - public Inventory getInventory() { - return inventory; - } + public Inventory getInventory() { + return inventory; + } - @Override - protected ItemStack getByIndex0(int ordinalIndex) { - return inventory.getItem(ordinalIndex); - } + @Override + protected ItemStack getByIndex0(int ordinalIndex) { + return inventory.getItem(ordinalIndex); + } - @Override - protected void setByIndex0(int ordinalIndex, ItemStack element) { - inventory.setItem(ordinalIndex, element); - } + @Override + protected void setByIndex0(int ordinalIndex, ItemStack element) { + inventory.setItem(ordinalIndex, element); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/inventory/MenuInventoryHolder.java b/plugin/src/main/java/me/filoghost/chestcommands/inventory/MenuInventoryHolder.java index 397d543..1d250f4 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/inventory/MenuInventoryHolder.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/inventory/MenuInventoryHolder.java @@ -12,25 +12,25 @@ import org.bukkit.inventory.InventoryHolder; public class MenuInventoryHolder implements InventoryHolder { - private final DefaultMenuView menuView; + private final DefaultMenuView menuView; - public MenuInventoryHolder(DefaultMenuView menuView) { - Preconditions.notNull(menuView, "menuView"); - this.menuView = menuView; - } + public MenuInventoryHolder(DefaultMenuView menuView) { + Preconditions.notNull(menuView, "menuView"); + this.menuView = menuView; + } - @Override - public Inventory getInventory() { - /* - * This inventory will not do anything. - * I'm 90% sure that it doesn't break any other plugin, - * because the only way you can get here is using InventoryClickEvent, - * that is cancelled by ChestCommands, or using InventoryOpenEvent. - */ - return Bukkit.createInventory(null, 9); - } + @Override + public Inventory getInventory() { + /* + * This inventory will not do anything. + * I'm 90% sure that it doesn't break any other plugin, + * because the only way you can get here is using InventoryClickEvent, + * that is cancelled by ChestCommands, or using InventoryOpenEvent. + */ + return Bukkit.createInventory(null, 9); + } - public DefaultMenuView getMenuView() { - return menuView; - } + public DefaultMenuView getMenuView() { + return menuView; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/Backup.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/Backup.java index e01ab5e..1f3e361 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/Backup.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/Backup.java @@ -5,52 +5,51 @@ */ package me.filoghost.chestcommands.legacy; -import me.filoghost.fcommons.Preconditions; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; +import me.filoghost.fcommons.Preconditions; public class Backup { - private final Path dataFolder; - private final Path backupFolder; - private final Path infoFile; + private final Path dataFolder; + private final Path backupFolder; + private final Path infoFile; - public Backup(Path dataFolder, String backupName) { - this.dataFolder = dataFolder; - Path backupsFolder = dataFolder.resolve("old_files"); - this.backupFolder = backupsFolder.resolve(backupName); - this.infoFile = backupsFolder.resolve("readme.txt"); - } + public Backup(Path dataFolder, String backupName) { + this.dataFolder = dataFolder; + Path backupsFolder = dataFolder.resolve("old_files"); + this.backupFolder = backupsFolder.resolve(backupName); + this.infoFile = backupsFolder.resolve("readme.txt"); + } - public static Backup newTimestampedBackup(Path dataFolder) { - String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm")); - String backupName = "backup_" + date; - return new Backup(dataFolder, backupName); - } + public static Backup newTimestampedBackup(Path dataFolder) { + String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm")); + String backupName = "backup_" + date; + return new Backup(dataFolder, backupName); + } - public void addFile(Path fileToBackup) throws IOException { - Preconditions.checkArgument(fileToBackup.startsWith(dataFolder), "file is not inside data folder"); - Path destination = backupFolder.resolve(dataFolder.relativize(fileToBackup)); - Files.createDirectories(destination.getParent()); + public void addFile(Path fileToBackup) throws IOException { + Preconditions.checkArgument(fileToBackup.startsWith(dataFolder), "file is not inside data folder"); + Path destination = backupFolder.resolve(dataFolder.relativize(fileToBackup)); + Files.createDirectories(destination.getParent()); - // Add backup file if no already present - if (!Files.isRegularFile(destination)) { - Files.copy(fileToBackup, destination); - } + // Add backup file if no already present + if (!Files.isRegularFile(destination)) { + Files.copy(fileToBackup, destination); + } - // Add README file if not already present - if (!Files.isRegularFile(infoFile)) { - Files.write(infoFile, Arrays.asList( - "Files in this folders are copies of original configuration files that have been automatically upgraded.", - "", - "Note: some configuration upgrades remove comments and other formatting (such as empty lines)." - )); - } - } + // Add README file if not already present + if (!Files.isRegularFile(infoFile)) { + Files.write(infoFile, Arrays.asList( + "Files in this folders are copies of original configuration files that have been automatically upgraded.", + "", + "Note: some configuration upgrades remove comments and other formatting (such as empty lines)." + )); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradeExecutorException.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradeExecutorException.java index 12dca04..ebd9aab 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradeExecutorException.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradeExecutorException.java @@ -7,8 +7,8 @@ package me.filoghost.chestcommands.legacy; public class UpgradeExecutorException extends Exception { - public UpgradeExecutorException(String message, Throwable cause) { - super(message, cause); - } + public UpgradeExecutorException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradeList.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradeList.java index f51531c..5c3fb48 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradeList.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradeList.java @@ -6,6 +6,11 @@ package me.filoghost.chestcommands.legacy; import com.google.common.collect.ImmutableList; +import java.io.IOException; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; import me.filoghost.chestcommands.config.ConfigManager; import me.filoghost.chestcommands.legacy.upgrade.Upgrade; import me.filoghost.chestcommands.legacy.upgrade.UpgradeTask; @@ -20,74 +25,68 @@ import me.filoghost.fcommons.collection.CollectionUtils; import me.filoghost.fcommons.config.ConfigLoader; import me.filoghost.fcommons.logging.Log; -import java.io.IOException; -import java.nio.file.Path; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; - public class UpgradeList { - /* - * Note: order of declaration determines order of execution - */ - private static final ImmutableList orderedUpgrades = ImmutableList.of( - multiTaskUpgrade("v4.0-menus-rename", (configManager) -> { - return createMenuTasks(configManager, v4_0_MenuNodeRenameUpgradeTask::new); - }), + /* + * Note: order of declaration determines order of execution + */ + private static final ImmutableList orderedUpgrades = ImmutableList.of( + multiTaskUpgrade("v4.0-menus-rename", (configManager) -> { + return createMenuTasks(configManager, v4_0_MenuNodeRenameUpgradeTask::new); + }), - // Reformat after nodes have already been renamed - multiTaskUpgrade("v4.0-menus-reformat", (configManager) -> { - String legacyCommandSeparator = readLegacyCommandSeparator(configManager); - return createMenuTasks(configManager, - file -> new v4_0_MenuReformatUpgradeTask(configManager, file, legacyCommandSeparator)); - }), + // Reformat after nodes have already been renamed + multiTaskUpgrade("v4.0-menus-reformat", (configManager) -> { + String legacyCommandSeparator = readLegacyCommandSeparator(configManager); + return createMenuTasks(configManager, + file -> new v4_0_MenuReformatUpgradeTask(configManager, file, legacyCommandSeparator)); + }), - // Upgrade config after reading the command separator for menus - singleTaskUpgrade("v4.0-config", v4_0_SettingsUpgradeTask::new), - singleTaskUpgrade("v4.0-placeholders", v4_0_PlaceholdersUpgradeTask::new), - singleTaskUpgrade("v4.0-lang", v4_0_LangUpgradeTask::new) - ); + // Upgrade config after reading the command separator for menus + singleTaskUpgrade("v4.0-config", v4_0_SettingsUpgradeTask::new), + singleTaskUpgrade("v4.0-placeholders", v4_0_PlaceholdersUpgradeTask::new), + singleTaskUpgrade("v4.0-lang", v4_0_LangUpgradeTask::new) + ); - private static Upgrade singleTaskUpgrade(String id, Upgrade.SingleTaskSupplier upgradeTaskSupplier) { - return new Upgrade(id, configManager -> { - return Collections.singletonList(upgradeTaskSupplier.getTask(configManager)); - }); - } + private static Upgrade singleTaskUpgrade(String id, Upgrade.SingleTaskSupplier upgradeTaskSupplier) { + return new Upgrade(id, configManager -> { + return Collections.singletonList(upgradeTaskSupplier.getTask(configManager)); + }); + } - private static Upgrade multiTaskUpgrade(String id, Upgrade.MultiTaskSupplier upgradeTasksSupplier) { - return new Upgrade(id, upgradeTasksSupplier); - } + private static Upgrade multiTaskUpgrade(String id, Upgrade.MultiTaskSupplier upgradeTasksSupplier) { + return new Upgrade(id, upgradeTasksSupplier); + } - private static List createMenuTasks(ConfigManager configManager, Function menuTaskSupplier) throws UpgradeTaskException { - List menuFiles = getMenuFiles(configManager); - return CollectionUtils.transform(menuFiles, menuTaskSupplier); - } + private static List createMenuTasks(ConfigManager configManager, Function menuTaskSupplier) throws UpgradeTaskException { + List menuFiles = getMenuFiles(configManager); + return CollectionUtils.transform(menuFiles, menuTaskSupplier); + } - private static List getMenuFiles(ConfigManager configManager) throws UpgradeTaskException { - try { - return configManager.getMenuFiles(); - } catch (IOException e) { - throw new UpgradeTaskException(Errors.Upgrade.menuListIOException, e); - } - } + private static List getMenuFiles(ConfigManager configManager) throws UpgradeTaskException { + try { + return configManager.getMenuFiles(); + } catch (IOException e) { + throw new UpgradeTaskException(Errors.Upgrade.menuListIOException, e); + } + } - private static String readLegacyCommandSeparator(ConfigManager configManager) { - ConfigLoader settingsConfigLoader = configManager.getConfigLoader("config.yml"); + private static String readLegacyCommandSeparator(ConfigManager configManager) { + ConfigLoader settingsConfigLoader = configManager.getConfigLoader("config.yml"); - if (!settingsConfigLoader.fileExists()) { - return null; - } + if (!settingsConfigLoader.fileExists()) { + return null; + } - try { - return settingsConfigLoader.load().getString("multiple-commands-separator"); - } catch (Throwable t) { - Log.warning("Failed to load \"" + settingsConfigLoader.getFile() + "\", assuming default command separator \";\"."); - return null; - } - } + try { + return settingsConfigLoader.load().getString("multiple-commands-separator"); + } catch (Throwable t) { + Log.warning("Failed to load \"" + settingsConfigLoader.getFile() + "\", assuming default command separator \";\"."); + return null; + } + } - public static ImmutableList getOrderedUpgrades() { - return orderedUpgrades; - } + public static ImmutableList getOrderedUpgrades() { + return orderedUpgrades; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesDoneRegistry.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesDoneRegistry.java index 20e5118..31e8876 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesDoneRegistry.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesDoneRegistry.java @@ -5,8 +5,6 @@ */ package me.filoghost.chestcommands.legacy; -import me.filoghost.chestcommands.legacy.upgrade.Upgrade; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -15,52 +13,53 @@ import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; +import me.filoghost.chestcommands.legacy.upgrade.Upgrade; public class UpgradesDoneRegistry { - private final Path saveFile; - private final Set upgradesDone; - private boolean needSave; + private final Path saveFile; + private final Set upgradesDone; + private boolean needSave; - public UpgradesDoneRegistry(Path saveFile) throws IOException { - this.saveFile = saveFile; - this.upgradesDone = new HashSet<>(); + public UpgradesDoneRegistry(Path saveFile) throws IOException { + this.saveFile = saveFile; + this.upgradesDone = new HashSet<>(); - if (Files.isRegularFile(saveFile)) { - try (Stream lines = Files.lines(saveFile)) { - lines.filter(s -> !s.startsWith("#")) - .forEach(upgradesDone::add); - } - } - } + if (Files.isRegularFile(saveFile)) { + try (Stream lines = Files.lines(saveFile)) { + lines.filter(s -> !s.startsWith("#")) + .forEach(upgradesDone::add); + } + } + } - public void setAllDone() { - for (Upgrade upgrade : UpgradeList.getOrderedUpgrades()) { - setDone(upgrade); - } - } + public void setAllDone() { + for (Upgrade upgrade : UpgradeList.getOrderedUpgrades()) { + setDone(upgrade); + } + } - public void setDone(Upgrade upgrade) { - if (upgradesDone.add(upgrade.getID())) { - needSave = true; - } - } + public void setDone(Upgrade upgrade) { + if (upgradesDone.add(upgrade.getID())) { + needSave = true; + } + } - public boolean isDone(Upgrade upgrade) { - return upgradesDone.contains(upgrade.getID()); - } + public boolean isDone(Upgrade upgrade) { + return upgradesDone.contains(upgrade.getID()); + } - public void save() throws IOException { - if (needSave) { - List lines = new ArrayList<>(); - lines.add("#"); - lines.add("# WARNING: manually editing this file is not recommended"); - lines.add("#"); - lines.addAll(upgradesDone); - Files.createDirectories(saveFile.getParent()); - Files.write(saveFile, lines); - needSave = false; - } - } + public void save() throws IOException { + if (needSave) { + List lines = new ArrayList<>(); + lines.add("#"); + lines.add("# WARNING: manually editing this file is not recommended"); + lines.add("#"); + lines.addAll(upgradesDone); + Files.createDirectories(saveFile.getParent()); + Files.write(saveFile, lines); + needSave = false; + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesExecutor.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesExecutor.java index 4de819c..3c3014a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesExecutor.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesExecutor.java @@ -5,6 +5,9 @@ */ package me.filoghost.chestcommands.legacy; +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; import me.filoghost.chestcommands.config.ConfigManager; import me.filoghost.chestcommands.legacy.upgrade.Upgrade; import me.filoghost.chestcommands.legacy.upgrade.UpgradeTask; @@ -13,92 +16,88 @@ import me.filoghost.chestcommands.logging.Errors; import me.filoghost.fcommons.logging.ErrorCollector; import me.filoghost.fcommons.logging.Log; -import java.io.IOException; -import java.nio.file.Path; -import java.util.List; - public class UpgradesExecutor { - private final ConfigManager configManager; - private boolean allUpgradesSuccessful; - private UpgradesDoneRegistry upgradesDoneRegistry; + private final ConfigManager configManager; + private boolean allUpgradesSuccessful; + private UpgradesDoneRegistry upgradesDoneRegistry; - public UpgradesExecutor(ConfigManager configManager) { - this.configManager = configManager; - } + public UpgradesExecutor(ConfigManager configManager) { + this.configManager = configManager; + } - public boolean run(boolean isFreshInstall, ErrorCollector errorCollector) throws UpgradeExecutorException { - this.allUpgradesSuccessful = true; - Path upgradesDoneFile = configManager.getRootDataFolder().resolve(".upgrades-done"); + public boolean run(boolean isFreshInstall, ErrorCollector errorCollector) throws UpgradeExecutorException { + this.allUpgradesSuccessful = true; + Path upgradesDoneFile = configManager.getRootDataFolder().resolve(".upgrades-done"); - try { - upgradesDoneRegistry = new UpgradesDoneRegistry(upgradesDoneFile); - } catch (IOException e) { - // Upgrades can't proceed if metadata file is not read correctly - throw new UpgradeExecutorException(Errors.Upgrade.metadataReadError(upgradesDoneFile), e); - } + try { + upgradesDoneRegistry = new UpgradesDoneRegistry(upgradesDoneFile); + } catch (IOException e) { + // Upgrades can't proceed if metadata file is not read correctly + throw new UpgradeExecutorException(Errors.Upgrade.metadataReadError(upgradesDoneFile), e); + } - if (isFreshInstall) { - // Mark all currently existing upgrades as already done, assuming default configuration files are up to date - upgradesDoneRegistry.setAllDone(); - } else { - // Run missing upgrades - Backup backup = Backup.newTimestampedBackup(configManager.getRootDataFolder()); - runMissingUpgrades(backup, errorCollector); - } + if (isFreshInstall) { + // Mark all currently existing upgrades as already done, assuming default configuration files are up to date + upgradesDoneRegistry.setAllDone(); + } else { + // Run missing upgrades + Backup backup = Backup.newTimestampedBackup(configManager.getRootDataFolder()); + runMissingUpgrades(backup, errorCollector); + } - try { - upgradesDoneRegistry.save(); - } catch (IOException e) { - // Upgrades can't proceed if metadata file is not saved correctly - throw new UpgradeExecutorException(Errors.Upgrade.metadataSaveError(upgradesDoneFile), e); - } + try { + upgradesDoneRegistry.save(); + } catch (IOException e) { + // Upgrades can't proceed if metadata file is not saved correctly + throw new UpgradeExecutorException(Errors.Upgrade.metadataSaveError(upgradesDoneFile), e); + } - return allUpgradesSuccessful; - } + return allUpgradesSuccessful; + } - private void runMissingUpgrades(Backup backup, ErrorCollector errorCollector) { - for (Upgrade upgrade : UpgradeList.getOrderedUpgrades()) { - if (!upgradesDoneRegistry.isDone(upgrade)) { - boolean allTasksSuccessful = tryRunUpgradeTasks(upgrade, backup, errorCollector); + private void runMissingUpgrades(Backup backup, ErrorCollector errorCollector) { + for (Upgrade upgrade : UpgradeList.getOrderedUpgrades()) { + if (!upgradesDoneRegistry.isDone(upgrade)) { + boolean allTasksSuccessful = tryRunUpgradeTasks(upgrade, backup, errorCollector); - // Consider an upgrade "done" if all its tasks were completed successfully - if (allTasksSuccessful) { - upgradesDoneRegistry.setDone(upgrade); - } else { - allUpgradesSuccessful = false; - } - } - } - } + // Consider an upgrade "done" if all its tasks were completed successfully + if (allTasksSuccessful) { + upgradesDoneRegistry.setDone(upgrade); + } else { + allUpgradesSuccessful = false; + } + } + } + } - private boolean tryRunUpgradeTasks(Upgrade upgrade, Backup backup, ErrorCollector errorCollector) { - boolean allTasksSuccessful = true; + private boolean tryRunUpgradeTasks(Upgrade upgrade, Backup backup, ErrorCollector errorCollector) { + boolean allTasksSuccessful = true; - List upgradeTasks; - try { - upgradeTasks = upgrade.createUpgradeTasks(configManager); - } catch (UpgradeTaskException e) { - errorCollector.add(e, Errors.Upgrade.failedToPrepareUpgradeTasks); - return false; - } + List upgradeTasks; + try { + upgradeTasks = upgrade.createUpgradeTasks(configManager); + } catch (UpgradeTaskException e) { + errorCollector.add(e, Errors.Upgrade.failedToPrepareUpgradeTasks); + return false; + } - for (UpgradeTask upgradeTask : upgradeTasks) { - try { - boolean modified = upgradeTask.runAndBackupIfNecessary(backup); - if (modified) { - Log.info("Automatically upgraded configuration file \"" + upgradeTask.getUpgradedFile() + "\". " - + "A backup of the old file has been saved."); - } - } catch (UpgradeTaskException e) { - allTasksSuccessful = false; - errorCollector.add(e, Errors.Upgrade.failedSingleUpgrade(upgradeTask.getOriginalFile())); - } - } + for (UpgradeTask upgradeTask : upgradeTasks) { + try { + boolean modified = upgradeTask.runAndBackupIfNecessary(backup); + if (modified) { + Log.info("Automatically upgraded configuration file \"" + upgradeTask.getUpgradedFile() + "\". " + + "A backup of the old file has been saved."); + } + } catch (UpgradeTaskException e) { + allTasksSuccessful = false; + errorCollector.add(e, Errors.Upgrade.failedSingleUpgrade(upgradeTask.getOriginalFile())); + } + } - return allTasksSuccessful; - } + return allTasksSuccessful; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/RegexReplacer.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/RegexReplacer.java index 184a617..6c1cd78 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/RegexReplacer.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/RegexReplacer.java @@ -11,24 +11,24 @@ import java.util.regex.Pattern; public class RegexReplacer implements Function { - private final Pattern regex; - private final Function replaceCallback; + private final Pattern regex; + private final Function replaceCallback; - public RegexReplacer(Pattern regex, Function replaceCallback) { - this.regex = regex; - this.replaceCallback = replaceCallback; - } + public RegexReplacer(Pattern regex, Function replaceCallback) { + this.regex = regex; + this.replaceCallback = replaceCallback; + } - @Override - public String apply(String string) { - Matcher matcher = regex.matcher(string); - StringBuffer output = new StringBuffer(); + @Override + public String apply(String string) { + Matcher matcher = regex.matcher(string); + StringBuffer output = new StringBuffer(); - while (matcher.find()) { - matcher.appendReplacement(output, replaceCallback.apply(matcher)); - } - matcher.appendTail(output); + while (matcher.find()) { + matcher.appendReplacement(output, replaceCallback.apply(matcher)); + } + matcher.appendTail(output); - return output.toString(); - } + return output.toString(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/RegexUpgradeTask.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/RegexUpgradeTask.java index 6650246..8245566 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/RegexUpgradeTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/RegexUpgradeTask.java @@ -5,10 +5,6 @@ */ package me.filoghost.chestcommands.legacy.upgrade; -import me.filoghost.fcommons.config.ConfigErrors; -import me.filoghost.fcommons.config.exception.ConfigLoadException; -import me.filoghost.fcommons.config.exception.ConfigSaveException; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -18,77 +14,80 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import me.filoghost.fcommons.config.ConfigErrors; +import me.filoghost.fcommons.config.exception.ConfigLoadException; +import me.filoghost.fcommons.config.exception.ConfigSaveException; public abstract class RegexUpgradeTask extends UpgradeTask { - private final Path file; - private List newContents; - private Stream linesStream; + private final Path file; + private List newContents; + private Stream linesStream; - public RegexUpgradeTask(Path file) { - this.file = file; - } + public RegexUpgradeTask(Path file) { + this.file = file; + } - @Override - public final Path getOriginalFile() { - return file; - } + @Override + public final Path getOriginalFile() { + return file; + } - @Override - public final Path getUpgradedFile() { - return file; - } + @Override + public final Path getUpgradedFile() { + return file; + } - @Override - public final void computeChanges() throws ConfigLoadException { - if (!Files.isRegularFile(file)) { - return; - } + @Override + public final void computeChanges() throws ConfigLoadException { + if (!Files.isRegularFile(file)) { + return; + } - List lines; - try { - lines = Files.readAllLines(file); - } catch (IOException e) { - throw new ConfigLoadException(ConfigErrors.readIOException, e); - } + List lines; + try { + lines = Files.readAllLines(file); + } catch (IOException e) { + throw new ConfigLoadException(ConfigErrors.readIOException, e); + } - this.linesStream = lines.stream(); - computeRegexChanges(); + this.linesStream = lines.stream(); + computeRegexChanges(); - newContents = linesStream.collect(Collectors.toList()); + newContents = linesStream.collect(Collectors.toList()); - if (!newContents.equals(lines)) { - setSaveRequired(); - } - } + if (!newContents.equals(lines)) { + setSaveRequired(); + } + } - @Override - public final void saveChanges() throws ConfigSaveException { - try { - Files.write(file, newContents); - } catch (IOException e) { - throw new ConfigSaveException(ConfigErrors.writeDataIOException, e); - } - } + @Override + public final void saveChanges() throws ConfigSaveException { + try { + Files.write(file, newContents); + } catch (IOException e) { + throw new ConfigSaveException(ConfigErrors.writeDataIOException, e); + } + } - protected abstract void computeRegexChanges(); + protected abstract void computeRegexChanges(); - protected void replaceString(String target, String replacement) { - replaceRegex( - Pattern.compile(Pattern.quote(target)), - matcher -> replacement - ); - } + protected void replaceString(String target, String replacement) { + replaceRegex( + Pattern.compile(Pattern.quote(target)), + matcher -> replacement + ); + } - protected void replaceSubNode(String oldNode, String newNode) { - replaceRegex( - Pattern.compile("(^\\s+)" + Pattern.quote(oldNode) + "(:)"), - matcher -> matcher.group(1) + newNode + matcher.group(2) - ); - } + protected void replaceSubNode(String oldNode, String newNode) { + replaceRegex( + Pattern.compile("(^\\s+)" + Pattern.quote(oldNode) + "(:)"), + matcher -> matcher.group(1) + newNode + matcher.group(2) + ); + } - protected void replaceRegex(Pattern regex, Function replaceCallback) { - linesStream = linesStream.map(new RegexReplacer(regex, replaceCallback)); - } + protected void replaceRegex(Pattern regex, Function replaceCallback) { + linesStream = linesStream.map(new RegexReplacer(regex, replaceCallback)); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/Upgrade.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/Upgrade.java index 02f2af4..347bb67 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/Upgrade.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/Upgrade.java @@ -5,40 +5,39 @@ */ package me.filoghost.chestcommands.legacy.upgrade; -import me.filoghost.chestcommands.config.ConfigManager; - import java.util.List; +import me.filoghost.chestcommands.config.ConfigManager; public class Upgrade { - private final String id; - private final MultiTaskSupplier upgradeTasksSupplier; + private final String id; + private final MultiTaskSupplier upgradeTasksSupplier; - public Upgrade(String id, MultiTaskSupplier taskSupplier) { - this.id = id; - this.upgradeTasksSupplier = taskSupplier; - } + public Upgrade(String id, MultiTaskSupplier taskSupplier) { + this.id = id; + this.upgradeTasksSupplier = taskSupplier; + } - public String getID() { - return id; - } + public String getID() { + return id; + } - public List createUpgradeTasks(ConfigManager configManager) throws UpgradeTaskException { - return upgradeTasksSupplier.getTasks(configManager); - } + public List createUpgradeTasks(ConfigManager configManager) throws UpgradeTaskException { + return upgradeTasksSupplier.getTasks(configManager); + } - @FunctionalInterface - public interface SingleTaskSupplier { + @FunctionalInterface + public interface SingleTaskSupplier { - UpgradeTask getTask(ConfigManager configManager) throws UpgradeTaskException; + UpgradeTask getTask(ConfigManager configManager) throws UpgradeTaskException; - } + } - @FunctionalInterface - public interface MultiTaskSupplier { + @FunctionalInterface + public interface MultiTaskSupplier { - List getTasks(ConfigManager configManager) throws UpgradeTaskException; + List getTasks(ConfigManager configManager) throws UpgradeTaskException; - } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/UpgradeTask.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/UpgradeTask.java index bd652fc..9a06a6d 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/UpgradeTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/UpgradeTask.java @@ -5,60 +5,59 @@ */ package me.filoghost.chestcommands.legacy.upgrade; +import java.io.IOException; +import java.nio.file.Path; import me.filoghost.chestcommands.legacy.Backup; import me.filoghost.chestcommands.logging.Errors; import me.filoghost.fcommons.Preconditions; import me.filoghost.fcommons.config.exception.ConfigLoadException; import me.filoghost.fcommons.config.exception.ConfigSaveException; -import java.io.IOException; -import java.nio.file.Path; - public abstract class UpgradeTask { - private boolean saveRequired; - private boolean hasRun; + private boolean saveRequired; + private boolean hasRun; - protected void setSaveRequired() { - this.saveRequired = true; - } + protected void setSaveRequired() { + this.saveRequired = true; + } - public boolean runAndBackupIfNecessary(Backup backup) throws UpgradeTaskException { - Preconditions.checkState(!hasRun, "Upgrade task has already run"); - hasRun = true; + public boolean runAndBackupIfNecessary(Backup backup) throws UpgradeTaskException { + Preconditions.checkState(!hasRun, "Upgrade task has already run"); + hasRun = true; - try { - computeChanges(); - } catch (ConfigLoadException e) { - throw new UpgradeTaskException(Errors.Upgrade.loadError(getOriginalFile()), e); - } + try { + computeChanges(); + } catch (ConfigLoadException e) { + throw new UpgradeTaskException(Errors.Upgrade.loadError(getOriginalFile()), e); + } - if (saveRequired) { - try { - backup.addFile(getOriginalFile()); - } catch (IOException e) { - throw new UpgradeTaskException(Errors.Upgrade.backupError(getOriginalFile()), e); - } + if (saveRequired) { + try { + backup.addFile(getOriginalFile()); + } catch (IOException e) { + throw new UpgradeTaskException(Errors.Upgrade.backupError(getOriginalFile()), e); + } - try { - saveChanges(); - } catch (ConfigSaveException e) { - throw new UpgradeTaskException(Errors.Upgrade.saveError(getUpgradedFile()), e); - } + try { + saveChanges(); + } catch (ConfigSaveException e) { + throw new UpgradeTaskException(Errors.Upgrade.saveError(getUpgradedFile()), e); + } - return true; + return true; - } else { - return false; - } - } + } else { + return false; + } + } - public abstract Path getOriginalFile(); + public abstract Path getOriginalFile(); - public abstract Path getUpgradedFile(); + public abstract Path getUpgradedFile(); - protected abstract void computeChanges() throws ConfigLoadException; + protected abstract void computeChanges() throws ConfigLoadException; - protected abstract void saveChanges() throws ConfigSaveException; + protected abstract void saveChanges() throws ConfigSaveException; } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/UpgradeTaskException.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/UpgradeTaskException.java index d0ae06c..0ce36ea 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/UpgradeTaskException.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/UpgradeTaskException.java @@ -7,8 +7,8 @@ package me.filoghost.chestcommands.legacy.upgrade; public class UpgradeTaskException extends Exception { - public UpgradeTaskException(String message, Throwable cause) { - super(message, cause); - } + public UpgradeTaskException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/YamlUpgradeTask.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/YamlUpgradeTask.java index e0f79ea..40d5fa6 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/YamlUpgradeTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrade/YamlUpgradeTask.java @@ -5,62 +5,61 @@ */ package me.filoghost.chestcommands.legacy.upgrade; +import java.nio.file.Path; import me.filoghost.fcommons.config.Config; import me.filoghost.fcommons.config.ConfigLoader; import me.filoghost.fcommons.config.exception.ConfigLoadException; import me.filoghost.fcommons.config.exception.ConfigSaveException; -import java.nio.file.Path; - public abstract class YamlUpgradeTask extends UpgradeTask { - private final ConfigLoader configLoader; - private Config updatedConfig; + private final ConfigLoader configLoader; + private Config updatedConfig; - public YamlUpgradeTask(ConfigLoader configLoader) { - this.configLoader = configLoader; - } + public YamlUpgradeTask(ConfigLoader configLoader) { + this.configLoader = configLoader; + } - @Override - public final Path getOriginalFile() { - return configLoader.getFile(); - } + @Override + public final Path getOriginalFile() { + return configLoader.getFile(); + } - @Override - public final Path getUpgradedFile() { - return configLoader.getFile(); - } + @Override + public final Path getUpgradedFile() { + return configLoader.getFile(); + } - @Override - public final void computeChanges() throws ConfigLoadException { - if (!configLoader.fileExists()) { - return; - } - Config config = configLoader.load(); - computeYamlChanges(config); - this.updatedConfig = config; - } + @Override + public final void computeChanges() throws ConfigLoadException { + if (!configLoader.fileExists()) { + return; + } + Config config = configLoader.load(); + computeYamlChanges(config); + this.updatedConfig = config; + } - @Override - public final void saveChanges() throws ConfigSaveException { - configLoader.save(updatedConfig); - } + @Override + public final void saveChanges() throws ConfigSaveException { + configLoader.save(updatedConfig); + } - protected abstract void computeYamlChanges(Config config); + protected abstract void computeYamlChanges(Config config); - protected void removeNode(Config config, String node) { - if (config.contains(node)) { - config.remove(node); - setSaveRequired(); - } - } + protected void removeNode(Config config, String node) { + if (config.contains(node)) { + config.remove(node); + setSaveRequired(); + } + } - protected void replaceStringValue(Config settingsConfig, String node, String target, String replacement) { - String value = settingsConfig.getString(node); - if (value.contains(target)) { - settingsConfig.setString(node, value.replace(target, replacement)); - setSaveRequired(); - } - } + protected void replaceStringValue(Config settingsConfig, String node, String target, String replacement) { + String value = settingsConfig.getString(node); + if (value.contains(target)) { + settingsConfig.setString(node, value.replace(target, replacement)); + setSaveRequired(); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_LangUpgradeTask.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_LangUpgradeTask.java index e499bbd..cf1a5ab 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_LangUpgradeTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_LangUpgradeTask.java @@ -11,15 +11,15 @@ import me.filoghost.fcommons.config.Config; public class v4_0_LangUpgradeTask extends YamlUpgradeTask { - public v4_0_LangUpgradeTask(ConfigManager configManager) { - super(configManager.getConfigLoader("lang.yml")); - } + public v4_0_LangUpgradeTask(ConfigManager configManager) { + super(configManager.getConfigLoader("lang.yml")); + } - @Override - public void computeYamlChanges(Config settingsConfig) { - removeNode(settingsConfig, "open-menu"); - removeNode(settingsConfig, "open-menu-others"); - replaceStringValue(settingsConfig, "no-required-item", "{datavalue}", "{durability}"); - } + @Override + public void computeYamlChanges(Config settingsConfig) { + removeNode(settingsConfig, "open-menu"); + removeNode(settingsConfig, "open-menu-others"); + replaceStringValue(settingsConfig, "no-required-item", "{datavalue}", "{durability}"); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_MenuNodeRenameUpgradeTask.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_MenuNodeRenameUpgradeTask.java index 51e2884..e1952a1 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_MenuNodeRenameUpgradeTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_MenuNodeRenameUpgradeTask.java @@ -5,29 +5,28 @@ */ package me.filoghost.chestcommands.legacy.v4_0; +import java.nio.file.Path; import me.filoghost.chestcommands.legacy.upgrade.RegexUpgradeTask; import me.filoghost.chestcommands.parsing.icon.AttributeType; -import java.nio.file.Path; - public class v4_0_MenuNodeRenameUpgradeTask extends RegexUpgradeTask { - public v4_0_MenuNodeRenameUpgradeTask(Path menuFile) { - super(menuFile); - } - @Override - protected void computeRegexChanges() { - replaceSubNode("command", "commands"); - replaceSubNode("open-action", "open-actions"); - replaceSubNode("id", "material"); + public v4_0_MenuNodeRenameUpgradeTask(Path menuFile) { + super(menuFile); + } + @Override + protected void computeRegexChanges() { + replaceSubNode("command", "commands"); + replaceSubNode("open-action", "open-actions"); + replaceSubNode("id", "material"); - replaceSubNode("ID", AttributeType.MATERIAL.getAttributeName()); - replaceSubNode("DATA-VALUE", AttributeType.DURABILITY.getAttributeName()); - replaceSubNode("NBT", AttributeType.NBT_DATA.getAttributeName()); - replaceSubNode("ENCHANTMENT", AttributeType.ENCHANTMENTS.getAttributeName()); - replaceSubNode("COMMAND", AttributeType.ACTIONS.getAttributeName()); - replaceSubNode("COMMANDS", AttributeType.ACTIONS.getAttributeName()); - replaceSubNode("REQUIRED-ITEM", AttributeType.REQUIRED_ITEMS.getAttributeName()); - } + replaceSubNode("ID", AttributeType.MATERIAL.getAttributeName()); + replaceSubNode("DATA-VALUE", AttributeType.DURABILITY.getAttributeName()); + replaceSubNode("NBT", AttributeType.NBT_DATA.getAttributeName()); + replaceSubNode("ENCHANTMENT", AttributeType.ENCHANTMENTS.getAttributeName()); + replaceSubNode("COMMAND", AttributeType.ACTIONS.getAttributeName()); + replaceSubNode("COMMANDS", AttributeType.ACTIONS.getAttributeName()); + replaceSubNode("REQUIRED-ITEM", AttributeType.REQUIRED_ITEMS.getAttributeName()); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_MenuReformatUpgradeTask.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_MenuReformatUpgradeTask.java index d6fab5c..a6ac8dc 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_MenuReformatUpgradeTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_MenuReformatUpgradeTask.java @@ -5,6 +5,11 @@ */ package me.filoghost.chestcommands.legacy.v4_0; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; import me.filoghost.chestcommands.config.ConfigManager; import me.filoghost.chestcommands.legacy.upgrade.YamlUpgradeTask; import me.filoghost.chestcommands.parsing.icon.AttributeType; @@ -14,154 +19,148 @@ import me.filoghost.fcommons.config.Config; import me.filoghost.fcommons.config.ConfigSection; import me.filoghost.fcommons.config.ConfigValueType; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; - public class v4_0_MenuReformatUpgradeTask extends YamlUpgradeTask { - private final String legacyCommandSeparator; + private final String legacyCommandSeparator; - public v4_0_MenuReformatUpgradeTask(ConfigManager configManager, Path menuFile, String legacyCommandSeparator) { - super(configManager.getConfigLoader(menuFile)); - this.legacyCommandSeparator = legacyCommandSeparator; - } + public v4_0_MenuReformatUpgradeTask(ConfigManager configManager, Path menuFile, String legacyCommandSeparator) { + super(configManager.getConfigLoader(menuFile)); + this.legacyCommandSeparator = legacyCommandSeparator; + } - @Override - public void computeYamlChanges(Config menuConfig) { - menuConfig.setHeader(null); + @Override + public void computeYamlChanges(Config menuConfig) { + menuConfig.setHeader(null); - for (String key : menuConfig.getKeys()) { - ConfigSection section = menuConfig.getConfigSection(key); - if (section == null) { - continue; - } + for (String key : menuConfig.getKeys()) { + ConfigSection section = menuConfig.getConfigSection(key); + if (section == null) { + continue; + } - if (key.equals(MenuSettingsNode.ROOT_SECTION)) { - upgradeMenuSettings(section); - } else { - upgradeIcon(section); - } - } - } + if (key.equals(MenuSettingsNode.ROOT_SECTION)) { + upgradeMenuSettings(section); + } else { + upgradeIcon(section); + } + } + } - private void upgradeMenuSettings(ConfigSection section) { - expandInlineList(section, MenuSettingsNode.COMMANDS, ";"); - expandInlineList(section, MenuSettingsNode.OPEN_ACTIONS, legacyCommandSeparator); - updateActionPrefixes(section, MenuSettingsNode.OPEN_ACTIONS); - } + private void upgradeMenuSettings(ConfigSection section) { + expandInlineList(section, MenuSettingsNode.COMMANDS, ";"); + expandInlineList(section, MenuSettingsNode.OPEN_ACTIONS, legacyCommandSeparator); + updateActionPrefixes(section, MenuSettingsNode.OPEN_ACTIONS); + } - private void upgradeIcon(ConfigSection section) { - expandInlineList(section, AttributeType.ENCHANTMENTS.getAttributeName(), ";"); - expandInlineList(section, AttributeType.ACTIONS.getAttributeName(), legacyCommandSeparator); - updateActionPrefixes(section, AttributeType.ACTIONS.getAttributeName()); - expandSingletonList(section, AttributeType.REQUIRED_ITEMS.getAttributeName()); - expandInlineItemstack(section); - } + private void upgradeIcon(ConfigSection section) { + expandInlineList(section, AttributeType.ENCHANTMENTS.getAttributeName(), ";"); + expandInlineList(section, AttributeType.ACTIONS.getAttributeName(), legacyCommandSeparator); + updateActionPrefixes(section, AttributeType.ACTIONS.getAttributeName()); + expandSingletonList(section, AttributeType.REQUIRED_ITEMS.getAttributeName()); + expandInlineItemstack(section); + } - private void updateActionPrefixes(ConfigSection config, String node) { - List actions = config.getStringList(node); - if (actions == null) { - return; - } + private void updateActionPrefixes(ConfigSection config, String node) { + List actions = config.getStringList(node); + if (actions == null) { + return; + } - for (int i = 0; i < actions.size(); i++) { - String oldAction = actions.get(i); - String newAction = oldAction; - newAction = replacePrefix(newAction, "menu:", "open:"); - newAction = replacePrefix(newAction, "givemoney:", "give-money:"); - newAction = replacePrefix(newAction, "dragonbar:", "dragon-bar:"); - newAction = replacePrefix(newAction, "server ", "server: "); + for (int i = 0; i < actions.size(); i++) { + String oldAction = actions.get(i); + String newAction = oldAction; + newAction = replacePrefix(newAction, "menu:", "open:"); + newAction = replacePrefix(newAction, "givemoney:", "give-money:"); + newAction = replacePrefix(newAction, "dragonbar:", "dragon-bar:"); + newAction = replacePrefix(newAction, "server ", "server: "); - if (!newAction.equals(oldAction)) { - setSaveRequired(); - actions.set(i, newAction); - } - } + if (!newAction.equals(oldAction)) { + setSaveRequired(); + actions.set(i, newAction); + } + } - config.setStringList(node, actions); - } + config.setStringList(node, actions); + } - private String replacePrefix(String action, String oldPrefix, String newPrefix) { - if (action.startsWith(oldPrefix)) { - setSaveRequired(); - return newPrefix + action.substring(oldPrefix.length()); - } else { - return action; - } - } + private String replacePrefix(String action, String oldPrefix, String newPrefix) { + if (action.startsWith(oldPrefix)) { + setSaveRequired(); + return newPrefix + action.substring(oldPrefix.length()); + } else { + return action; + } + } - private void expandInlineItemstack(ConfigSection section) { - String material = section.getString(AttributeType.MATERIAL.getAttributeName()); - if (material == null) { - return; - } + private void expandInlineItemstack(ConfigSection section) { + String material = section.getString(AttributeType.MATERIAL.getAttributeName()); + if (material == null) { + return; + } - if (material.contains(",")) { - String[] parts = Strings.trimmedSplit(material, ",", 2); - if (!section.contains(AttributeType.AMOUNT.getAttributeName())) { - try { - section.setInt(AttributeType.AMOUNT.getAttributeName(), Integer.parseInt(parts[1])); - } catch (NumberFormatException e) { - section.setString(AttributeType.AMOUNT.getAttributeName(), parts[1]); - } - } - material = parts[0]; - section.setString(AttributeType.MATERIAL.getAttributeName(), material); - setSaveRequired(); - } + if (material.contains(",")) { + String[] parts = Strings.trimmedSplit(material, ",", 2); + if (!section.contains(AttributeType.AMOUNT.getAttributeName())) { + try { + section.setInt(AttributeType.AMOUNT.getAttributeName(), Integer.parseInt(parts[1])); + } catch (NumberFormatException e) { + section.setString(AttributeType.AMOUNT.getAttributeName(), parts[1]); + } + } + material = parts[0]; + section.setString(AttributeType.MATERIAL.getAttributeName(), material); + setSaveRequired(); + } - if (material.contains(":")) { - String[] parts = Strings.trimmedSplit(material, ":", 2); - if (!section.contains(AttributeType.DURABILITY.getAttributeName())) { - try { - section.setInt(AttributeType.DURABILITY.getAttributeName(), Integer.parseInt(parts[1])); - } catch (NumberFormatException e) { - section.setString(AttributeType.DURABILITY.getAttributeName(), parts[1]); - } - } - material = parts[0]; - section.setString(AttributeType.MATERIAL.getAttributeName(), material); - setSaveRequired(); - } - } + if (material.contains(":")) { + String[] parts = Strings.trimmedSplit(material, ":", 2); + if (!section.contains(AttributeType.DURABILITY.getAttributeName())) { + try { + section.setInt(AttributeType.DURABILITY.getAttributeName(), Integer.parseInt(parts[1])); + } catch (NumberFormatException e) { + section.setString(AttributeType.DURABILITY.getAttributeName(), parts[1]); + } + } + material = parts[0]; + section.setString(AttributeType.MATERIAL.getAttributeName(), material); + setSaveRequired(); + } + } - private void expandInlineList(ConfigSection config, String node, String separator) { - if (config.get(node).isValidAs(ConfigValueType.STRING)) { - config.setStringList(node, splitListElements(config.getString(node), separator)); - setSaveRequired(); - } - } + private void expandInlineList(ConfigSection config, String node, String separator) { + if (config.get(node).isValidAs(ConfigValueType.STRING)) { + config.setStringList(node, splitListElements(config.getString(node), separator)); + setSaveRequired(); + } + } - private void expandSingletonList(ConfigSection config, String node) { - if (config.get(node).isValidAs(ConfigValueType.STRING)) { - config.setStringList(node, Collections.singletonList(config.getString(node))); - setSaveRequired(); - } - } + private void expandSingletonList(ConfigSection config, String node) { + if (config.get(node).isValidAs(ConfigValueType.STRING)) { + config.setStringList(node, Collections.singletonList(config.getString(node))); + setSaveRequired(); + } + } - private List splitListElements(String input, String separator) { - if (separator == null || separator.length() == 0) { - separator = ";"; - } + private List splitListElements(String input, String separator) { + if (separator == null || separator.length() == 0) { + separator = ";"; + } - String[] splitValues = Strings.trimmedSplit(input, Pattern.quote(separator)); - List values = new ArrayList<>(); + String[] splitValues = Strings.trimmedSplit(input, Pattern.quote(separator)); + List values = new ArrayList<>(); - for (String value : splitValues) { - if (!value.isEmpty()) { - values.add(value); - } - } + for (String value : splitValues) { + if (!value.isEmpty()) { + values.add(value); + } + } - // Return a list with an empty value to avoid displaying the empty list value "[]" in the YML file - if (values.isEmpty()) { - values.add(""); - } + // Return a list with an empty value to avoid displaying the empty list value "[]" in the YML file + if (values.isEmpty()) { + values.add(""); + } - return values; - } + return values; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_PlaceholdersUpgradeTask.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_PlaceholdersUpgradeTask.java index d0a109d..c806a04 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_PlaceholdersUpgradeTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_PlaceholdersUpgradeTask.java @@ -5,6 +5,10 @@ */ package me.filoghost.chestcommands.legacy.v4_0; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; import me.filoghost.chestcommands.config.ConfigManager; import me.filoghost.chestcommands.legacy.upgrade.UpgradeTask; import me.filoghost.fcommons.Strings; @@ -15,89 +19,84 @@ import me.filoghost.fcommons.config.exception.ConfigLoadException; import me.filoghost.fcommons.config.exception.ConfigSaveException; import org.apache.commons.lang.StringEscapeUtils; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - public class v4_0_PlaceholdersUpgradeTask extends UpgradeTask { - private final Path oldPlaceholdersFile; - private final ConfigLoader newPlaceholdersConfigLoader; - private Config updatedConfig; + private final Path oldPlaceholdersFile; + private final ConfigLoader newPlaceholdersConfigLoader; + private Config updatedConfig; - public v4_0_PlaceholdersUpgradeTask(ConfigManager configManager) { - this.oldPlaceholdersFile = configManager.getRootDataFolder().resolve("placeholders.yml"); - this.newPlaceholdersConfigLoader = configManager.getConfigLoader("custom-placeholders.yml"); - } + public v4_0_PlaceholdersUpgradeTask(ConfigManager configManager) { + this.oldPlaceholdersFile = configManager.getRootDataFolder().resolve("placeholders.yml"); + this.newPlaceholdersConfigLoader = configManager.getConfigLoader("custom-placeholders.yml"); + } - @Override - public Path getOriginalFile() { - return oldPlaceholdersFile; - } + @Override + public Path getOriginalFile() { + return oldPlaceholdersFile; + } - @Override - public Path getUpgradedFile() { - return newPlaceholdersConfigLoader.getFile(); - } + @Override + public Path getUpgradedFile() { + return newPlaceholdersConfigLoader.getFile(); + } - @Override - public void computeChanges() throws ConfigLoadException { - if (!Files.isRegularFile(oldPlaceholdersFile)) { - return; - } + @Override + public void computeChanges() throws ConfigLoadException { + if (!Files.isRegularFile(oldPlaceholdersFile)) { + return; + } - // Do NOT load the new placeholder configuration from disk, as it should only contain placeholders imported from the old file - Config newPlaceholdersConfig = new Config(newPlaceholdersConfigLoader.getFile()); - List lines; - try { - lines = Files.readAllLines(oldPlaceholdersFile); - } catch (IOException e) { - throw new ConfigLoadException(ConfigErrors.readIOException, e); - } + // Do NOT load the new placeholder configuration from disk, as it should only contain placeholders imported from the old file + Config newPlaceholdersConfig = new Config(newPlaceholdersConfigLoader.getFile()); + List lines; + try { + lines = Files.readAllLines(oldPlaceholdersFile); + } catch (IOException e) { + throw new ConfigLoadException(ConfigErrors.readIOException, e); + } - for (String line : lines) { - // Comment or empty line - if (line.isEmpty() || line.startsWith("#")) { - continue; - } + for (String line : lines) { + // Comment or empty line + if (line.isEmpty() || line.startsWith("#")) { + continue; + } - // Ignore bad line - if (!line.contains(":")) { - continue; - } + // Ignore bad line + if (!line.contains(":")) { + continue; + } - String[] parts = Strings.trimmedSplit(line, ":", 2); - String placeholder = unquote(parts[0]); - String replacement = StringEscapeUtils.unescapeJava(unquote(parts[1])); + String[] parts = Strings.trimmedSplit(line, ":", 2); + String placeholder = unquote(parts[0]); + String replacement = StringEscapeUtils.unescapeJava(unquote(parts[1])); - newPlaceholdersConfig.setString("placeholders." + placeholder, replacement); - setSaveRequired(); - } + newPlaceholdersConfig.setString("placeholders." + placeholder, replacement); + setSaveRequired(); + } - this.updatedConfig = newPlaceholdersConfig; - } + this.updatedConfig = newPlaceholdersConfig; + } - @Override - public void saveChanges() throws ConfigSaveException { - try { - Files.deleteIfExists(oldPlaceholdersFile); - } catch (IOException ignored) {} - newPlaceholdersConfigLoader.save(updatedConfig); - } + @Override + public void saveChanges() throws ConfigSaveException { + try { + Files.deleteIfExists(oldPlaceholdersFile); + } catch (IOException ignored) {} + newPlaceholdersConfigLoader.save(updatedConfig); + } - private static String unquote(String input) { - if (input.length() < 2) { - // Too short, cannot be a quoted string - return input; - } - if (input.startsWith("'") && input.endsWith("'")) { - return input.substring(1, input.length() - 1); - } else if (input.startsWith("\"") && input.endsWith("\"")) { - return input.substring(1, input.length() - 1); - } + private static String unquote(String input) { + if (input.length() < 2) { + // Too short, cannot be a quoted string + return input; + } + if (input.startsWith("'") && input.endsWith("'")) { + return input.substring(1, input.length() - 1); + } else if (input.startsWith("\"") && input.endsWith("\"")) { + return input.substring(1, input.length() - 1); + } - return input; - } + return input; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_SettingsUpgradeTask.java b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_SettingsUpgradeTask.java index e728684..bc2eb0f 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_SettingsUpgradeTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/legacy/v4_0/v4_0_SettingsUpgradeTask.java @@ -11,15 +11,15 @@ import me.filoghost.fcommons.config.Config; public class v4_0_SettingsUpgradeTask extends YamlUpgradeTask { - public v4_0_SettingsUpgradeTask(ConfigManager configManager) { - super(configManager.getConfigLoader("config.yml")); - } + public v4_0_SettingsUpgradeTask(ConfigManager configManager) { + super(configManager.getConfigLoader("config.yml")); + } - @Override - public void computeYamlChanges(Config settingsConfig) { - removeNode(settingsConfig, "use-only-commands-without-args"); - removeNode(settingsConfig, "use-console-colors"); - removeNode(settingsConfig, "multiple-commands-separator"); - } + @Override + public void computeYamlChanges(Config settingsConfig) { + removeNode(settingsConfig, "use-only-commands-without-args"); + removeNode(settingsConfig, "use-console-colors"); + removeNode(settingsConfig, "multiple-commands-separator"); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/listener/CommandListener.java b/plugin/src/main/java/me/filoghost/chestcommands/listener/CommandListener.java index 883ef95..80c0e62 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/listener/CommandListener.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/listener/CommandListener.java @@ -13,40 +13,40 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; public class CommandListener implements Listener { - - private final MenuManager menuManager; - - public CommandListener(MenuManager menuManager) { - this.menuManager = menuManager; - } + + private final MenuManager menuManager; + + public CommandListener(MenuManager menuManager) { + this.menuManager = menuManager; + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onCommand(PlayerCommandPreprocessEvent event) { - String command = getCommandName(event.getMessage()); - if (command == null) { - return; - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onCommand(PlayerCommandPreprocessEvent event) { + String command = getCommandName(event.getMessage()); + if (command == null) { + return; + } - InternalMenu menu = menuManager.getMenuByOpenCommand(command); - if (menu == null) { - return; - } - - event.setCancelled(true); - menu.openCheckingPermission(event.getPlayer()); - } - - private static String getCommandName(String fullCommand) { - if (!fullCommand.startsWith("/")) { - return null; - } - - int firstSpace = fullCommand.indexOf(' '); - if (firstSpace >= 1) { - return fullCommand.substring(1, firstSpace); - } else { - return fullCommand.substring(1); - } - } + InternalMenu menu = menuManager.getMenuByOpenCommand(command); + if (menu == null) { + return; + } + + event.setCancelled(true); + menu.openCheckingPermission(event.getPlayer()); + } + + private static String getCommandName(String fullCommand) { + if (!fullCommand.startsWith("/")) { + return null; + } + + int firstSpace = fullCommand.indexOf(' '); + if (firstSpace >= 1) { + return fullCommand.substring(1, firstSpace); + } else { + return fullCommand.substring(1); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/listener/InventoryListener.java b/plugin/src/main/java/me/filoghost/chestcommands/listener/InventoryListener.java index faee40a..5dcfb8f 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/listener/InventoryListener.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/listener/InventoryListener.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.listener; +import java.util.Map; +import java.util.WeakHashMap; import me.filoghost.chestcommands.ChestCommands; import me.filoghost.chestcommands.api.ClickResult; import me.filoghost.chestcommands.api.Icon; @@ -21,73 +23,70 @@ import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; -import java.util.Map; -import java.util.WeakHashMap; - public class InventoryListener implements Listener { - private final MenuManager menuManager; - private final Map antiClickSpam; + private final MenuManager menuManager; + private final Map antiClickSpam; - public InventoryListener(MenuManager menuManager) { - this.menuManager = menuManager; - this.antiClickSpam = new WeakHashMap<>(); - } - + public InventoryListener(MenuManager menuManager) { + this.menuManager = menuManager; + this.antiClickSpam = new WeakHashMap<>(); + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) - public void onInteract(PlayerInteractEvent event) { - if (event.hasItem() && event.getAction() != Action.PHYSICAL) { - menuManager.openMenuByItem(event.getPlayer(), event.getItem(), event.getAction()); - } - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) - public void onEarlyInventoryClick(InventoryClickEvent event) { - if (MenuManager.isMenuInventory(event.getInventory())) { - // Cancel the event as early as possible - event.setCancelled(true); - } - } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) - public void onLateInventoryClick(InventoryClickEvent event) { - Inventory inventory = event.getInventory(); - DefaultMenuView menuView = MenuManager.getOpenMenuView(inventory); - if (menuView == null) { - return; - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) + public void onInteract(PlayerInteractEvent event) { + if (event.hasItem() && event.getAction() != Action.PHYSICAL) { + menuManager.openMenuByItem(event.getPlayer(), event.getItem(), event.getAction()); + } + } - // Cancel the event again just in case a plugin un-cancels it - event.setCancelled(true); + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) + public void onEarlyInventoryClick(InventoryClickEvent event) { + if (MenuManager.isMenuInventory(event.getInventory())) { + // Cancel the event as early as possible + event.setCancelled(true); + } + } - int slot = event.getRawSlot(); - Player clicker = (Player) event.getWhoClicked(); - Icon icon = menuView.getIcon(slot); - if (icon == null) { - return; - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + public void onLateInventoryClick(InventoryClickEvent event) { + Inventory inventory = event.getInventory(); + DefaultMenuView menuView = MenuManager.getOpenMenuView(inventory); + if (menuView == null) { + return; + } - Long cooldownUntil = antiClickSpam.get(clicker); - long now = System.currentTimeMillis(); - int minDelay = Settings.anti_click_spam_delay; + // Cancel the event again just in case a plugin un-cancels it + event.setCancelled(true); - if (minDelay > 0) { - if (cooldownUntil != null && cooldownUntil > now) { - return; - } else { - antiClickSpam.put(clicker, now + minDelay); - } - } + int slot = event.getRawSlot(); + Player clicker = (Player) event.getWhoClicked(); + Icon icon = menuView.getIcon(slot); + if (icon == null) { + return; + } - // Only handle the click AFTER the event has finished - Bukkit.getScheduler().runTask(ChestCommands.getPluginInstance(), () -> { - ClickResult result = icon.onClick(menuView, clicker); + Long cooldownUntil = antiClickSpam.get(clicker); + long now = System.currentTimeMillis(); + int minDelay = Settings.anti_click_spam_delay; - if (result == ClickResult.CLOSE) { - clicker.closeInventory(); - } - }); - } + if (minDelay > 0) { + if (cooldownUntil != null && cooldownUntil > now) { + return; + } else { + antiClickSpam.put(clicker, now + minDelay); + } + } + + // Only handle the click AFTER the event has finished + Bukkit.getScheduler().runTask(ChestCommands.getPluginInstance(), () -> { + ClickResult result = icon.onClick(menuView, clicker); + + if (result == ClickResult.CLOSE) { + clicker.closeInventory(); + } + }); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/listener/JoinListener.java b/plugin/src/main/java/me/filoghost/chestcommands/listener/JoinListener.java index 61b986f..716b08e 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/listener/JoinListener.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/listener/JoinListener.java @@ -16,20 +16,20 @@ import org.bukkit.event.player.PlayerJoinEvent; public class JoinListener implements Listener { - @EventHandler - public void onJoin(PlayerJoinEvent event) { - Player player = event.getPlayer(); + @EventHandler + public void onJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); - if (ChestCommands.getLastLoadErrors().hasErrors() && player.hasPermission(Permissions.SEE_ERRORS)) { - player.sendMessage( - ChestCommands.CHAT_PREFIX + ChatColor.RED + "The plugin found " + ChestCommands.getLastLoadErrors().getErrorsCount() - + " error(s) last time it was loaded. You can see them by doing \"/cc reload\" in the console."); - } + if (ChestCommands.getLastLoadErrors().hasErrors() && player.hasPermission(Permissions.SEE_ERRORS)) { + player.sendMessage( + ChestCommands.CHAT_PREFIX + ChatColor.RED + "The plugin found " + ChestCommands.getLastLoadErrors().getErrorsCount() + + " error(s) last time it was loaded. You can see them by doing \"/cc reload\" in the console."); + } - if (ChestCommands.hasNewVersion() && Settings.update_notifications && player.hasPermission(Permissions.UPDATE_NOTIFICATIONS)) { - player.sendMessage(ChestCommands.CHAT_PREFIX + "Found an update: " + ChestCommands.getNewVersion() + ". Download:"); - player.sendMessage(ChatColor.DARK_GREEN + ">> " + ChatColor.GREEN + "http://dev.bukkit.org/bukkit-plugins/chest-commands"); - } - } + if (ChestCommands.hasNewVersion() && Settings.update_notifications && player.hasPermission(Permissions.UPDATE_NOTIFICATIONS)) { + player.sendMessage(ChestCommands.CHAT_PREFIX + "Found an update: " + ChestCommands.getNewVersion() + ". Download:"); + player.sendMessage(ChatColor.DARK_GREEN + ">> " + ChatColor.GREEN + "http://dev.bukkit.org/bukkit-plugins/chest-commands"); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/listener/SignListener.java b/plugin/src/main/java/me/filoghost/chestcommands/listener/SignListener.java index 2a16834..a6607c6 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/listener/SignListener.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/listener/SignListener.java @@ -22,97 +22,97 @@ import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.player.PlayerInteractEvent; public class SignListener implements Listener { - - private static final int HEADER_LINE = 0; - private static final int FILENAME_LINE = 1; - - private static final String SIGN_CREATION_TRIGGER = "[menu]"; - - private static final ChatColor VALID_SIGN_COLOR = ChatColor.DARK_BLUE; - private static final String VALID_SIGN_HEADER = VALID_SIGN_COLOR + SIGN_CREATION_TRIGGER; - - private final MenuManager menuManager; - - public SignListener(MenuManager menuManager) { - this.menuManager = menuManager; - } + + private static final int HEADER_LINE = 0; + private static final int FILENAME_LINE = 1; + + private static final String SIGN_CREATION_TRIGGER = "[menu]"; + + private static final ChatColor VALID_SIGN_COLOR = ChatColor.DARK_BLUE; + private static final String VALID_SIGN_HEADER = VALID_SIGN_COLOR + SIGN_CREATION_TRIGGER; + + private final MenuManager menuManager; + + public SignListener(MenuManager menuManager) { + this.menuManager = menuManager; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSignClick(PlayerInteractEvent event) { - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { - return; - } - - BlockState clickedBlockState = event.getClickedBlock().getState(); - - if (!(clickedBlockState instanceof Sign)) { - return; - } - - Sign sign = (Sign) clickedBlockState; - - if (!sign.getLine(HEADER_LINE).equalsIgnoreCase(VALID_SIGN_HEADER)) { - return; - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSignClick(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { + return; + } + + BlockState clickedBlockState = event.getClickedBlock().getState(); + + if (!(clickedBlockState instanceof Sign)) { + return; + } + + Sign sign = (Sign) clickedBlockState; + + if (!sign.getLine(HEADER_LINE).equalsIgnoreCase(VALID_SIGN_HEADER)) { + return; + } - String menuFileName = Utils.addYamlExtension(sign.getLine(FILENAME_LINE).trim()); - InternalMenu menu = menuManager.getMenuByFileName(menuFileName); - - if (menu == null) { - event.getPlayer().sendMessage(Lang.menu_not_found); - return; - } - - menu.openCheckingPermission(event.getPlayer()); - } + String menuFileName = Utils.addYamlExtension(sign.getLine(FILENAME_LINE).trim()); + InternalMenu menu = menuManager.getMenuByFileName(menuFileName); + + if (menu == null) { + event.getPlayer().sendMessage(Lang.menu_not_found); + return; + } + + menu.openCheckingPermission(event.getPlayer()); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onCreateMenuSign(SignChangeEvent event) { - Player player = event.getPlayer(); + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCreateMenuSign(SignChangeEvent event) { + Player player = event.getPlayer(); - if (isCreatingMenuSign(event.getLine(HEADER_LINE)) && canCreateMenuSign(player)) { - String menuFileName = event.getLine(FILENAME_LINE).trim(); - - if (menuFileName.isEmpty()) { - event.setCancelled(true); - player.sendMessage(ChatColor.RED + "You must write a menu name in the second line."); - return; - } - - menuFileName = Utils.addYamlExtension(menuFileName); - - InternalMenu menu = menuManager.getMenuByFileName(menuFileName); - if (menu == null) { - event.setCancelled(true); - player.sendMessage(ChatColor.RED + "Menu \"" + menuFileName + "\" was not found."); - return; - } - - event.setLine(HEADER_LINE, VALID_SIGN_COLOR + event.getLine(HEADER_LINE)); - player.sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + menuFileName + "."); - } - } + if (isCreatingMenuSign(event.getLine(HEADER_LINE)) && canCreateMenuSign(player)) { + String menuFileName = event.getLine(FILENAME_LINE).trim(); + + if (menuFileName.isEmpty()) { + event.setCancelled(true); + player.sendMessage(ChatColor.RED + "You must write a menu name in the second line."); + return; + } + + menuFileName = Utils.addYamlExtension(menuFileName); + + InternalMenu menu = menuManager.getMenuByFileName(menuFileName); + if (menu == null) { + event.setCancelled(true); + player.sendMessage(ChatColor.RED + "Menu \"" + menuFileName + "\" was not found."); + return; + } + + event.setLine(HEADER_LINE, VALID_SIGN_COLOR + event.getLine(HEADER_LINE)); + player.sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + menuFileName + "."); + } + } - + - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onSignChangeMonitor(SignChangeEvent event) { - // Prevent players without permissions from creating menu signs - if (isValidMenuSign(event.getLine(HEADER_LINE)) && !canCreateMenuSign(event.getPlayer())) { - event.setLine(HEADER_LINE, ChatColor.stripColor(event.getLine(HEADER_LINE))); - } - } - - private boolean isCreatingMenuSign(String headerLine) { - return headerLine.equalsIgnoreCase(SIGN_CREATION_TRIGGER); - } - - private boolean isValidMenuSign(String headerLine) { - return headerLine.equalsIgnoreCase(VALID_SIGN_HEADER); - } - - private boolean canCreateMenuSign(Player player) { - return player.hasPermission(Permissions.SIGN_CREATE); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onSignChangeMonitor(SignChangeEvent event) { + // Prevent players without permissions from creating menu signs + if (isValidMenuSign(event.getLine(HEADER_LINE)) && !canCreateMenuSign(event.getPlayer())) { + event.setLine(HEADER_LINE, ChatColor.stripColor(event.getLine(HEADER_LINE))); + } + } + + private boolean isCreatingMenuSign(String headerLine) { + return headerLine.equalsIgnoreCase(SIGN_CREATION_TRIGGER); + } + + private boolean isValidMenuSign(String headerLine) { + return headerLine.equalsIgnoreCase(VALID_SIGN_HEADER); + } + + private boolean canCreateMenuSign(Player player) { + return player.hasPermission(Permissions.SIGN_CREATE); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/logging/ErrorPrintInfo.java b/plugin/src/main/java/me/filoghost/chestcommands/logging/ErrorPrintInfo.java index 8d966c8..f7b25d5 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/logging/ErrorPrintInfo.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/logging/ErrorPrintInfo.java @@ -9,32 +9,32 @@ import java.util.List; class ErrorPrintInfo { - private final int index; - private final List message; - private final String details; - private final Throwable cause; + private final int index; + private final List message; + private final String details; + private final Throwable cause; - public ErrorPrintInfo(int index, List message, String details, Throwable cause) { - this.index = index; - this.message = message; - this.details = details; - this.cause = cause; - } + public ErrorPrintInfo(int index, List message, String details, Throwable cause) { + this.index = index; + this.message = message; + this.details = details; + this.cause = cause; + } - public int getIndex() { - return index; - } + public int getIndex() { + return index; + } - public List getMessage() { - return message; - } + public List getMessage() { + return message; + } - public String getDetails() { - return details; - } + public String getDetails() { + return details; + } - public Throwable getCause() { - return cause; - } + public Throwable getCause() { + return cause; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/logging/Errors.java b/plugin/src/main/java/me/filoghost/chestcommands/logging/Errors.java index dcbf4c5..b2aedde 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/logging/Errors.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/logging/Errors.java @@ -5,216 +5,215 @@ */ package me.filoghost.chestcommands.logging; +import java.nio.file.Path; import me.filoghost.chestcommands.ChestCommands; import me.filoghost.chestcommands.parsing.icon.AttributeType; import me.filoghost.chestcommands.parsing.icon.IconSettings; import me.filoghost.fcommons.config.ConfigErrors; import org.bukkit.ChatColor; -import java.nio.file.Path; - public class Errors { - public static class Config { + public static class Config { - public static final String createDataFolderIOException = "plugin failed to load, couldn't create data folder"; + public static final String createDataFolderIOException = "plugin failed to load, couldn't create data folder"; - public static String menuListIOException(Path menuFolder) { - return "couldn't fetch menu files inside the folder \"" + menuFolder + "\""; - } + public static String menuListIOException(Path menuFolder) { + return "couldn't fetch menu files inside the folder \"" + menuFolder + "\""; + } - public static String initException(Path file) { - return "error while initializing config file \"" + formatPath(file) + "\""; - } + public static String initException(Path file) { + return "error while initializing config file \"" + formatPath(file) + "\""; + } - public static String emptyPlaceholder(Path configFile) { - return "error in \"" + configFile + "\": placeholder cannot be empty (skipped)."; - } + public static String emptyPlaceholder(Path configFile) { + return "error in \"" + configFile + "\": placeholder cannot be empty (skipped)."; + } - public static String tooLongPlaceholder(Path configFile, String placeholder) { - return "error in \"" + configFile + "\": placeholder cannot be longer than 100 character (" + placeholder + ")."; - } + public static String tooLongPlaceholder(Path configFile, String placeholder) { + return "error in \"" + configFile + "\": placeholder cannot be longer than 100 character (" + placeholder + ")."; + } - } + } - public static class Upgrade { + public static class Upgrade { - public static final String genericExecutorError = "error while running automatic configuration upgrades"; - public static final String menuListIOException = "couldn't obtain a list of menu files"; - public static final String failedSomeUpgrades = "note: one or more automatic upgrades may have not been applied, configuration files or menus may require manual changes"; - public static final String failedToPrepareUpgradeTasks = "error while trying to prepare an automatic configuration upgrade"; + public static final String genericExecutorError = "error while running automatic configuration upgrades"; + public static final String menuListIOException = "couldn't obtain a list of menu files"; + public static final String failedSomeUpgrades = "note: one or more automatic upgrades may have not been applied, configuration files or menus may require manual changes"; + public static final String failedToPrepareUpgradeTasks = "error while trying to prepare an automatic configuration upgrade"; - public static String metadataReadError(Path metadataFile) { - return "couldn't read upgrades metadata file \"" + formatPath(metadataFile) + "\""; - } + public static String metadataReadError(Path metadataFile) { + return "couldn't read upgrades metadata file \"" + formatPath(metadataFile) + "\""; + } - public static String metadataSaveError(Path metadataFile) { - return "couldn't save upgrades metadata file \"" + formatPath(metadataFile) + "\""; - } + public static String metadataSaveError(Path metadataFile) { + return "couldn't save upgrades metadata file \"" + formatPath(metadataFile) + "\""; + } - public static String failedSingleUpgrade(Path file) { - return "error while trying to automatically upgrade \"" + formatPath(file) + "\""; - } + public static String failedSingleUpgrade(Path file) { + return "error while trying to automatically upgrade \"" + formatPath(file) + "\""; + } - public static String loadError(Path file) { - return "couldn't load file to upgrade \"" + formatPath(file) + "\""; - } + public static String loadError(Path file) { + return "couldn't load file to upgrade \"" + formatPath(file) + "\""; + } - public static String backupError(Path file) { - return "couldn't create backup of file \"" + formatPath(file) + "\""; - } + public static String backupError(Path file) { + return "couldn't create backup of file \"" + formatPath(file) + "\""; + } - public static String saveError(Path file) { - return "couldn't save upgraded file \"" + formatPath(file) + "\""; - } + public static String saveError(Path file) { + return "couldn't save upgraded file \"" + formatPath(file) + "\""; + } - } + } - public static class Parsing { + public static class Parsing { - public static final String invalidDecimal = "value is not a valid decimal"; - public static final String invalidShort = "value is not a valid short integer"; - public static final String invalidInteger = "value is not a valid integer"; + public static final String invalidDecimal = "value is not a valid decimal"; + public static final String invalidShort = "value is not a valid short integer"; + public static final String invalidInteger = "value is not a valid integer"; - public static final String strictlyPositive = "value must be greater than zero"; - public static final String zeroOrPositive = "value must be zero or greater"; + public static final String strictlyPositive = "value must be greater than zero"; + public static final String zeroOrPositive = "value must be zero or greater"; - public static final String invalidColorFormat = "value must match the format \"red, green, blue\""; - public static final String invalidPatternFormat = "value must match the format \"pattern:color\""; + public static final String invalidColorFormat = "value must match the format \"red, green, blue\""; + public static final String invalidPatternFormat = "value must match the format \"pattern:color\""; - public static final String unknownAttribute = "unknown attribute"; - public static final String materialCannotBeAir = "material cannot be air"; + public static final String unknownAttribute = "unknown attribute"; + public static final String materialCannotBeAir = "material cannot be air"; - public static String unknownMaterial(String materialString) { - return "unknown material \"" + materialString + "\""; - } + public static String unknownMaterial(String materialString) { + return "unknown material \"" + materialString + "\""; + } - public static String unknownPatternType(String patternTypeString) { - return "unknown pattern type \"" + patternTypeString + "\""; - } + public static String unknownPatternType(String patternTypeString) { + return "unknown pattern type \"" + patternTypeString + "\""; + } - public static String unknownDyeColor(String dyeColorString) { - return "unknown dye color \"" + dyeColorString + "\""; - } + public static String unknownDyeColor(String dyeColorString) { + return "unknown dye color \"" + dyeColorString + "\""; + } - public static String unknownEnchantmentType(String typeString) { - return "unknown enchantment type \"" + typeString + "\""; - } + public static String unknownEnchantmentType(String typeString) { + return "unknown enchantment type \"" + typeString + "\""; + } - public static String invalidEnchantmentLevel(String levelString) { - return "invalid enchantment level \"" + levelString + "\","; - } + public static String invalidEnchantmentLevel(String levelString) { + return "invalid enchantment level \"" + levelString + "\","; + } - public static String invalidDurability(String durabilityString) { - return "invalid durability \"" + durabilityString + "\""; - } + public static String invalidDurability(String durabilityString) { + return "invalid durability \"" + durabilityString + "\""; + } - public static String invalidAmount(String amountString) { - return "invalid amount \"" + amountString + "\""; - } + public static String invalidAmount(String amountString) { + return "invalid amount \"" + amountString + "\""; + } - public static String invalidColorNumber(String numberString, String colorName) { - return "invalid " + colorName + " color \"" + numberString + "\""; - } + public static String invalidColorNumber(String numberString, String colorName) { + return "invalid " + colorName + " color \"" + numberString + "\""; + } - public static String invalidColorRange(String valueString, String colorName) { - return "invalid " + colorName + " color \"" + valueString + "\", value must be between 0 and 255"; - } + public static String invalidColorRange(String valueString, String colorName) { + return "invalid " + colorName + " color \"" + valueString + "\", value must be between 0 and 255"; + } - public static String invalidBossBarTime(String timeString) { - return "invalid dragon bar time \"" + timeString + "\""; - } + public static String invalidBossBarTime(String timeString) { + return "invalid dragon bar time \"" + timeString + "\""; + } - public static String invalidSoundPitch(String pitchString) { - return "invalid sound pitch \"" + pitchString + "\""; - } + public static String invalidSoundPitch(String pitchString) { + return "invalid sound pitch \"" + pitchString + "\""; + } - public static String invalidSoundVolume(String volumeString) { - return "invalid sound volume \"" + volumeString + "\""; - } + public static String invalidSoundVolume(String volumeString) { + return "invalid sound volume \"" + volumeString + "\""; + } - public static String unknownSound(String soundString) { - return "unknown sound \"" + soundString + "\""; - } + public static String unknownSound(String soundString) { + return "unknown sound \"" + soundString + "\""; + } - } + } - public static class Menu { + public static class Menu { - public static String invalidSetting(Path menuFile, String invalidSetting) { - return menuError(menuFile, "has an invalid menu setting \"" + invalidSetting + "\""); - } + public static String invalidSetting(Path menuFile, String invalidSetting) { + return menuError(menuFile, "has an invalid menu setting \"" + invalidSetting + "\""); + } - public static String missingSetting(Path menuFile, String missingSetting) { - return menuError(menuFile, "is missing the menu setting \"" + missingSetting + "\""); - } + public static String missingSetting(Path menuFile, String missingSetting) { + return menuError(menuFile, "is missing the menu setting \"" + missingSetting + "\""); + } - public static String missingSettingsSection(Path menuFile) { - return menuError(menuFile, "is missing the menu setting section"); - } + public static String missingSettingsSection(Path menuFile) { + return menuError(menuFile, "is missing the menu setting section"); + } - public static String invalidSettingListElement(Path menuFile, String invalidSetting, String listElement) { - return menuError(menuFile, - "contains an invalid list element (\"" + listElement + "\") " - + "in the menu setting \"" + invalidSetting + "\""); - } + public static String invalidSettingListElement(Path menuFile, String invalidSetting, String listElement) { + return menuError(menuFile, + "contains an invalid list element (\"" + listElement + "\") " + + "in the menu setting \"" + invalidSetting + "\""); + } - private static String menuError(Path menuFile, String errorMessage) { - return "the menu \"" + formatPath(menuFile) + "\" " + errorMessage; - } + private static String menuError(Path menuFile, String errorMessage) { + return "the menu \"" + formatPath(menuFile) + "\" " + errorMessage; + } - public static String invalidAttribute(IconSettings iconSettings, AttributeType attributeType) { - return invalidAttribute(iconSettings, attributeType.getAttributeName()); - } + public static String invalidAttribute(IconSettings iconSettings, AttributeType attributeType) { + return invalidAttribute(iconSettings, attributeType.getAttributeName()); + } - public static String invalidAttribute(IconSettings iconSettings, String attributeName) { - return iconError(iconSettings, "has an invalid attribute \"" + attributeName + "\""); - } + public static String invalidAttribute(IconSettings iconSettings, String attributeName) { + return iconError(iconSettings, "has an invalid attribute \"" + attributeName + "\""); + } - public static String missingAttribute(IconSettings iconSettings, AttributeType attributeType) { - return iconError(iconSettings, "is missing the attribute \"" + attributeType.getAttributeName() + "\""); - } + public static String missingAttribute(IconSettings iconSettings, AttributeType attributeType) { + return iconError(iconSettings, "is missing the attribute \"" + attributeType.getAttributeName() + "\""); + } - public static String invalidAttributeListElement(IconSettings iconSettings, String attributeName, String listElement) { - return iconError(iconSettings, - "contains an invalid list element (\"" + listElement + "\") " - + "in the attribute \"" + attributeName + "\""); - } + public static String invalidAttributeListElement(IconSettings iconSettings, String attributeName, String listElement) { + return iconError(iconSettings, + "contains an invalid list element (\"" + listElement + "\") " + + "in the attribute \"" + attributeName + "\""); + } - public static String iconOverridesAnother(IconSettings iconSettings) { - return iconError(iconSettings, "is overriding another icon with the same position"); - } + public static String iconOverridesAnother(IconSettings iconSettings) { + return iconError(iconSettings, "is overriding another icon with the same position"); + } - private static String iconError(IconSettings iconSettings, String errorMessage) { - return "the icon \"" + iconSettings.getIconName() + "\" in the menu \"" - + formatPath(iconSettings.getMenuFile()) + "\" " + errorMessage; - } + private static String iconError(IconSettings iconSettings, String errorMessage) { + return "the icon \"" + iconSettings.getIconName() + "\" in the menu \"" + + formatPath(iconSettings.getMenuFile()) + "\" " + errorMessage; + } - public static String duplicateMenuName(Path menuFile1, Path menuFile2) { - return "two menus (\"" + menuFile1 + "\" and \"" + menuFile2 + "\") " - + "have the same file name. Only of them will work when referenced by name"; - } + public static String duplicateMenuName(Path menuFile1, Path menuFile2) { + return "two menus (\"" + menuFile1 + "\" and \"" + menuFile2 + "\") " + + "have the same file name. Only of them will work when referenced by name"; + } - public static String duplicateMenuCommand(Path menuFile1, Path menuFile2, String command) { - return "two menus (\"" + menuFile1 + "\" and \"" + menuFile2 + "\") " - + "have the same command \"" + command + "\". Only one will be opened when the command is executed"; - } - } + public static String duplicateMenuCommand(Path menuFile1, Path menuFile2, String command) { + return "two menus (\"" + menuFile1 + "\" and \"" + menuFile2 + "\") " + + "have the same command \"" + command + "\". Only one will be opened when the command is executed"; + } + } - public static class User { + public static class User { - public static final String notifyStaffRequest = "Please inform the staff."; + public static final String notifyStaffRequest = "Please inform the staff."; - public static String configurationError(String errorMessage) { - return ChatColor.RED + "Error: " + errorMessage + ". " + Errors.User.notifyStaffRequest; - } + public static String configurationError(String errorMessage) { + return ChatColor.RED + "Error: " + errorMessage + ". " + Errors.User.notifyStaffRequest; + } - } + } - private static String formatPath(Path path) { - return ConfigErrors.formatPath(ChestCommands.getDataFolderPath(), path); - } + private static String formatPath(Path path) { + return ConfigErrors.formatPath(ChestCommands.getDataFolderPath(), path); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/logging/MessagePartJoiner.java b/plugin/src/main/java/me/filoghost/chestcommands/logging/MessagePartJoiner.java index ac881dd..eaf18a2 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/logging/MessagePartJoiner.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/logging/MessagePartJoiner.java @@ -5,77 +5,76 @@ */ package me.filoghost.chestcommands.logging; -import me.filoghost.fcommons.Strings; - import java.util.List; +import me.filoghost.fcommons.Strings; class MessagePartJoiner { - private final StringBuilder output; + private final StringBuilder output; - private String previousMessagePart; - private boolean appendedFirstSentenceSeparator; + private String previousMessagePart; + private boolean appendedFirstSentenceSeparator; - public static String join(List messageParts) { - int estimateLength = getEstimateLength(messageParts); - MessagePartJoiner errorMessageBuilder = new MessagePartJoiner(estimateLength); - for (String messagePart : messageParts) { - errorMessageBuilder.append(messagePart); - } - return errorMessageBuilder.build(); - } + public static String join(List messageParts) { + int estimateLength = getEstimateLength(messageParts); + MessagePartJoiner errorMessageBuilder = new MessagePartJoiner(estimateLength); + for (String messagePart : messageParts) { + errorMessageBuilder.append(messagePart); + } + return errorMessageBuilder.build(); + } - private static int getEstimateLength(List messageParts) { - int estimateLength = 0; + private static int getEstimateLength(List messageParts) { + int estimateLength = 0; - // Length of message parts - for (String messagePart : messageParts) { - estimateLength += messagePart.length(); - } + // Length of message parts + for (String messagePart : messageParts) { + estimateLength += messagePart.length(); + } - // Length of separators in between - estimateLength += (messageParts.size() - 1) * 2; + // Length of separators in between + estimateLength += (messageParts.size() - 1) * 2; - return estimateLength; - } + return estimateLength; + } - private MessagePartJoiner(int estimateLength) { - output = new StringBuilder(estimateLength); - } + private MessagePartJoiner(int estimateLength) { + output = new StringBuilder(estimateLength); + } - private void append(String messagePart) { - appendSeparator(); - appendMessagePart(messagePart); + private void append(String messagePart) { + appendSeparator(); + appendMessagePart(messagePart); - previousMessagePart = messagePart; - } + previousMessagePart = messagePart; + } - private void appendMessagePart(String messagePart) { - if (previousMessagePart == null || previousMessagePart.endsWith(".")) { - output.append(Strings.capitalizeFirst(messagePart)); - } else { - output.append(messagePart); - } - } + private void appendMessagePart(String messagePart) { + if (previousMessagePart == null || previousMessagePart.endsWith(".")) { + output.append(Strings.capitalizeFirst(messagePart)); + } else { + output.append(messagePart); + } + } - private void appendSeparator() { - if (previousMessagePart != null) { - if (previousMessagePart.endsWith(".")) { - output.append(" "); - this.appendedFirstSentenceSeparator = false; + private void appendSeparator() { + if (previousMessagePart != null) { + if (previousMessagePart.endsWith(".")) { + output.append(" "); + this.appendedFirstSentenceSeparator = false; - } else if (!appendedFirstSentenceSeparator) { - output.append(": "); - this.appendedFirstSentenceSeparator = true; + } else if (!appendedFirstSentenceSeparator) { + output.append(": "); + this.appendedFirstSentenceSeparator = true; - } else { - output.append(", "); - } - } - } + } else { + output.append(", "); + } + } + } - private String build() { - return output.toString(); - } + private String build() { + return output.toString(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/logging/PrintableErrorCollector.java b/plugin/src/main/java/me/filoghost/chestcommands/logging/PrintableErrorCollector.java index da1e5c1..eb3e2f8 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/logging/PrintableErrorCollector.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/logging/PrintableErrorCollector.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.logging; +import java.util.ArrayList; +import java.util.List; import me.filoghost.chestcommands.ChestCommands; import me.filoghost.chestcommands.legacy.UpgradeExecutorException; import me.filoghost.chestcommands.legacy.upgrade.UpgradeTaskException; @@ -17,74 +19,71 @@ import me.filoghost.fcommons.logging.ErrorLog; import org.bukkit.Bukkit; import org.bukkit.ChatColor; -import java.util.ArrayList; -import java.util.List; - public class PrintableErrorCollector extends ErrorCollector { - @Override - public void logToConsole() { - StringBuilder output = new StringBuilder(); + @Override + public void logToConsole() { + StringBuilder output = new StringBuilder(); - if (errors.size() > 0) { - output.append(ChestCommands.CHAT_PREFIX).append(ChatColor.RED).append("Encountered ").append(errors.size()).append(" error(s) on load:\n"); - output.append(" \n"); + if (errors.size() > 0) { + output.append(ChestCommands.CHAT_PREFIX).append(ChatColor.RED).append("Encountered ").append(errors.size()).append(" error(s) on load:\n"); + output.append(" \n"); - int index = 1; - for (ErrorLog error : errors) { - ErrorPrintInfo printFormat = getErrorPrintInfo(index, error); - printError(output, printFormat); - index++; - } - } + int index = 1; + for (ErrorLog error : errors) { + ErrorPrintInfo printFormat = getErrorPrintInfo(index, error); + printError(output, printFormat); + index++; + } + } - Bukkit.getConsoleSender().sendMessage(output.toString()); - } + Bukkit.getConsoleSender().sendMessage(output.toString()); + } - private ErrorPrintInfo getErrorPrintInfo(int index, ErrorLog error) { - List message = new ArrayList<>(error.getMessage().asList()); - String details = null; - Throwable cause = error.getCause(); + private ErrorPrintInfo getErrorPrintInfo(int index, ErrorLog error) { + List message = new ArrayList<>(error.getMessage().asList()); + String details = null; + Throwable cause = error.getCause(); - // Recursively inspect the cause until an unknown or null exception is found - while (true) { - if (cause instanceof ConfigSyntaxException) { - message.add(cause.getMessage()); - details = ((ConfigSyntaxException) cause).getParsingErrorDetails(); - cause = null; // Do not print stacktrace for syntax exceptions + // Recursively inspect the cause until an unknown or null exception is found + while (true) { + if (cause instanceof ConfigSyntaxException) { + message.add(cause.getMessage()); + details = ((ConfigSyntaxException) cause).getParsingErrorDetails(); + cause = null; // Do not print stacktrace for syntax exceptions - } else if (cause instanceof ConfigException - || cause instanceof ParseException - || cause instanceof UpgradeTaskException - || cause instanceof UpgradeExecutorException) { - message.add(cause.getMessage()); - cause = cause.getCause(); // Print the cause (or nothing if null), not our "known" exception + } else if (cause instanceof ConfigException + || cause instanceof ParseException + || cause instanceof UpgradeTaskException + || cause instanceof UpgradeExecutorException) { + message.add(cause.getMessage()); + cause = cause.getCause(); // Print the cause (or nothing if null), not our "known" exception - } else { - return new ErrorPrintInfo(index, message, details, cause); - } - } - } + } else { + return new ErrorPrintInfo(index, message, details, cause); + } + } + } - private static void printError(StringBuilder output, ErrorPrintInfo error) { - output.append(ChatColor.YELLOW).append(error.getIndex()).append(") "); - output.append(ChatColor.WHITE).append(MessagePartJoiner.join(error.getMessage())); + private static void printError(StringBuilder output, ErrorPrintInfo error) { + output.append(ChatColor.YELLOW).append(error.getIndex()).append(") "); + output.append(ChatColor.WHITE).append(MessagePartJoiner.join(error.getMessage())); - if (error.getDetails() != null) { - output.append(". Details:\n"); - output.append(ChatColor.YELLOW).append(error.getDetails()).append("\n"); - } else { - output.append(".\n"); - } - if (error.getCause() != null) { - output.append(ChatColor.DARK_GRAY); - output.append("--------[ Exception details ]--------\n"); - output.append(CommonsUtil.getStackTraceString(error.getCause())); - output.append("-------------------------------------\n"); - } - output.append(" \n"); - output.append(ChatColor.RESET); - } + if (error.getDetails() != null) { + output.append(". Details:\n"); + output.append(ChatColor.YELLOW).append(error.getDetails()).append("\n"); + } else { + output.append(".\n"); + } + if (error.getCause() != null) { + output.append(ChatColor.DARK_GRAY); + output.append("--------[ Exception details ]--------\n"); + output.append(CommonsUtil.getStackTraceString(error.getCause())); + output.append("-------------------------------------\n"); + } + output.append(" \n"); + output.append(ChatColor.RESET); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/menu/APIMenu.java b/plugin/src/main/java/me/filoghost/chestcommands/menu/APIMenu.java index cac7eac..00a6dee 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/menu/APIMenu.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/menu/APIMenu.java @@ -10,16 +10,16 @@ import org.bukkit.plugin.Plugin; public class APIMenu extends BaseMenu { - private final Plugin owner; - - public APIMenu(Plugin owner, String title, int rows) { - super(title, rows); - Preconditions.notNull(owner, "owner"); - this.owner = owner; - } + private final Plugin owner; + + public APIMenu(Plugin owner, String title, int rows) { + super(title, rows); + Preconditions.notNull(owner, "owner"); + this.owner = owner; + } - public Plugin getOwner() { - return owner; - } + public Plugin getOwner() { + return owner; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/menu/BaseMenu.java b/plugin/src/main/java/me/filoghost/chestcommands/menu/BaseMenu.java index df85c5b..b70480b 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/menu/BaseMenu.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/menu/BaseMenu.java @@ -18,62 +18,62 @@ import org.bukkit.entity.Player; public abstract class BaseMenu implements Menu { - protected final String title; - protected final Grid icons; + protected final String title; + protected final Grid icons; - public BaseMenu(String title, int rows) { - Preconditions.notNull(title, "title"); - Preconditions.checkArgument(rows > 0, "rows must be greater than 0"); - this.title = title; - this.icons = new ArrayGrid<>(rows, 9); - } + public BaseMenu(String title, int rows) { + Preconditions.notNull(title, "title"); + Preconditions.checkArgument(rows > 0, "rows must be greater than 0"); + this.title = title; + this.icons = new ArrayGrid<>(rows, 9); + } - @Override - public void setIcon(int row, int column, Icon icon) { - icons.set(row, column, icon); - } + @Override + public void setIcon(int row, int column, Icon icon) { + icons.set(row, column, icon); + } - @Override - public Icon getIcon(int row, int column) { - return icons.get(row, column); - } + @Override + public Icon getIcon(int row, int column) { + return icons.get(row, column); + } - @Override - public int getRowCount() { - return icons.getRows(); - } - - @Override - public int getColumnCount() { - return icons.getColumns(); - } + @Override + public int getRowCount() { + return icons.getRows(); + } + + @Override + public int getColumnCount() { + return icons.getColumns(); + } - @Override - public String getTitle() { - return title; - } + @Override + public String getTitle() { + return title; + } - public Grid getIcons() { - return icons; - } + public Grid getIcons() { + return icons; + } - @Override - public MenuView open(Player player) { - Preconditions.notNull(player, "player"); + @Override + public MenuView open(Player player) { + Preconditions.notNull(player, "player"); - DefaultMenuView menuView = new DefaultMenuView(this, player); - menuView.open(player); - return menuView; - } + DefaultMenuView menuView = new DefaultMenuView(this, player); + menuView.open(player); + return menuView; + } - @Override - public void refreshMenuViews() { - for (Player player : Bukkit.getOnlinePlayers()) { - DefaultMenuView menuView = MenuManager.getOpenMenuView(player); - if (menuView != null && menuView.getMenu() == this) { - menuView.refresh(); - } - } - } + @Override + public void refreshMenuViews() { + for (Player player : Bukkit.getOnlinePlayers()) { + DefaultMenuView menuView = MenuManager.getOpenMenuView(player); + if (menuView != null && menuView.getMenu() == this) { + menuView.refresh(); + } + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/menu/InternalMenu.java b/plugin/src/main/java/me/filoghost/chestcommands/menu/InternalMenu.java index 6e72838..f62da51 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/menu/InternalMenu.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/menu/InternalMenu.java @@ -6,6 +6,8 @@ package me.filoghost.chestcommands.menu; import com.google.common.collect.ImmutableList; +import java.nio.file.Path; +import java.util.List; import me.filoghost.chestcommands.Permissions; import me.filoghost.chestcommands.action.Action; import me.filoghost.chestcommands.api.MenuView; @@ -14,67 +16,64 @@ import me.filoghost.fcommons.collection.CollectionUtils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.nio.file.Path; -import java.util.List; - public class InternalMenu extends BaseMenu { - private final Path sourceFile; - private final String openPermission; - - private ImmutableList openActions; - private int refreshTicks; + private final Path sourceFile; + private final String openPermission; - public InternalMenu(String title, int rows, Path sourceFile) { - super(title, rows); - this.sourceFile = sourceFile; - this.openPermission = Permissions.OPEN_MENU_PREFIX + sourceFile.getFileName(); - } + private ImmutableList openActions; + private int refreshTicks; - public Path getSourceFile() { - return sourceFile; - } + public InternalMenu(String title, int rows, Path sourceFile) { + super(title, rows); + this.sourceFile = sourceFile; + this.openPermission = Permissions.OPEN_MENU_PREFIX + sourceFile.getFileName(); + } - public void setOpenActions(List openAction) { - this.openActions = CollectionUtils.immutableCopy(openAction); - } + public Path getSourceFile() { + return sourceFile; + } - public String getOpenPermission() { - return openPermission; - } + public void setOpenActions(List openAction) { + this.openActions = CollectionUtils.immutableCopy(openAction); + } - public int getRefreshTicks() { - return refreshTicks; - } + public String getOpenPermission() { + return openPermission; + } - public void setRefreshTicks(int refreshTicks) { - this.refreshTicks = refreshTicks; - } + public int getRefreshTicks() { + return refreshTicks; + } - @Override - public MenuView open(Player player) { - if (openActions != null) { - for (Action openAction : openActions) { - openAction.execute(player); - } - } + public void setRefreshTicks(int refreshTicks) { + this.refreshTicks = refreshTicks; + } - return super.open(player); - } - - public void openCheckingPermission(Player player) { - if (player.hasPermission(openPermission)) { - open(player); - } else { - sendNoOpenPermissionMessage(player); - } - } + @Override + public MenuView open(Player player) { + if (openActions != null) { + for (Action openAction : openActions) { + openAction.execute(player); + } + } - public void sendNoOpenPermissionMessage(CommandSender sender) { - String noPermMessage = Lang.no_open_permission; - if (noPermMessage != null && !noPermMessage.isEmpty()) { - sender.sendMessage(noPermMessage.replace("{permission}", this.openPermission)); - } - } + return super.open(player); + } + + public void openCheckingPermission(Player player) { + if (player.hasPermission(openPermission)) { + open(player); + } else { + sendNoOpenPermissionMessage(player); + } + } + + public void sendNoOpenPermissionMessage(CommandSender sender) { + String noPermMessage = Lang.no_open_permission; + if (noPermMessage != null && !noPermMessage.isEmpty()) { + sender.sendMessage(noPermMessage.replace("{permission}", this.openPermission)); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/menu/MenuManager.java b/plugin/src/main/java/me/filoghost/chestcommands/menu/MenuManager.java index 8a357f5..52795f7 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/menu/MenuManager.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/menu/MenuManager.java @@ -5,6 +5,10 @@ */ package me.filoghost.chestcommands.menu; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import me.filoghost.chestcommands.inventory.DefaultMenuView; import me.filoghost.chestcommands.inventory.MenuInventoryHolder; import me.filoghost.chestcommands.logging.Errors; @@ -18,110 +22,105 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - public class MenuManager { - - private static Map menusByFile; - private static Map menusByOpenCommand; - private static Map menusByOpenItem; - - public MenuManager() { - menusByFile = new CaseInsensitiveMap<>(); - menusByOpenCommand = new CaseInsensitiveMap<>(); - menusByOpenItem = new HashMap<>(); - } - - public void clear() { - menusByFile.clear(); - menusByOpenCommand.clear(); - menusByOpenItem.clear(); - } - public InternalMenu getMenuByFileName(String fileName) { - return menusByFile.get(fileName); - } + private static Map menusByFile; + private static Map menusByOpenCommand; + private static Map menusByOpenItem; - public void registerMenu(LoadedMenu loadedMenu, ErrorCollector errorCollector) { - InternalMenu menu = loadedMenu.getMenu(); + public MenuManager() { + menusByFile = new CaseInsensitiveMap<>(); + menusByOpenCommand = new CaseInsensitiveMap<>(); + menusByOpenItem = new HashMap<>(); + } - String fileName = loadedMenu.getSourceFile().getFileName().toString(); - InternalMenu sameNameMenu = menusByFile.get(fileName); - if (sameNameMenu != null) { - errorCollector.add(Errors.Menu.duplicateMenuName(sameNameMenu.getSourceFile(), loadedMenu.getSourceFile())); - } - menusByFile.put(fileName, menu); + public void clear() { + menusByFile.clear(); + menusByOpenCommand.clear(); + menusByOpenItem.clear(); + } - if (loadedMenu.getOpenCommands() != null) { - for (String openCommand : loadedMenu.getOpenCommands()) { - if (!openCommand.isEmpty()) { - InternalMenu sameCommandMenu = menusByOpenCommand.get(openCommand); - if (sameCommandMenu != null) { - errorCollector.add(Errors.Menu.duplicateMenuCommand(sameCommandMenu.getSourceFile(), loadedMenu.getSourceFile(), openCommand)); - } - menusByOpenCommand.put(openCommand, menu); - } - } - } + public InternalMenu getMenuByFileName(String fileName) { + return menusByFile.get(fileName); + } - if (loadedMenu.getOpenItem() != null) { - menusByOpenItem.put(loadedMenu.getOpenItem(), menu); - } - } + public void registerMenu(LoadedMenu loadedMenu, ErrorCollector errorCollector) { + InternalMenu menu = loadedMenu.getMenu(); - public void openMenuByItem(Player player, ItemStack itemInHand, Action clickAction) { - menusByOpenItem.forEach((openItem, menu) -> { - if (openItem.matches(itemInHand, clickAction)) { - menu.openCheckingPermission(player); - } - }); - } + String fileName = loadedMenu.getSourceFile().getFileName().toString(); + InternalMenu sameNameMenu = menusByFile.get(fileName); + if (sameNameMenu != null) { + errorCollector.add(Errors.Menu.duplicateMenuName(sameNameMenu.getSourceFile(), loadedMenu.getSourceFile())); + } + menusByFile.put(fileName, menu); - public InternalMenu getMenuByOpenCommand(String openCommand) { - return menusByOpenCommand.get(openCommand); - } + if (loadedMenu.getOpenCommands() != null) { + for (String openCommand : loadedMenu.getOpenCommands()) { + if (!openCommand.isEmpty()) { + InternalMenu sameCommandMenu = menusByOpenCommand.get(openCommand); + if (sameCommandMenu != null) { + errorCollector.add(Errors.Menu.duplicateMenuCommand(sameCommandMenu.getSourceFile(), loadedMenu.getSourceFile(), openCommand)); + } + menusByOpenCommand.put(openCommand, menu); + } + } + } - public Collection getMenuFileNames() { - return Collections.unmodifiableCollection(menusByFile.keySet()); - } - - public static boolean isMenuInventory(Inventory inventory) { - return getMenuInventoryHolder(inventory) != null; - } + if (loadedMenu.getOpenItem() != null) { + menusByOpenItem.put(loadedMenu.getOpenItem(), menu); + } + } - public static DefaultMenuView getOpenMenuView(Player player) { - InventoryView view = player.getOpenInventory(); - if (view == null) { - return null; - } + public void openMenuByItem(Player player, ItemStack itemInHand, Action clickAction) { + menusByOpenItem.forEach((openItem, menu) -> { + if (openItem.matches(itemInHand, clickAction)) { + menu.openCheckingPermission(player); + } + }); + } - DefaultMenuView menuView = getOpenMenuView(view.getTopInventory()); - if (menuView == null) { - menuView = getOpenMenuView(view.getBottomInventory()); - } - - return menuView; - } - - - public static DefaultMenuView getOpenMenuView(Inventory inventory) { - MenuInventoryHolder inventoryHolder = getMenuInventoryHolder(inventory); - if (inventoryHolder != null) { - return inventoryHolder.getMenuView(); - } else { - return null; - } - } - - private static MenuInventoryHolder getMenuInventoryHolder(Inventory inventory) { - if (inventory.getHolder() instanceof MenuInventoryHolder) { - return (MenuInventoryHolder) inventory.getHolder(); - } else { - return null; - } - } + public InternalMenu getMenuByOpenCommand(String openCommand) { + return menusByOpenCommand.get(openCommand); + } + + public Collection getMenuFileNames() { + return Collections.unmodifiableCollection(menusByFile.keySet()); + } + + public static boolean isMenuInventory(Inventory inventory) { + return getMenuInventoryHolder(inventory) != null; + } + + public static DefaultMenuView getOpenMenuView(Player player) { + InventoryView view = player.getOpenInventory(); + if (view == null) { + return null; + } + + DefaultMenuView menuView = getOpenMenuView(view.getTopInventory()); + if (menuView == null) { + menuView = getOpenMenuView(view.getBottomInventory()); + } + + return menuView; + } + + + public static DefaultMenuView getOpenMenuView(Inventory inventory) { + MenuInventoryHolder inventoryHolder = getMenuInventoryHolder(inventory); + if (inventoryHolder != null) { + return inventoryHolder.getMenuView(); + } else { + return null; + } + } + + private static MenuInventoryHolder getMenuInventoryHolder(Inventory inventory) { + if (inventory.getHolder() instanceof MenuInventoryHolder) { + return (MenuInventoryHolder) inventory.getHolder(); + } else { + return null; + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/ActionParser.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/ActionParser.java index dac98ac..a946162 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/ActionParser.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/ActionParser.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.parsing; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import me.filoghost.chestcommands.action.Action; import me.filoghost.chestcommands.action.BroadcastAction; import me.filoghost.chestcommands.action.ChangeServerAction; @@ -18,55 +20,52 @@ import me.filoghost.chestcommands.action.PlaySoundAction; import me.filoghost.chestcommands.action.PlayerCommandAction; import me.filoghost.chestcommands.action.SendMessageAction; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - public class ActionParser { - public static Action parse(String serializedAction) throws ParseException { - for (ActionType actionType : ActionType.values()) { - Matcher matcher = actionType.prefixPattern.matcher(serializedAction); - if (matcher.find()) { - // Remove the action prefix and trim the spaces - serializedAction = matcher.replaceFirst("").trim(); - return actionType.actionFactory.create(serializedAction); - } - } + public static Action parse(String serializedAction) throws ParseException { + for (ActionType actionType : ActionType.values()) { + Matcher matcher = actionType.prefixPattern.matcher(serializedAction); + if (matcher.find()) { + // Remove the action prefix and trim the spaces + serializedAction = matcher.replaceFirst("").trim(); + return actionType.actionFactory.create(serializedAction); + } + } - return new PlayerCommandAction(serializedAction); // Default action, no match found - } + return new PlayerCommandAction(serializedAction); // Default action, no match found + } - private enum ActionType { + private enum ActionType { - CONSOLE_COMMAND("console", ConsoleCommandAction::new), - OP_COMMAND("op", OpCommandAction::new), - OPEN("open", OpenMenuAction::new), - SERVER("server", ChangeServerAction::new), // The colon is optional - TELL("tell", SendMessageAction::new), - BROADCAST("broadcast", BroadcastAction::new), - GIVE_ITEM("give", GiveItemAction::new), - GIVE_MONEY("give-money", GiveMoneyAction::new), - SOUND("sound", PlaySoundAction::new), - BOSS_BAR("dragon-bar", DragonBarAction::new); + CONSOLE_COMMAND("console", ConsoleCommandAction::new), + OP_COMMAND("op", OpCommandAction::new), + OPEN("open", OpenMenuAction::new), + SERVER("server", ChangeServerAction::new), // The colon is optional + TELL("tell", SendMessageAction::new), + BROADCAST("broadcast", BroadcastAction::new), + GIVE_ITEM("give", GiveItemAction::new), + GIVE_MONEY("give-money", GiveMoneyAction::new), + SOUND("sound", PlaySoundAction::new), + BOSS_BAR("dragon-bar", DragonBarAction::new); - private final Pattern prefixPattern; - private final ActionFactory actionFactory; + private final Pattern prefixPattern; + private final ActionFactory actionFactory; - ActionType(String prefix, ActionFactory actionFactory) { - // Non-default actions must match the format "{prefix}: {content}" - this.prefixPattern = Pattern.compile("^" + Pattern.quote(prefix) + ":", Pattern.CASE_INSENSITIVE); - this.actionFactory = actionFactory; - } + ActionType(String prefix, ActionFactory actionFactory) { + // Non-default actions must match the format "{prefix}: {content}" + this.prefixPattern = Pattern.compile("^" + Pattern.quote(prefix) + ":", Pattern.CASE_INSENSITIVE); + this.actionFactory = actionFactory; + } - @FunctionalInterface - private interface ActionFactory { + @FunctionalInterface + private interface ActionFactory { - Action create(String serializedAction) throws ParseException; + Action create(String serializedAction) throws ParseException; - } + } - } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/EnchantmentParser.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/EnchantmentParser.java index fd7ab79..bf59312 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/EnchantmentParser.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/EnchantmentParser.java @@ -5,89 +5,88 @@ */ package me.filoghost.chestcommands.parsing; +import java.util.Optional; import me.filoghost.chestcommands.logging.Errors; import me.filoghost.fcommons.Strings; import me.filoghost.fcommons.collection.Registry; import org.bukkit.enchantments.Enchantment; -import java.util.Optional; - public class EnchantmentParser { - private static final Registry ENCHANTMENTS_REGISTRY; + private static final Registry ENCHANTMENTS_REGISTRY; - static { - ENCHANTMENTS_REGISTRY = Registry.fromValues(Enchantment.values(), Enchantment::getName); - - // Add aliases - ENCHANTMENTS_REGISTRY.put("Protection", Enchantment.PROTECTION_ENVIRONMENTAL); - ENCHANTMENTS_REGISTRY.put("Fire Protection", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS_REGISTRY.put("Feather Falling", Enchantment.PROTECTION_FALL); - ENCHANTMENTS_REGISTRY.put("Blast Protection", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS_REGISTRY.put("Projectile Protection", Enchantment.PROTECTION_PROJECTILE); - ENCHANTMENTS_REGISTRY.put("Respiration", Enchantment.OXYGEN); - ENCHANTMENTS_REGISTRY.put("Aqua Affinity", Enchantment.WATER_WORKER); - ENCHANTMENTS_REGISTRY.put("Thorns", Enchantment.THORNS); - ENCHANTMENTS_REGISTRY.put("Sharpness", Enchantment.DAMAGE_ALL); - ENCHANTMENTS_REGISTRY.put("Smite", Enchantment.DAMAGE_UNDEAD); - ENCHANTMENTS_REGISTRY.put("Bane Of Arthropods", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS_REGISTRY.put("Knockback", Enchantment.KNOCKBACK); - ENCHANTMENTS_REGISTRY.put("Fire Aspect", Enchantment.FIRE_ASPECT); - ENCHANTMENTS_REGISTRY.put("Looting", Enchantment.LOOT_BONUS_MOBS); - ENCHANTMENTS_REGISTRY.put("Efficiency", Enchantment.DIG_SPEED); - ENCHANTMENTS_REGISTRY.put("Silk Touch", Enchantment.SILK_TOUCH); - ENCHANTMENTS_REGISTRY.put("Unbreaking", Enchantment.DURABILITY); - ENCHANTMENTS_REGISTRY.put("Fortune", Enchantment.LOOT_BONUS_BLOCKS); - ENCHANTMENTS_REGISTRY.put("Power", Enchantment.ARROW_DAMAGE); - ENCHANTMENTS_REGISTRY.put("Punch", Enchantment.ARROW_KNOCKBACK); - ENCHANTMENTS_REGISTRY.put("Flame", Enchantment.ARROW_FIRE); - ENCHANTMENTS_REGISTRY.put("Infinity", Enchantment.ARROW_INFINITE); - ENCHANTMENTS_REGISTRY.put("Lure", Enchantment.LURE); - ENCHANTMENTS_REGISTRY.put("Luck Of The Sea", Enchantment.LUCK); - } + static { + ENCHANTMENTS_REGISTRY = Registry.fromValues(Enchantment.values(), Enchantment::getName); - public static EnchantmentDetails parseEnchantment(String input) throws ParseException { - int level = 1; + // Add aliases + ENCHANTMENTS_REGISTRY.put("Protection", Enchantment.PROTECTION_ENVIRONMENTAL); + ENCHANTMENTS_REGISTRY.put("Fire Protection", Enchantment.PROTECTION_FIRE); + ENCHANTMENTS_REGISTRY.put("Feather Falling", Enchantment.PROTECTION_FALL); + ENCHANTMENTS_REGISTRY.put("Blast Protection", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS_REGISTRY.put("Projectile Protection", Enchantment.PROTECTION_PROJECTILE); + ENCHANTMENTS_REGISTRY.put("Respiration", Enchantment.OXYGEN); + ENCHANTMENTS_REGISTRY.put("Aqua Affinity", Enchantment.WATER_WORKER); + ENCHANTMENTS_REGISTRY.put("Thorns", Enchantment.THORNS); + ENCHANTMENTS_REGISTRY.put("Sharpness", Enchantment.DAMAGE_ALL); + ENCHANTMENTS_REGISTRY.put("Smite", Enchantment.DAMAGE_UNDEAD); + ENCHANTMENTS_REGISTRY.put("Bane Of Arthropods", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS_REGISTRY.put("Knockback", Enchantment.KNOCKBACK); + ENCHANTMENTS_REGISTRY.put("Fire Aspect", Enchantment.FIRE_ASPECT); + ENCHANTMENTS_REGISTRY.put("Looting", Enchantment.LOOT_BONUS_MOBS); + ENCHANTMENTS_REGISTRY.put("Efficiency", Enchantment.DIG_SPEED); + ENCHANTMENTS_REGISTRY.put("Silk Touch", Enchantment.SILK_TOUCH); + ENCHANTMENTS_REGISTRY.put("Unbreaking", Enchantment.DURABILITY); + ENCHANTMENTS_REGISTRY.put("Fortune", Enchantment.LOOT_BONUS_BLOCKS); + ENCHANTMENTS_REGISTRY.put("Power", Enchantment.ARROW_DAMAGE); + ENCHANTMENTS_REGISTRY.put("Punch", Enchantment.ARROW_KNOCKBACK); + ENCHANTMENTS_REGISTRY.put("Flame", Enchantment.ARROW_FIRE); + ENCHANTMENTS_REGISTRY.put("Infinity", Enchantment.ARROW_INFINITE); + ENCHANTMENTS_REGISTRY.put("Lure", Enchantment.LURE); + ENCHANTMENTS_REGISTRY.put("Luck Of The Sea", Enchantment.LUCK); + } - if (input.contains(",")) { - String[] levelSplit = Strings.trimmedSplit(input, ",", 2); + public static EnchantmentDetails parseEnchantment(String input) throws ParseException { + int level = 1; - try { - level = NumberParser.getStrictlyPositiveInteger(levelSplit[1]); - } catch (ParseException e) { - throw new ParseException(Errors.Parsing.invalidEnchantmentLevel(levelSplit[1]), e); - } - input = levelSplit[0]; - } + if (input.contains(",")) { + String[] levelSplit = Strings.trimmedSplit(input, ",", 2); - Optional enchantment = ENCHANTMENTS_REGISTRY.find(input); + try { + level = NumberParser.getStrictlyPositiveInteger(levelSplit[1]); + } catch (ParseException e) { + throw new ParseException(Errors.Parsing.invalidEnchantmentLevel(levelSplit[1]), e); + } + input = levelSplit[0]; + } - if (enchantment.isPresent()) { - return new EnchantmentDetails(enchantment.get(), level); - } else { - throw new ParseException(Errors.Parsing.unknownEnchantmentType(input)); - } - } - - - public static class EnchantmentDetails { - - private final Enchantment enchantment; - private final int level; - - private EnchantmentDetails(Enchantment enchantment, int level) { - this.enchantment = enchantment; - this.level = level; - } + Optional enchantment = ENCHANTMENTS_REGISTRY.find(input); - public Enchantment getEnchantment() { - return enchantment; - } + if (enchantment.isPresent()) { + return new EnchantmentDetails(enchantment.get(), level); + } else { + throw new ParseException(Errors.Parsing.unknownEnchantmentType(input)); + } + } - public int getLevel() { - return level; - } - - } + + public static class EnchantmentDetails { + + private final Enchantment enchantment; + private final int level; + + private EnchantmentDetails(Enchantment enchantment, int level) { + this.enchantment = enchantment; + this.level = level; + } + + public Enchantment getEnchantment() { + return enchantment; + } + + public int getLevel() { + return level; + } + + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/ItemMetaParser.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/ItemMetaParser.java index ec233c1..f6ab85b 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/ItemMetaParser.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/ItemMetaParser.java @@ -14,58 +14,58 @@ import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; public final class ItemMetaParser { - - private static final Registry DYE_COLORS_REGISTRY = Registry.fromEnumValues(DyeColor.class); - private static final Registry PATTERN_TYPES_REGISTRY = Registry.fromEnumValues(PatternType.class); - private ItemMetaParser() {} + private static final Registry DYE_COLORS_REGISTRY = Registry.fromEnumValues(DyeColor.class); + private static final Registry PATTERN_TYPES_REGISTRY = Registry.fromEnumValues(PatternType.class); - - public static Color parseRGBColor(String input) throws ParseException { - String[] split = Strings.trimmedSplit(input, ","); + private ItemMetaParser() {} - if (split.length != 3) { - throw new ParseException(Errors.Parsing.invalidColorFormat); - } - int red = parseColor(split[0], "red"); - int green = parseColor(split[1], "green"); - int blue = parseColor(split[2], "blue"); + public static Color parseRGBColor(String input) throws ParseException { + String[] split = Strings.trimmedSplit(input, ","); - return Color.fromRGB(red, green, blue); - } + if (split.length != 3) { + throw new ParseException(Errors.Parsing.invalidColorFormat); + } - private static int parseColor(String valueString, String colorName) throws ParseException { - int value; + int red = parseColor(split[0], "red"); + int green = parseColor(split[1], "green"); + int blue = parseColor(split[2], "blue"); - try { - value = NumberParser.getInteger(valueString); - } catch (ParseException e) { - throw new ParseException(Errors.Parsing.invalidColorNumber(valueString, colorName), e); - } + return Color.fromRGB(red, green, blue); + } - if (value < 0 || value > 255) { - throw new ParseException(Errors.Parsing.invalidColorRange(valueString, colorName)); - } + private static int parseColor(String valueString, String colorName) throws ParseException { + int value; - return value; - } + try { + value = NumberParser.getInteger(valueString); + } catch (ParseException e) { + throw new ParseException(Errors.Parsing.invalidColorNumber(valueString, colorName), e); + } - public static DyeColor parseDyeColor(String input) throws ParseException { - return DYE_COLORS_REGISTRY.find(input) - .orElseThrow(() -> new ParseException(Errors.Parsing.unknownDyeColor(input))); - } + if (value < 0 || value > 255) { + throw new ParseException(Errors.Parsing.invalidColorRange(valueString, colorName)); + } - public static Pattern parseBannerPattern(String input) throws ParseException { - String[] split = Strings.trimmedSplit(input, ":"); - if (split.length != 2) { - throw new ParseException(Errors.Parsing.invalidPatternFormat); - } + return value; + } - PatternType patternType = PATTERN_TYPES_REGISTRY.find(split[0]) - .orElseThrow(() -> new ParseException(Errors.Parsing.unknownPatternType(split[0]))); - DyeColor patternColor = parseDyeColor(split[1]); + public static DyeColor parseDyeColor(String input) throws ParseException { + return DYE_COLORS_REGISTRY.find(input) + .orElseThrow(() -> new ParseException(Errors.Parsing.unknownDyeColor(input))); + } - return new Pattern(patternColor, patternType); - } + public static Pattern parseBannerPattern(String input) throws ParseException { + String[] split = Strings.trimmedSplit(input, ":"); + if (split.length != 2) { + throw new ParseException(Errors.Parsing.invalidPatternFormat); + } + + PatternType patternType = PATTERN_TYPES_REGISTRY.find(split[0]) + .orElseThrow(() -> new ParseException(Errors.Parsing.unknownPatternType(split[0]))); + DyeColor patternColor = parseDyeColor(split[1]); + + return new Pattern(patternColor, patternType); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/ItemStackParser.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/ItemStackParser.java index d9613e2..9467092 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/ItemStackParser.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/ItemStackParser.java @@ -14,77 +14,77 @@ import org.bukkit.inventory.ItemStack; public class ItemStackParser { - private final Material material; - private int amount = 1; - private short durability = 0; - private boolean hasExplicitDurability = false; + private final Material material; + private int amount = 1; + private short durability = 0; + private boolean hasExplicitDurability = false; - /** - * Reads item in the format "material:durability, amount". - */ - public ItemStackParser(String input, boolean parseAmount) throws ParseException { - Preconditions.notNull(input, "input"); + /** + * Reads item in the format "material:durability, amount". + */ + public ItemStackParser(String input, boolean parseAmount) throws ParseException { + Preconditions.notNull(input, "input"); - if (parseAmount) { - // Read the optional amount - String[] splitAmount = Strings.trimmedSplit(input, ",", 2); + if (parseAmount) { + // Read the optional amount + String[] splitAmount = Strings.trimmedSplit(input, ",", 2); - if (splitAmount.length > 1) { - try { - this.amount = NumberParser.getStrictlyPositiveInteger(splitAmount[1]); - } catch (ParseException e) { - throw new ParseException(Errors.Parsing.invalidAmount(splitAmount[1]), e); - } + if (splitAmount.length > 1) { + try { + this.amount = NumberParser.getStrictlyPositiveInteger(splitAmount[1]); + } catch (ParseException e) { + throw new ParseException(Errors.Parsing.invalidAmount(splitAmount[1]), e); + } - // Only keep the first part as input - input = splitAmount[0]; - } - } + // Only keep the first part as input + input = splitAmount[0]; + } + } - // Read the optional durability - String[] splitByColons = Strings.trimmedSplit(input, ":", 2); + // Read the optional durability + String[] splitByColons = Strings.trimmedSplit(input, ":", 2); - if (splitByColons.length > 1) { - try { - this.durability = NumberParser.getPositiveShort(splitByColons[1]); - } catch (ParseException e) { - throw new ParseException(Errors.Parsing.invalidDurability(splitByColons[1]), e); - } + if (splitByColons.length > 1) { + try { + this.durability = NumberParser.getPositiveShort(splitByColons[1]); + } catch (ParseException e) { + throw new ParseException(Errors.Parsing.invalidDurability(splitByColons[1]), e); + } - this.hasExplicitDurability = true; + this.hasExplicitDurability = true; - // Only keep the first part as input - input = splitByColons[0]; - } + // Only keep the first part as input + input = splitByColons[0]; + } - this.material = MaterialParser.parseMaterial(input); - } + this.material = MaterialParser.parseMaterial(input); + } - public void checkNotAir() throws ParseException { - if (MaterialsHelper.isAir(material)) { - throw new ParseException(Errors.Parsing.materialCannotBeAir); - } - } + public void checkNotAir() throws ParseException { + if (MaterialsHelper.isAir(material)) { + throw new ParseException(Errors.Parsing.materialCannotBeAir); + } + } - public Material getMaterial() { - return material; - } + public Material getMaterial() { + return material; + } - public int getAmount() { - return amount; - } + public int getAmount() { + return amount; + } - public short getDurability() { - return durability; - } + public short getDurability() { + return durability; + } - public boolean hasExplicitDurability() { - return hasExplicitDurability; - } + public boolean hasExplicitDurability() { + return hasExplicitDurability; + } - public ItemStack createStack() { - return new ItemStack(material, amount, durability); - } + public ItemStack createStack() { + return new ItemStack(material, amount, durability); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/MaterialParser.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/MaterialParser.java index 0caed34..86dd555 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/MaterialParser.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/MaterialParser.java @@ -11,9 +11,9 @@ import org.bukkit.Material; public class MaterialParser { - public static Material parseMaterial(String materialName) throws ParseException { - return MaterialsHelper.matchMaterial(materialName) - .orElseThrow(() -> new ParseException(Errors.Parsing.unknownMaterial(materialName))); - } + public static Material parseMaterial(String materialName) throws ParseException { + return MaterialsHelper.matchMaterial(materialName) + .orElseThrow(() -> new ParseException(Errors.Parsing.unknownMaterial(materialName))); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/NumberParser.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/NumberParser.java index db377b9..79df356 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/NumberParser.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/NumberParser.java @@ -9,59 +9,59 @@ import me.filoghost.chestcommands.logging.Errors; public class NumberParser { - public static double getStrictlyPositiveDouble(String input) throws ParseException { - double value = getDouble(input); - check(value > 0.0, Errors.Parsing.strictlyPositive); - return value; - } + public static double getStrictlyPositiveDouble(String input) throws ParseException { + double value = getDouble(input); + check(value > 0.0, Errors.Parsing.strictlyPositive); + return value; + } - private static double getDouble(String input) throws ParseException { - try { - return Double.parseDouble(input); - } catch (NumberFormatException ex) { - throw new ParseException(Errors.Parsing.invalidDecimal); - } - } + private static double getDouble(String input) throws ParseException { + try { + return Double.parseDouble(input); + } catch (NumberFormatException ex) { + throw new ParseException(Errors.Parsing.invalidDecimal); + } + } - public static float getFloat(String input) throws ParseException { - try { - return Float.parseFloat(input); - } catch (NumberFormatException ex) { - throw new ParseException(Errors.Parsing.invalidDecimal); - } - } + public static float getFloat(String input) throws ParseException { + try { + return Float.parseFloat(input); + } catch (NumberFormatException ex) { + throw new ParseException(Errors.Parsing.invalidDecimal); + } + } - public static short getPositiveShort(String input) throws ParseException { - short value = getShort(input); - check(value >= 0, Errors.Parsing.zeroOrPositive); - return value; - } + public static short getPositiveShort(String input) throws ParseException { + short value = getShort(input); + check(value >= 0, Errors.Parsing.zeroOrPositive); + return value; + } - private static short getShort(String input) throws ParseException { - try { - return Short.parseShort(input); - } catch (NumberFormatException ex) { - throw new ParseException(Errors.Parsing.invalidShort); - } - } + private static short getShort(String input) throws ParseException { + try { + return Short.parseShort(input); + } catch (NumberFormatException ex) { + throw new ParseException(Errors.Parsing.invalidShort); + } + } - public static int getStrictlyPositiveInteger(String input) throws ParseException { - int value = getInteger(input); - check(value > 0, Errors.Parsing.strictlyPositive); - return value; - } + public static int getStrictlyPositiveInteger(String input) throws ParseException { + int value = getInteger(input); + check(value > 0, Errors.Parsing.strictlyPositive); + return value; + } - public static int getInteger(String input) throws ParseException { - try { - return Integer.parseInt(input); - } catch (NumberFormatException ex) { - throw new ParseException(Errors.Parsing.invalidInteger); - } - } + public static int getInteger(String input) throws ParseException { + try { + return Integer.parseInt(input); + } catch (NumberFormatException ex) { + throw new ParseException(Errors.Parsing.invalidInteger); + } + } - private static void check(boolean expression, String errorMessage) throws ParseException { - if (!expression) { - throw new ParseException(errorMessage); - } - } + private static void check(boolean expression, String errorMessage) throws ParseException { + if (!expression) { + throw new ParseException(errorMessage); + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/ParseException.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/ParseException.java index 93746ab..a37ab33 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/ParseException.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/ParseException.java @@ -7,14 +7,14 @@ package me.filoghost.chestcommands.parsing; public class ParseException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public ParseException(String message) { - super(message); - } + public ParseException(String message) { + super(message); + } - public ParseException(String message, ParseException cause) { - super(message, cause); - } + public ParseException(String message, ParseException cause) { + super(message, cause); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/icon/AttributeType.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/icon/AttributeType.java index 7c68e84..09c3762 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/icon/AttributeType.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/icon/AttributeType.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.parsing.icon; +import java.util.HashMap; +import java.util.Map; import me.filoghost.chestcommands.attribute.ActionsAttribute; import me.filoghost.chestcommands.attribute.AmountAttribute; import me.filoghost.chestcommands.attribute.AttributeErrorHandler; @@ -32,77 +34,74 @@ import me.filoghost.fcommons.config.ConfigValue; import me.filoghost.fcommons.config.ConfigValueType; import me.filoghost.fcommons.config.exception.ConfigValueException; -import java.util.HashMap; -import java.util.Map; - public enum AttributeType { - POSITION_X("POSITION-X", ConfigValueType.INTEGER, PositionAttribute::new), - POSITION_Y("POSITION-Y", ConfigValueType.INTEGER, PositionAttribute::new), - MATERIAL("MATERIAL", ConfigValueType.STRING, MaterialAttribute::new), - DURABILITY("DURABILITY", ConfigValueType.SHORT, DurabilityAttribute::new), - AMOUNT("AMOUNT", ConfigValueType.INTEGER, AmountAttribute::new), - NAME("NAME", ConfigValueType.STRING, NameAttribute::new), - LORE("LORE", ConfigValueType.STRING_LIST, LoreAttribute::new), - NBT_DATA("NBT-DATA", ConfigValueType.STRING, NBTDataAttribute::new), - LEATHER_COLOR("COLOR", ConfigValueType.STRING, LeatherColorAttribute::new), - SKULL_OWNER("SKULL-OWNER", ConfigValueType.STRING, SkullOwnerAttribute::new), - BANNER_COLOR("BANNER-COLOR", ConfigValueType.STRING, BannerColorAttribute::new), - BANNER_PATTERNS("BANNER-PATTERNS", ConfigValueType.STRING_LIST, BannerPatternsAttribute::new), - PRICE("PRICE", ConfigValueType.DOUBLE, PriceAttribute::new), - EXP_LEVELS("LEVELS", ConfigValueType.INTEGER, ExpLevelsAttribute::new), - CLICK_PERMISSION("PERMISSION", ConfigValueType.STRING, ClickPermissionAttribute::new), - CLICK_PERMISSION_MESSAGE("PERMISSION-MESSAGE", ConfigValueType.STRING, ClickPermissionMessageAttribute::new), - VIEW_PERMISSION("VIEW-PERMISSION", ConfigValueType.STRING, ViewPermissionAttribute::new), - KEEP_OPEN("KEEP-OPEN", ConfigValueType.BOOLEAN, KeepOpenAttribute::new), - ACTIONS("ACTIONS", ConfigValueType.STRING_LIST, ActionsAttribute::new), - ENCHANTMENTS("ENCHANTMENTS", ConfigValueType.STRING_LIST, EnchantmentsAttribute::new), - REQUIRED_ITEMS("REQUIRED-ITEMS", ConfigValueType.STRING_LIST, RequiredItemsAttribute::new); + POSITION_X("POSITION-X", ConfigValueType.INTEGER, PositionAttribute::new), + POSITION_Y("POSITION-Y", ConfigValueType.INTEGER, PositionAttribute::new), + MATERIAL("MATERIAL", ConfigValueType.STRING, MaterialAttribute::new), + DURABILITY("DURABILITY", ConfigValueType.SHORT, DurabilityAttribute::new), + AMOUNT("AMOUNT", ConfigValueType.INTEGER, AmountAttribute::new), + NAME("NAME", ConfigValueType.STRING, NameAttribute::new), + LORE("LORE", ConfigValueType.STRING_LIST, LoreAttribute::new), + NBT_DATA("NBT-DATA", ConfigValueType.STRING, NBTDataAttribute::new), + LEATHER_COLOR("COLOR", ConfigValueType.STRING, LeatherColorAttribute::new), + SKULL_OWNER("SKULL-OWNER", ConfigValueType.STRING, SkullOwnerAttribute::new), + BANNER_COLOR("BANNER-COLOR", ConfigValueType.STRING, BannerColorAttribute::new), + BANNER_PATTERNS("BANNER-PATTERNS", ConfigValueType.STRING_LIST, BannerPatternsAttribute::new), + PRICE("PRICE", ConfigValueType.DOUBLE, PriceAttribute::new), + EXP_LEVELS("LEVELS", ConfigValueType.INTEGER, ExpLevelsAttribute::new), + CLICK_PERMISSION("PERMISSION", ConfigValueType.STRING, ClickPermissionAttribute::new), + CLICK_PERMISSION_MESSAGE("PERMISSION-MESSAGE", ConfigValueType.STRING, ClickPermissionMessageAttribute::new), + VIEW_PERMISSION("VIEW-PERMISSION", ConfigValueType.STRING, ViewPermissionAttribute::new), + KEEP_OPEN("KEEP-OPEN", ConfigValueType.BOOLEAN, KeepOpenAttribute::new), + ACTIONS("ACTIONS", ConfigValueType.STRING_LIST, ActionsAttribute::new), + ENCHANTMENTS("ENCHANTMENTS", ConfigValueType.STRING_LIST, EnchantmentsAttribute::new), + REQUIRED_ITEMS("REQUIRED-ITEMS", ConfigValueType.STRING_LIST, RequiredItemsAttribute::new); - private static final Map parsersByAttributeName; - static { - parsersByAttributeName = new HashMap<>(); - for (AttributeType attributeParser : values()) { - parsersByAttributeName.put(attributeParser.getAttributeName(), attributeParser); - } - } + private static final Map parsersByAttributeName; + static { + parsersByAttributeName = new HashMap<>(); + for (AttributeType attributeParser : values()) { + parsersByAttributeName.put(attributeParser.getAttributeName(), attributeParser); + } + } - private final String attributeName; - private final AttributeParser attributeParser; + private final String attributeName; + private final AttributeParser attributeParser; - AttributeType(String attributeName, ConfigValueType configValueType, AttributeFactory attributeFactory) { - this.attributeName = attributeName; - this.attributeParser = (ConfigValue configValue, AttributeErrorHandler errorHandler) -> { - return attributeFactory.create(configValue.asRequired(configValueType), errorHandler); - }; - } + AttributeType(String attributeName, ConfigValueType configValueType, AttributeFactory attributeFactory) { + this.attributeName = attributeName; + this.attributeParser = (ConfigValue configValue, AttributeErrorHandler errorHandler) -> { + return attributeFactory.create(configValue.asRequired(configValueType), errorHandler); + }; + } - public String getAttributeName() { - return attributeName; - } + public String getAttributeName() { + return attributeName; + } - public AttributeParser getParser() { - return attributeParser; - } + public AttributeParser getParser() { + return attributeParser; + } - public static AttributeType fromAttributeName(String attributeName) { - return parsersByAttributeName.get(attributeName); - } + public static AttributeType fromAttributeName(String attributeName) { + return parsersByAttributeName.get(attributeName); + } - @FunctionalInterface - private interface AttributeFactory { + @FunctionalInterface + private interface AttributeFactory { - A create(V value, AttributeErrorHandler errorHandler) throws ParseException; + A create(V value, AttributeErrorHandler errorHandler) throws ParseException; - } + } - @FunctionalInterface - public interface AttributeParser { + @FunctionalInterface + public interface AttributeParser { - IconAttribute parse(ConfigValue configValue, AttributeErrorHandler errorHandler) throws ParseException, ConfigValueException; + IconAttribute parse(ConfigValue configValue, AttributeErrorHandler errorHandler) throws ParseException, ConfigValueException; - } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/icon/IconSettings.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/icon/IconSettings.java index 2ac48a2..8b0db4b 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/icon/IconSettings.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/icon/IconSettings.java @@ -5,6 +5,9 @@ */ package me.filoghost.chestcommands.parsing.icon; +import java.nio.file.Path; +import java.util.EnumMap; +import java.util.Map; import me.filoghost.chestcommands.attribute.AttributeErrorHandler; import me.filoghost.chestcommands.attribute.IconAttribute; import me.filoghost.chestcommands.icon.InternalConfigurableIcon; @@ -16,64 +19,60 @@ import me.filoghost.fcommons.config.exception.ConfigValueException; import me.filoghost.fcommons.logging.ErrorCollector; import org.bukkit.Material; -import java.nio.file.Path; -import java.util.EnumMap; -import java.util.Map; - public class IconSettings { - private final Path menuFile; - private final String iconName; - private final Map attributes; + private final Path menuFile; + private final String iconName; + private final Map attributes; - public IconSettings(Path menuFile, String iconName) { - this.menuFile = menuFile; - this.iconName = iconName; - this.attributes = new EnumMap<>(AttributeType.class); - } + public IconSettings(Path menuFile, String iconName) { + this.menuFile = menuFile; + this.iconName = iconName; + this.attributes = new EnumMap<>(AttributeType.class); + } - public InternalConfigurableIcon createIcon() { - InternalConfigurableIcon icon = new InternalConfigurableIcon(Material.BEDROCK); + public InternalConfigurableIcon createIcon() { + InternalConfigurableIcon icon = new InternalConfigurableIcon(Material.BEDROCK); - for (IconAttribute attribute : attributes.values()) { - attribute.apply(icon); - } + for (IconAttribute attribute : attributes.values()) { + attribute.apply(icon); + } - return icon; - } + return icon; + } - public IconAttribute getAttributeValue(AttributeType attributeType) { - return attributes.get(attributeType); - } + public IconAttribute getAttributeValue(AttributeType attributeType) { + return attributes.get(attributeType); + } - public void loadFrom(ConfigSection config, ErrorCollector errorCollector) { - for (String attributeName : config.getKeys()) { - try { - AttributeType attributeType = AttributeType.fromAttributeName(attributeName); - if (attributeType == null) { - throw new ParseException(Errors.Parsing.unknownAttribute); - } + public void loadFrom(ConfigSection config, ErrorCollector errorCollector) { + for (String attributeName : config.getKeys()) { + try { + AttributeType attributeType = AttributeType.fromAttributeName(attributeName); + if (attributeType == null) { + throw new ParseException(Errors.Parsing.unknownAttribute); + } - AttributeErrorHandler errorHandler = (String listElement, ParseException e) -> { - errorCollector.add(e, Errors.Menu.invalidAttributeListElement(this, attributeName, listElement)); - }; + AttributeErrorHandler errorHandler = (String listElement, ParseException e) -> { + errorCollector.add(e, Errors.Menu.invalidAttributeListElement(this, attributeName, listElement)); + }; - ConfigValue configValue = config.get(attributeName); - IconAttribute iconAttribute = attributeType.getParser().parse(configValue, errorHandler); - attributes.put(attributeType, iconAttribute); + ConfigValue configValue = config.get(attributeName); + IconAttribute iconAttribute = attributeType.getParser().parse(configValue, errorHandler); + attributes.put(attributeType, iconAttribute); - } catch (ParseException | ConfigValueException e) { - errorCollector.add(e, Errors.Menu.invalidAttribute(this, attributeName)); - } - } - } + } catch (ParseException | ConfigValueException e) { + errorCollector.add(e, Errors.Menu.invalidAttribute(this, attributeName)); + } + } + } - public Path getMenuFile() { - return menuFile; - } + public Path getMenuFile() { + return menuFile; + } - public String getIconName() { - return iconName; - } + public String getIconName() { + return iconName; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/ClickType.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/ClickType.java index dcca7fd..186b5eb 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/ClickType.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/ClickType.java @@ -9,30 +9,30 @@ import org.bukkit.event.block.Action; public enum ClickType { - LEFT, - RIGHT, - BOTH; + LEFT, + RIGHT, + BOTH; - public static ClickType fromOptions(boolean left, boolean right) { - if (left && right) { - return BOTH; - } else if (left) { - return LEFT; - } else if (right) { - return RIGHT; - } else { - return null; - } - } + public static ClickType fromOptions(boolean left, boolean right) { + if (left && right) { + return BOTH; + } else if (left) { + return LEFT; + } else if (right) { + return RIGHT; + } else { + return null; + } + } - public boolean isValidInteract(Action action) { - if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) { - return this == LEFT || this == BOTH; - } else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) { - return this == RIGHT || this == BOTH; - } else { - return false; - } - } + public boolean isValidInteract(Action action) { + if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) { + return this == LEFT || this == BOTH; + } else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) { + return this == RIGHT || this == BOTH; + } else { + return false; + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/LoadedMenu.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/LoadedMenu.java index 7ea4517..9ac28c4 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/LoadedMenu.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/LoadedMenu.java @@ -6,40 +6,39 @@ package me.filoghost.chestcommands.parsing.menu; import com.google.common.collect.ImmutableList; +import java.nio.file.Path; +import java.util.List; import me.filoghost.chestcommands.menu.InternalMenu; import me.filoghost.fcommons.collection.CollectionUtils; -import java.nio.file.Path; -import java.util.List; - public class LoadedMenu { - private final InternalMenu menu; - private final Path sourceFile; - private final ImmutableList openCommands; - private final MenuOpenItem openItem; + private final InternalMenu menu; + private final Path sourceFile; + private final ImmutableList openCommands; + private final MenuOpenItem openItem; - public LoadedMenu(InternalMenu menu, Path menuFile, List openCommands, MenuOpenItem openItem) { - this.menu = menu; - this.sourceFile = menuFile; - this.openCommands = CollectionUtils.immutableCopy(openCommands); - this.openItem = openItem; - } + public LoadedMenu(InternalMenu menu, Path menuFile, List openCommands, MenuOpenItem openItem) { + this.menu = menu; + this.sourceFile = menuFile; + this.openCommands = CollectionUtils.immutableCopy(openCommands); + this.openItem = openItem; + } - public InternalMenu getMenu() { - return menu; - } + public InternalMenu getMenu() { + return menu; + } - public Path getSourceFile() { - return sourceFile; - } + public Path getSourceFile() { + return sourceFile; + } - public ImmutableList getOpenCommands() { - return openCommands; - } + public ImmutableList getOpenCommands() { + return openCommands; + } - public MenuOpenItem getOpenItem() { - return openItem; - } + public MenuOpenItem getOpenItem() { + return openItem; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuOpenItem.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuOpenItem.java index c4c7ce2..ce99fb3 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuOpenItem.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuOpenItem.java @@ -12,37 +12,37 @@ import org.bukkit.inventory.ItemStack; public class MenuOpenItem { - private final Material material; - private final ClickType clickType; - private short durability; - private boolean isRestrictiveDurability; + private final Material material; + private final ClickType clickType; + private short durability; + private boolean isRestrictiveDurability; - public MenuOpenItem(Material material, ClickType clickType) { - Preconditions.checkArgumentNotAir(material, "material"); - Preconditions.notNull(clickType, "clickType"); - - this.material = material; - this.clickType = clickType; - } + public MenuOpenItem(Material material, ClickType clickType) { + Preconditions.checkArgumentNotAir(material, "material"); + Preconditions.notNull(clickType, "clickType"); + + this.material = material; + this.clickType = clickType; + } - public void setRestrictiveDurability(short durability) { - this.durability = durability; - this.isRestrictiveDurability = true; - } + public void setRestrictiveDurability(short durability) { + this.durability = durability; + this.isRestrictiveDurability = true; + } - public boolean matches(ItemStack item, Action action) { - if (item == null) { - return false; - } + public boolean matches(ItemStack item, Action action) { + if (item == null) { + return false; + } - if (this.material != item.getType()) { - return false; - } - - if (isRestrictiveDurability && this.durability != item.getDurability()) { - return false; - } + if (this.material != item.getType()) { + return false; + } + + if (isRestrictiveDurability && this.durability != item.getDurability()) { + return false; + } - return clickType.isValidInteract(action); - } + return clickType.isValidInteract(action); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuParser.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuParser.java index 95144cc..00257a1 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuParser.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuParser.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.parsing.menu; +import java.util.ArrayList; +import java.util.List; import me.filoghost.chestcommands.action.Action; import me.filoghost.chestcommands.action.DisabledAction; import me.filoghost.chestcommands.attribute.PositionAttribute; @@ -24,186 +26,183 @@ import me.filoghost.fcommons.config.exception.MissingConfigValueException; import me.filoghost.fcommons.logging.ErrorCollector; import org.bukkit.ChatColor; -import java.util.ArrayList; -import java.util.List; - public class MenuParser { - public static LoadedMenu loadMenu(Config menuConfig, ErrorCollector errorCollector) { - MenuSettings menuSettings = loadMenuSettings(menuConfig, errorCollector); - List iconSettingsList = loadIconSettingsList(menuConfig, errorCollector); + public static LoadedMenu loadMenu(Config menuConfig, ErrorCollector errorCollector) { + MenuSettings menuSettings = loadMenuSettings(menuConfig, errorCollector); + List iconSettingsList = loadIconSettingsList(menuConfig, errorCollector); - InternalMenu menu = new InternalMenu(menuSettings.getTitle(), menuSettings.getRows(), menuConfig.getSourceFile()); + InternalMenu menu = new InternalMenu(menuSettings.getTitle(), menuSettings.getRows(), menuConfig.getSourceFile()); - for (IconSettings iconSettings : iconSettingsList) { - tryAddIconToMenu(menu, iconSettings, errorCollector); - } + for (IconSettings iconSettings : iconSettingsList) { + tryAddIconToMenu(menu, iconSettings, errorCollector); + } - menu.setRefreshTicks(menuSettings.getRefreshTicks()); - menu.setOpenActions(menuSettings.getOpenActions()); + menu.setRefreshTicks(menuSettings.getRefreshTicks()); + menu.setOpenActions(menuSettings.getOpenActions()); - return new LoadedMenu(menu, menuConfig.getSourceFile(), menuSettings.getCommands(), menuSettings.getOpenItem()); - } + return new LoadedMenu(menu, menuConfig.getSourceFile(), menuSettings.getCommands(), menuSettings.getOpenItem()); + } - private static void tryAddIconToMenu(InternalMenu menu, IconSettings iconSettings, ErrorCollector errorCollector) { - PositionAttribute positionX = (PositionAttribute) iconSettings.getAttributeValue(AttributeType.POSITION_X); - PositionAttribute positionY = (PositionAttribute) iconSettings.getAttributeValue(AttributeType.POSITION_Y); + private static void tryAddIconToMenu(InternalMenu menu, IconSettings iconSettings, ErrorCollector errorCollector) { + PositionAttribute positionX = (PositionAttribute) iconSettings.getAttributeValue(AttributeType.POSITION_X); + PositionAttribute positionY = (PositionAttribute) iconSettings.getAttributeValue(AttributeType.POSITION_Y); - if (positionX == null) { - errorCollector.add(Errors.Menu.missingAttribute(iconSettings, AttributeType.POSITION_X)); - return; - } + if (positionX == null) { + errorCollector.add(Errors.Menu.missingAttribute(iconSettings, AttributeType.POSITION_X)); + return; + } - if (positionY == null) { - errorCollector.add(Errors.Menu.missingAttribute(iconSettings, AttributeType.POSITION_Y)); - return; - } + if (positionY == null) { + errorCollector.add(Errors.Menu.missingAttribute(iconSettings, AttributeType.POSITION_Y)); + return; + } - int row = positionY.getPosition() - 1; - int column = positionX.getPosition() - 1; + int row = positionY.getPosition() - 1; + int column = positionX.getPosition() - 1; - if (row < 0 || row >= menu.getRowCount()) { - errorCollector.add( - Errors.Menu.invalidAttribute(iconSettings, AttributeType.POSITION_Y), - "it must be between 1 and " + menu.getRowCount()); - return; - } - if (column < 0 || column >= menu.getColumnCount()) { - errorCollector.add( - Errors.Menu.invalidAttribute(iconSettings, AttributeType.POSITION_X), - "it must be between 1 and " + menu.getColumnCount()); - return; - } + if (row < 0 || row >= menu.getRowCount()) { + errorCollector.add( + Errors.Menu.invalidAttribute(iconSettings, AttributeType.POSITION_Y), + "it must be between 1 and " + menu.getRowCount()); + return; + } + if (column < 0 || column >= menu.getColumnCount()) { + errorCollector.add( + Errors.Menu.invalidAttribute(iconSettings, AttributeType.POSITION_X), + "it must be between 1 and " + menu.getColumnCount()); + return; + } - if (menu.getIcon(row, column) != null) { - errorCollector.add(Errors.Menu.iconOverridesAnother(iconSettings)); - } + if (menu.getIcon(row, column) != null) { + errorCollector.add(Errors.Menu.iconOverridesAnother(iconSettings)); + } - if (iconSettings.getAttributeValue(AttributeType.MATERIAL) == null) { - errorCollector.add(Errors.Menu.missingAttribute(iconSettings, AttributeType.MATERIAL)); - } + if (iconSettings.getAttributeValue(AttributeType.MATERIAL) == null) { + errorCollector.add(Errors.Menu.missingAttribute(iconSettings, AttributeType.MATERIAL)); + } - menu.setIcon(row, column, iconSettings.createIcon()); - } + menu.setIcon(row, column, iconSettings.createIcon()); + } - private static MenuSettings loadMenuSettings(Config config, ErrorCollector errorCollector) { - ConfigSection settingsSection = config.getConfigSection(MenuSettingsNode.ROOT_SECTION); - if (settingsSection == null) { - errorCollector.add(Errors.Menu.missingSettingsSection(config.getSourceFile())); - settingsSection = new EmptyConfigSection(); - } + private static MenuSettings loadMenuSettings(Config config, ErrorCollector errorCollector) { + ConfigSection settingsSection = config.getConfigSection(MenuSettingsNode.ROOT_SECTION); + if (settingsSection == null) { + errorCollector.add(Errors.Menu.missingSettingsSection(config.getSourceFile())); + settingsSection = new EmptyConfigSection(); + } - String title; - try { - title = Colors.addColors(settingsSection.getRequiredString(MenuSettingsNode.NAME)); - if (title.length() > 32) { - title = title.substring(0, 32); - } - } catch (ConfigValueException e) { - title = ChatColor.DARK_RED + "No name set"; - addMenuSettingError(errorCollector, config, MenuSettingsNode.NAME, e); - } + String title; + try { + title = Colors.addColors(settingsSection.getRequiredString(MenuSettingsNode.NAME)); + if (title.length() > 32) { + title = title.substring(0, 32); + } + } catch (ConfigValueException e) { + title = ChatColor.DARK_RED + "No name set"; + addMenuSettingError(errorCollector, config, MenuSettingsNode.NAME, e); + } - int rows; - try { - rows = settingsSection.getRequiredInt(MenuSettingsNode.ROWS); - if (rows <= 0) { - rows = 1; - } - } catch (ConfigValueException e) { - rows = 6; // Defaults to 6 rows - addMenuSettingError(errorCollector, config, MenuSettingsNode.ROWS, e); - } + int rows; + try { + rows = settingsSection.getRequiredInt(MenuSettingsNode.ROWS); + if (rows <= 0) { + rows = 1; + } + } catch (ConfigValueException e) { + rows = 6; // Defaults to 6 rows + addMenuSettingError(errorCollector, config, MenuSettingsNode.ROWS, e); + } - MenuSettings menuSettings = new MenuSettings(title, rows); + MenuSettings menuSettings = new MenuSettings(title, rows); - List openCommands = settingsSection.getStringList(MenuSettingsNode.COMMANDS); - menuSettings.setCommands(openCommands); + List openCommands = settingsSection.getStringList(MenuSettingsNode.COMMANDS); + menuSettings.setCommands(openCommands); - List serializedOpenActions = settingsSection.getStringList(MenuSettingsNode.OPEN_ACTIONS); + List serializedOpenActions = settingsSection.getStringList(MenuSettingsNode.OPEN_ACTIONS); - if (serializedOpenActions != null) { - List openActions = new ArrayList<>(); + if (serializedOpenActions != null) { + List openActions = new ArrayList<>(); - for (String serializedAction : serializedOpenActions) { - if (serializedAction != null && !serializedAction.isEmpty()) { - try { - openActions.add(ActionParser.parse(serializedAction)); - } catch (ParseException e) { - errorCollector.add(e, Errors.Menu.invalidSettingListElement( - config.getSourceFile(), MenuSettingsNode.OPEN_ACTIONS, serializedAction)); - openActions.add(new DisabledAction(Errors.User.configurationError( - "an action linked to opening this menu was not executed because it was not valid"))); - } - } - } + for (String serializedAction : serializedOpenActions) { + if (serializedAction != null && !serializedAction.isEmpty()) { + try { + openActions.add(ActionParser.parse(serializedAction)); + } catch (ParseException e) { + errorCollector.add(e, Errors.Menu.invalidSettingListElement( + config.getSourceFile(), MenuSettingsNode.OPEN_ACTIONS, serializedAction)); + openActions.add(new DisabledAction(Errors.User.configurationError( + "an action linked to opening this menu was not executed because it was not valid"))); + } + } + } - menuSettings.setOpenActions(openActions); - } + menuSettings.setOpenActions(openActions); + } - String openItemMaterial = settingsSection.getString(MenuSettingsNode.OPEN_ITEM_MATERIAL); - if (openItemMaterial != null) { - boolean leftClick = settingsSection.getBoolean(MenuSettingsNode.OPEN_ITEM_LEFT_CLICK); - boolean rightClick = settingsSection.getBoolean(MenuSettingsNode.OPEN_ITEM_RIGHT_CLICK); + String openItemMaterial = settingsSection.getString(MenuSettingsNode.OPEN_ITEM_MATERIAL); + if (openItemMaterial != null) { + boolean leftClick = settingsSection.getBoolean(MenuSettingsNode.OPEN_ITEM_LEFT_CLICK); + boolean rightClick = settingsSection.getBoolean(MenuSettingsNode.OPEN_ITEM_RIGHT_CLICK); - if (leftClick || rightClick) { - try { - ItemStackParser itemReader = new ItemStackParser(openItemMaterial, false); - itemReader.checkNotAir(); - ClickType clickType = ClickType.fromOptions(leftClick, rightClick); + if (leftClick || rightClick) { + try { + ItemStackParser itemReader = new ItemStackParser(openItemMaterial, false); + itemReader.checkNotAir(); + ClickType clickType = ClickType.fromOptions(leftClick, rightClick); - MenuOpenItem openItem = new MenuOpenItem(itemReader.getMaterial(), clickType); + MenuOpenItem openItem = new MenuOpenItem(itemReader.getMaterial(), clickType); - if (itemReader.hasExplicitDurability()) { - openItem.setRestrictiveDurability(itemReader.getDurability()); - } + if (itemReader.hasExplicitDurability()) { + openItem.setRestrictiveDurability(itemReader.getDurability()); + } - menuSettings.setOpenItem(openItem); + menuSettings.setOpenItem(openItem); - } catch (ParseException e) { - errorCollector.add(e, Errors.Menu.invalidSetting(config.getSourceFile(), MenuSettingsNode.OPEN_ITEM_MATERIAL)); - } - } - } + } catch (ParseException e) { + errorCollector.add(e, Errors.Menu.invalidSetting(config.getSourceFile(), MenuSettingsNode.OPEN_ITEM_MATERIAL)); + } + } + } - if (settingsSection.contains(MenuSettingsNode.AUTO_REFRESH)) { - int refreshTicks = (int) (settingsSection.getDouble(MenuSettingsNode.AUTO_REFRESH) * 20.0); - if (refreshTicks < 1) { - refreshTicks = 1; - } - menuSettings.setRefreshTicks(refreshTicks); - } + if (settingsSection.contains(MenuSettingsNode.AUTO_REFRESH)) { + int refreshTicks = (int) (settingsSection.getDouble(MenuSettingsNode.AUTO_REFRESH) * 20.0); + if (refreshTicks < 1) { + refreshTicks = 1; + } + menuSettings.setRefreshTicks(refreshTicks); + } - return menuSettings; - } + return menuSettings; + } - private static void addMenuSettingError(ErrorCollector errorCollector, Config config, String missingSetting, ConfigValueException e) { - if (e instanceof MissingConfigValueException) { - errorCollector.add(Errors.Menu.missingSetting(config.getSourceFile(), missingSetting)); - } else { - errorCollector.add(e, Errors.Menu.invalidSetting(config.getSourceFile(), missingSetting)); - } - } + private static void addMenuSettingError(ErrorCollector errorCollector, Config config, String missingSetting, ConfigValueException e) { + if (e instanceof MissingConfigValueException) { + errorCollector.add(Errors.Menu.missingSetting(config.getSourceFile(), missingSetting)); + } else { + errorCollector.add(e, Errors.Menu.invalidSetting(config.getSourceFile(), missingSetting)); + } + } - private static List loadIconSettingsList(Config config, ErrorCollector errorCollector) { - List iconSettingsList = new ArrayList<>(); + private static List loadIconSettingsList(Config config, ErrorCollector errorCollector) { + List iconSettingsList = new ArrayList<>(); - for (String iconSectionName : config.getKeys()) { - if (iconSectionName.equals(MenuSettingsNode.ROOT_SECTION)) { - continue; - } + for (String iconSectionName : config.getKeys()) { + if (iconSectionName.equals(MenuSettingsNode.ROOT_SECTION)) { + continue; + } - ConfigSection iconSection = config.getConfigSection(iconSectionName); - IconSettings iconSettings = new IconSettings(config.getSourceFile(), iconSectionName); - iconSettings.loadFrom(iconSection, errorCollector); - iconSettingsList.add(iconSettings); - } + ConfigSection iconSection = config.getConfigSection(iconSectionName); + IconSettings iconSettings = new IconSettings(config.getSourceFile(), iconSectionName); + iconSettings.loadFrom(iconSection, errorCollector); + iconSettingsList.add(iconSettings); + } - return iconSettingsList; - } + return iconSettingsList; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuSettings.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuSettings.java index c41e1d4..d11c58c 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuSettings.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuSettings.java @@ -6,67 +6,66 @@ package me.filoghost.chestcommands.parsing.menu; import com.google.common.collect.ImmutableList; +import java.util.List; import me.filoghost.chestcommands.action.Action; import me.filoghost.fcommons.collection.CollectionUtils; -import java.util.List; - public class MenuSettings { - // Required settings - private final String title; - private final int rows; + // Required settings + private final String title; + private final int rows; - // Optional settings - private ImmutableList commands; - private ImmutableList openActions; - private int refreshTicks; + // Optional settings + private ImmutableList commands; + private ImmutableList openActions; + private int refreshTicks; - private MenuOpenItem openItem; - - public MenuSettings(String title, int rows) { - this.title = title; - this.rows = rows; - } + private MenuOpenItem openItem; - public String getTitle() { - return title; - } + public MenuSettings(String title, int rows) { + this.title = title; + this.rows = rows; + } - public int getRows() { - return rows; - } + public String getTitle() { + return title; + } - public void setCommands(List commands) { - this.commands = CollectionUtils.immutableCopy(commands); - } + public int getRows() { + return rows; + } - public ImmutableList getCommands() { - return commands; - } + public void setCommands(List commands) { + this.commands = CollectionUtils.immutableCopy(commands); + } - public ImmutableList getOpenActions() { - return openActions; - } + public ImmutableList getCommands() { + return commands; + } - public void setOpenActions(List openAction) { - this.openActions = CollectionUtils.immutableCopy(openAction); - } + public ImmutableList getOpenActions() { + return openActions; + } - public int getRefreshTicks() { - return refreshTicks; - } + public void setOpenActions(List openAction) { + this.openActions = CollectionUtils.immutableCopy(openAction); + } - public void setRefreshTicks(int refreshTicks) { - this.refreshTicks = refreshTicks; - } - - public MenuOpenItem getOpenItem() { - return openItem; - } + public int getRefreshTicks() { + return refreshTicks; + } + + public void setRefreshTicks(int refreshTicks) { + this.refreshTicks = refreshTicks; + } + + public MenuOpenItem getOpenItem() { + return openItem; + } + + public void setOpenItem(MenuOpenItem openItem) { + this.openItem = openItem; + } - public void setOpenItem(MenuOpenItem openItem) { - this.openItem = openItem; - } - } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuSettingsNode.java b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuSettingsNode.java index 144d5db..9333957 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuSettingsNode.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuSettingsNode.java @@ -7,18 +7,18 @@ package me.filoghost.chestcommands.parsing.menu; public class MenuSettingsNode { - public static final String - ROOT_SECTION = "menu-settings", + public static final String + ROOT_SECTION = "menu-settings", - NAME = "name", - ROWS = "rows", + NAME = "name", + ROWS = "rows", - COMMANDS = "commands", - OPEN_ACTIONS = "open-actions", - AUTO_REFRESH = "auto-refresh", + COMMANDS = "commands", + OPEN_ACTIONS = "open-actions", + AUTO_REFRESH = "auto-refresh", - OPEN_ITEM_MATERIAL = "open-with-item.material", - OPEN_ITEM_LEFT_CLICK = "open-with-item.left-click", - OPEN_ITEM_RIGHT_CLICK = "open-with-item.right-click"; + OPEN_ITEM_MATERIAL = "open-with-item.material", + OPEN_ITEM_LEFT_CLICK = "open-with-item.left-click", + OPEN_ITEM_RIGHT_CLICK = "open-with-item.right-click"; } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/DefaultPlaceholder.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/DefaultPlaceholder.java index af5c084..e3ae504 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/DefaultPlaceholder.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/DefaultPlaceholder.java @@ -11,37 +11,37 @@ import org.bukkit.Bukkit; public enum DefaultPlaceholder { - PLAYER("player", (player, argument) -> player.getName()), + PLAYER("player", (player, argument) -> player.getName()), - ONLINE("online", (player, argument) -> String.valueOf(Bukkit.getOnlinePlayers().size())), + ONLINE("online", (player, argument) -> String.valueOf(Bukkit.getOnlinePlayers().size())), - MAX_PLAYERS("max_players", (player, argument) -> String.valueOf(Bukkit.getMaxPlayers())), + MAX_PLAYERS("max_players", (player, argument) -> String.valueOf(Bukkit.getMaxPlayers())), - WORLD("world", (player, argument) -> player.getWorld().getName()), + WORLD("world", (player, argument) -> player.getWorld().getName()), - MONEY("money", (player, argument) -> { - if (VaultEconomyHook.INSTANCE.isEnabled()) { - return VaultEconomyHook.formatMoney(VaultEconomyHook.getMoney(player)); - } else { - return "[ECONOMY PLUGIN NOT FOUND]"; - } - }); + MONEY("money", (player, argument) -> { + if (VaultEconomyHook.INSTANCE.isEnabled()) { + return VaultEconomyHook.formatMoney(VaultEconomyHook.getMoney(player)); + } else { + return "[ECONOMY PLUGIN NOT FOUND]"; + } + }); - private final String identifier; - private final PlaceholderReplacer replacer; + private final String identifier; + private final PlaceholderReplacer replacer; - DefaultPlaceholder(String identifier, PlaceholderReplacer replacer) { - this.identifier = identifier; - this.replacer = replacer; - } + DefaultPlaceholder(String identifier, PlaceholderReplacer replacer) { + this.identifier = identifier; + this.replacer = replacer; + } - public String getIdentifier() { - return identifier; - } + public String getIdentifier() { + return identifier; + } - public PlaceholderReplacer getReplacer() { - return replacer; - } + public PlaceholderReplacer getReplacer() { + return replacer; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderCache.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderCache.java index a51b0a3..d140e76 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderCache.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderCache.java @@ -5,30 +5,29 @@ */ package me.filoghost.chestcommands.placeholder; -import me.filoghost.chestcommands.placeholder.scanner.PlaceholderMatch; -import org.bukkit.entity.Player; - import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; import java.util.function.Supplier; +import me.filoghost.chestcommands.placeholder.scanner.PlaceholderMatch; +import org.bukkit.entity.Player; public class PlaceholderCache { - private final Map> cachedReplacements; + private final Map> cachedReplacements; - public PlaceholderCache() { - cachedReplacements = new WeakHashMap<>(); - } + public PlaceholderCache() { + cachedReplacements = new WeakHashMap<>(); + } - public String computeIfAbsent(PlaceholderMatch placeholderMatch, Player player, Supplier replacementGetter) { - return cachedReplacements - .computeIfAbsent(player, key -> new HashMap<>()) - .computeIfAbsent(placeholderMatch, key -> replacementGetter.get()); - } + public String computeIfAbsent(PlaceholderMatch placeholderMatch, Player player, Supplier replacementGetter) { + return cachedReplacements + .computeIfAbsent(player, key -> new HashMap<>()) + .computeIfAbsent(placeholderMatch, key -> replacementGetter.get()); + } - public void onTick() { - cachedReplacements.forEach((player, placeholderMap) -> placeholderMap.clear()); - } + public void onTick() { + cachedReplacements.forEach((player, placeholderMap) -> placeholderMap.clear()); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderManager.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderManager.java index 4af360e..06cbac4 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderManager.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderManager.java @@ -5,6 +5,8 @@ */ package me.filoghost.chestcommands.placeholder; +import java.util.ArrayList; +import java.util.List; import me.filoghost.chestcommands.api.PlaceholderReplacer; import me.filoghost.chestcommands.hook.PlaceholderAPIHook; import me.filoghost.chestcommands.placeholder.scanner.PlaceholderMatch; @@ -13,110 +15,107 @@ import me.filoghost.fcommons.Preconditions; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import java.util.ArrayList; -import java.util.List; - public class PlaceholderManager { - private static final List staticPlaceholders = new ArrayList<>(); - private static final PlaceholderRegistry relativePlaceholderRegistry = new PlaceholderRegistry(); - static { - for (DefaultPlaceholder placeholder : DefaultPlaceholder.values()) { - relativePlaceholderRegistry.registerInternalPlaceholder(placeholder.getIdentifier(), placeholder.getReplacer()); - } - } + private static final List staticPlaceholders = new ArrayList<>(); + private static final PlaceholderRegistry relativePlaceholderRegistry = new PlaceholderRegistry(); + static { + for (DefaultPlaceholder placeholder : DefaultPlaceholder.values()) { + relativePlaceholderRegistry.registerInternalPlaceholder(placeholder.getIdentifier(), placeholder.getReplacer()); + } + } - private static final PlaceholderCache placeholderCache = new PlaceholderCache(); + private static final PlaceholderCache placeholderCache = new PlaceholderCache(); - public static boolean hasRelativePlaceholders(List list) { - for (String element : list) { - if (hasRelativePlaceholders(element)) { - return true; - } - } - return false; - } + public static boolean hasRelativePlaceholders(List list) { + for (String element : list) { + if (hasRelativePlaceholders(element)) { + return true; + } + } + return false; + } - public static boolean hasRelativePlaceholders(String text) { - if (new PlaceholderScanner(text).anyMatch(PlaceholderManager::isValidPlaceholder)) { - return true; - } + public static boolean hasRelativePlaceholders(String text) { + if (new PlaceholderScanner(text).anyMatch(PlaceholderManager::isValidPlaceholder)) { + return true; + } - if (PlaceholderAPIHook.INSTANCE.isEnabled() && PlaceholderAPIHook.hasPlaceholders(text)) { - return true; - } + if (PlaceholderAPIHook.INSTANCE.isEnabled() && PlaceholderAPIHook.hasPlaceholders(text)) { + return true; + } - return false; - } + return false; + } - public static String replaceRelativePlaceholders(String text, Player player) { - text = new PlaceholderScanner(text).replace(match -> getReplacement(match, player)); + public static String replaceRelativePlaceholders(String text, Player player) { + text = new PlaceholderScanner(text).replace(match -> getReplacement(match, player)); - if (PlaceholderAPIHook.INSTANCE.isEnabled()) { - text = PlaceholderAPIHook.setPlaceholders(text, player); - } + if (PlaceholderAPIHook.INSTANCE.isEnabled()) { + text = PlaceholderAPIHook.setPlaceholders(text, player); + } - return text; - } + return text; + } - private static boolean isValidPlaceholder(PlaceholderMatch placeholderMatch) { - return relativePlaceholderRegistry.getPlaceholderReplacer(placeholderMatch) != null; - } + private static boolean isValidPlaceholder(PlaceholderMatch placeholderMatch) { + return relativePlaceholderRegistry.getPlaceholderReplacer(placeholderMatch) != null; + } - private static String getReplacement(PlaceholderMatch placeholderMatch, Player player) { - PlaceholderReplacer placeholderReplacer = relativePlaceholderRegistry.getPlaceholderReplacer(placeholderMatch); + private static String getReplacement(PlaceholderMatch placeholderMatch, Player player) { + PlaceholderReplacer placeholderReplacer = relativePlaceholderRegistry.getPlaceholderReplacer(placeholderMatch); - if (placeholderReplacer == null) { - return null; // Placeholder not found - } + if (placeholderReplacer == null) { + return null; // Placeholder not found + } - return placeholderCache.computeIfAbsent(placeholderMatch, player, () -> { - return placeholderReplacer.getReplacement(player, placeholderMatch.getArgument()); - }); - } + return placeholderCache.computeIfAbsent(placeholderMatch, player, () -> { + return placeholderReplacer.getReplacement(player, placeholderMatch.getArgument()); + }); + } - public static void setStaticPlaceholders(List staticPlaceholders) { - PlaceholderManager.staticPlaceholders.clear(); - PlaceholderManager.staticPlaceholders.addAll(staticPlaceholders); - } + public static void setStaticPlaceholders(List staticPlaceholders) { + PlaceholderManager.staticPlaceholders.clear(); + PlaceholderManager.staticPlaceholders.addAll(staticPlaceholders); + } - public static boolean hasStaticPlaceholders(List list) { - for (String element : list) { - if (hasStaticPlaceholders(element)) { - return true; - } - } - return false; - } + public static boolean hasStaticPlaceholders(List list) { + for (String element : list) { + if (hasStaticPlaceholders(element)) { + return true; + } + } + return false; + } - public static boolean hasStaticPlaceholders(String text) { - for (StaticPlaceholder staticPlaceholder : staticPlaceholders) { - if (text.contains(staticPlaceholder.getIdentifier())) { - return true; - } - } - return false; - } + public static boolean hasStaticPlaceholders(String text) { + for (StaticPlaceholder staticPlaceholder : staticPlaceholders) { + if (text.contains(staticPlaceholder.getIdentifier())) { + return true; + } + } + return false; + } - public static String replaceStaticPlaceholders(String text) { - for (StaticPlaceholder staticPlaceholder : staticPlaceholders) { - text = text.replace(staticPlaceholder.getIdentifier(), staticPlaceholder.getReplacement()); - } - return text; - } + public static String replaceStaticPlaceholders(String text) { + for (StaticPlaceholder staticPlaceholder : staticPlaceholders) { + text = text.replace(staticPlaceholder.getIdentifier(), staticPlaceholder.getReplacement()); + } + return text; + } - public static void registerPluginPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) { - Preconditions.notNull(plugin, "plugin"); - Preconditions.notNull(identifier, "identifier"); - Preconditions.checkArgument(1 <= identifier.length() && identifier.length() <= 30, "identifier length must be between 1 and 30"); - Preconditions.checkArgument(identifier.matches("[a-zA-Z0-9_]+"), "identifier must contain only letters, numbers and underscores"); - Preconditions.notNull(placeholderReplacer, "placeholderReplacer"); + public static void registerPluginPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) { + Preconditions.notNull(plugin, "plugin"); + Preconditions.notNull(identifier, "identifier"); + Preconditions.checkArgument(1 <= identifier.length() && identifier.length() <= 30, "identifier length must be between 1 and 30"); + Preconditions.checkArgument(identifier.matches("[a-zA-Z0-9_]+"), "identifier must contain only letters, numbers and underscores"); + Preconditions.notNull(placeholderReplacer, "placeholderReplacer"); - relativePlaceholderRegistry.registerExternalPlaceholder(plugin, identifier, placeholderReplacer); - } + relativePlaceholderRegistry.registerExternalPlaceholder(plugin, identifier, placeholderReplacer); + } - public static void onTick() { - placeholderCache.onTick(); - } + public static void onTick() { + placeholderCache.onTick(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderRegistry.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderRegistry.java index 73a9ea0..a192586 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderRegistry.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderRegistry.java @@ -5,49 +5,48 @@ */ package me.filoghost.chestcommands.placeholder; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; import me.filoghost.chestcommands.api.PlaceholderReplacer; import me.filoghost.chestcommands.placeholder.scanner.PlaceholderMatch; import org.bukkit.plugin.Plugin; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - public class PlaceholderRegistry { - private final Map internalPlaceholders = new HashMap<>(); - private final Map> externalPlaceholders = new HashMap<>(); + private final Map internalPlaceholders = new HashMap<>(); + private final Map> externalPlaceholders = new HashMap<>(); - public void registerInternalPlaceholder(String identifier, PlaceholderReplacer replacer) { - internalPlaceholders.put(identifier, replacer); - } + public void registerInternalPlaceholder(String identifier, PlaceholderReplacer replacer) { + internalPlaceholders.put(identifier, replacer); + } - public void registerExternalPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) { - externalPlaceholders - .computeIfAbsent(identifier, key -> new LinkedHashMap<>()) - .put(plugin.getName(), placeholderReplacer); - } + public void registerExternalPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) { + externalPlaceholders + .computeIfAbsent(identifier, key -> new LinkedHashMap<>()) + .put(plugin.getName(), placeholderReplacer); + } - public PlaceholderReplacer getPlaceholderReplacer(PlaceholderMatch placeholderMatch) { - if (placeholderMatch.getPluginNamespace() == null) { - PlaceholderReplacer internalReplacer = internalPlaceholders.get(placeholderMatch.getIdentifier()); - if (internalReplacer != null) { - return internalReplacer; - } - } + public PlaceholderReplacer getPlaceholderReplacer(PlaceholderMatch placeholderMatch) { + if (placeholderMatch.getPluginNamespace() == null) { + PlaceholderReplacer internalReplacer = internalPlaceholders.get(placeholderMatch.getIdentifier()); + if (internalReplacer != null) { + return internalReplacer; + } + } - Map externalReplacers = externalPlaceholders.get(placeholderMatch.getIdentifier()); + Map externalReplacers = externalPlaceholders.get(placeholderMatch.getIdentifier()); - // Find exact replacer if plugin name is specified - if (placeholderMatch.getPluginNamespace() != null) { - return externalReplacers.get(placeholderMatch.getPluginNamespace()); - } + // Find exact replacer if plugin name is specified + if (placeholderMatch.getPluginNamespace() != null) { + return externalReplacers.get(placeholderMatch.getPluginNamespace()); + } - if (externalReplacers != null && !externalReplacers.isEmpty()) { - return externalReplacers.values().iterator().next(); - } + if (externalReplacers != null && !externalReplacers.isEmpty()) { + return externalReplacers.values().iterator().next(); + } - return null; - } + return null; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderString.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderString.java index fd1ef4e..3a8e294 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderString.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderString.java @@ -9,38 +9,38 @@ import org.bukkit.entity.Player; public class PlaceholderString { - private final String originalString; - private final String stringWithStaticPlaceholders; - private final boolean hasDynamicPlaceholders; + private final String originalString; + private final String stringWithStaticPlaceholders; + private final boolean hasDynamicPlaceholders; - public static PlaceholderString of(String string) { - if (string != null) { - return new PlaceholderString(string); - } else { - return null; - } - } - - private PlaceholderString(String originalString) { - this.originalString = originalString; - this.stringWithStaticPlaceholders = PlaceholderManager.replaceStaticPlaceholders(originalString); - this.hasDynamicPlaceholders = PlaceholderManager.hasRelativePlaceholders(stringWithStaticPlaceholders); - } - - public String getValue(Player player) { - if (hasDynamicPlaceholders) { - return PlaceholderManager.replaceRelativePlaceholders(stringWithStaticPlaceholders, player); - } else { - return stringWithStaticPlaceholders; - } - } + public static PlaceholderString of(String string) { + if (string != null) { + return new PlaceholderString(string); + } else { + return null; + } + } + + private PlaceholderString(String originalString) { + this.originalString = originalString; + this.stringWithStaticPlaceholders = PlaceholderManager.replaceStaticPlaceholders(originalString); + this.hasDynamicPlaceholders = PlaceholderManager.hasRelativePlaceholders(stringWithStaticPlaceholders); + } + + public String getValue(Player player) { + if (hasDynamicPlaceholders) { + return PlaceholderManager.replaceRelativePlaceholders(stringWithStaticPlaceholders, player); + } else { + return stringWithStaticPlaceholders; + } + } - public String getOriginalValue() { - return originalString; - } + public String getOriginalValue() { + return originalString; + } - public boolean hasDynamicPlaceholders() { - return hasDynamicPlaceholders; - } + public boolean hasDynamicPlaceholders() { + return hasDynamicPlaceholders; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderStringList.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderStringList.java index 4ee54b0..0bda021 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderStringList.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/PlaceholderStringList.java @@ -6,52 +6,51 @@ package me.filoghost.chestcommands.placeholder; import com.google.common.collect.ImmutableList; +import java.util.List; import me.filoghost.fcommons.Preconditions; import me.filoghost.fcommons.collection.CollectionUtils; import org.bukkit.entity.Player; -import java.util.List; - public class PlaceholderStringList { - private final ImmutableList originalList; - private final ImmutableList listWithStaticPlaceholders; - private final ImmutableList placeholderStringList; - private final boolean hasDynamicPlaceholders; - - public PlaceholderStringList(List list) { - Preconditions.notNull(list, "list"); - this.originalList = ImmutableList.copyOf(list); + private final ImmutableList originalList; + private final ImmutableList listWithStaticPlaceholders; + private final ImmutableList placeholderStringList; + private final boolean hasDynamicPlaceholders; - // Replace static placeholders only once, if present - if (PlaceholderManager.hasStaticPlaceholders(originalList)) { - this.listWithStaticPlaceholders = CollectionUtils.transformImmutable(originalList, PlaceholderManager::replaceStaticPlaceholders); - } else { - this.listWithStaticPlaceholders = originalList; - } + public PlaceholderStringList(List list) { + Preconditions.notNull(list, "list"); + this.originalList = ImmutableList.copyOf(list); - this.hasDynamicPlaceholders = PlaceholderManager.hasRelativePlaceholders(listWithStaticPlaceholders); - if (hasDynamicPlaceholders) { - this.placeholderStringList = CollectionUtils.transformImmutable(listWithStaticPlaceholders, PlaceholderString::of); - } else { - this.placeholderStringList = null; - } - } - - public ImmutableList getOriginalValue() { - return originalList; - } - - public ImmutableList getValue(Player player) { - if (hasDynamicPlaceholders) { - return CollectionUtils.transformImmutable(placeholderStringList, element -> element.getValue(player)); - } else { - return listWithStaticPlaceholders; - } - } - - public boolean hasDynamicPlaceholders() { - return hasDynamicPlaceholders; - } + // Replace static placeholders only once, if present + if (PlaceholderManager.hasStaticPlaceholders(originalList)) { + this.listWithStaticPlaceholders = CollectionUtils.transformImmutable(originalList, PlaceholderManager::replaceStaticPlaceholders); + } else { + this.listWithStaticPlaceholders = originalList; + } + + this.hasDynamicPlaceholders = PlaceholderManager.hasRelativePlaceholders(listWithStaticPlaceholders); + if (hasDynamicPlaceholders) { + this.placeholderStringList = CollectionUtils.transformImmutable(listWithStaticPlaceholders, PlaceholderString::of); + } else { + this.placeholderStringList = null; + } + } + + public ImmutableList getOriginalValue() { + return originalList; + } + + public ImmutableList getValue(Player player) { + if (hasDynamicPlaceholders) { + return CollectionUtils.transformImmutable(placeholderStringList, element -> element.getValue(player)); + } else { + return listWithStaticPlaceholders; + } + } + + public boolean hasDynamicPlaceholders() { + return hasDynamicPlaceholders; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/StaticPlaceholder.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/StaticPlaceholder.java index 247fe9d..3c532b8 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/StaticPlaceholder.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/StaticPlaceholder.java @@ -7,20 +7,20 @@ package me.filoghost.chestcommands.placeholder; public class StaticPlaceholder { - private final String identifier; - private final String replacement; + private final String identifier; + private final String replacement; - public StaticPlaceholder(String identifier, String replacement) { - this.identifier = identifier; - this.replacement = replacement; - } + public StaticPlaceholder(String identifier, String replacement) { + this.identifier = identifier; + this.replacement = replacement; + } - public String getIdentifier() { - return identifier; - } + public String getIdentifier() { + return identifier; + } - public String getReplacement() { - return replacement; - } + public String getReplacement() { + return replacement; + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/scanner/PlaceholderMatch.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/scanner/PlaceholderMatch.java index 2eea883..b0ecb49 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/scanner/PlaceholderMatch.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/scanner/PlaceholderMatch.java @@ -5,80 +5,79 @@ */ package me.filoghost.chestcommands.placeholder.scanner; -import me.filoghost.fcommons.Strings; - import java.util.Objects; +import me.filoghost.fcommons.Strings; public class PlaceholderMatch { - private final String pluginNamespace; - private final String identifier; - private final String argument; + private final String pluginNamespace; + private final String identifier; + private final String argument; - private PlaceholderMatch(String pluginNamespace, String identifier, String argument) { - this.pluginNamespace = pluginNamespace; - this.identifier = identifier; - this.argument = argument; - } + private PlaceholderMatch(String pluginNamespace, String identifier, String argument) { + this.pluginNamespace = pluginNamespace; + this.identifier = identifier; + this.argument = argument; + } - public String getPluginNamespace() { - return pluginNamespace; - } + public String getPluginNamespace() { + return pluginNamespace; + } - public String getIdentifier() { - return identifier; - } + public String getIdentifier() { + return identifier; + } - public String getArgument() { - return argument; - } + public String getArgument() { + return argument; + } - /** - * Valid formats: - * {pluginName/placeholder: argument} - * {placeholder: argument} - * {placeholder} - */ - public static PlaceholderMatch parse(String placeholderContent) { - String explicitPluginName = null; - String identifier; - String argument = null; + /** + * Valid formats: + * {pluginName/placeholder: argument} + * {placeholder: argument} + * {placeholder} + */ + public static PlaceholderMatch parse(String placeholderContent) { + String explicitPluginName = null; + String identifier; + String argument = null; - if (placeholderContent.contains(":")) { - String[] parts = Strings.trimmedSplit(placeholderContent, ":", 2); - identifier = parts[0]; - argument = parts[1]; - } else { - identifier = placeholderContent; - } + if (placeholderContent.contains(":")) { + String[] parts = Strings.trimmedSplit(placeholderContent, ":", 2); + identifier = parts[0]; + argument = parts[1]; + } else { + identifier = placeholderContent; + } - if (identifier.contains("/")) { - String[] parts = Strings.trimmedSplit(identifier, "\\/", 2); - identifier = parts[0]; - explicitPluginName = parts[1]; - } + if (identifier.contains("/")) { + String[] parts = Strings.trimmedSplit(identifier, "\\/", 2); + identifier = parts[0]; + explicitPluginName = parts[1]; + } - return new PlaceholderMatch(explicitPluginName, identifier, argument); - } + return new PlaceholderMatch(explicitPluginName, identifier, argument); + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || this.getClass() != obj.getClass()) { - return false; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || this.getClass() != obj.getClass()) { + return false; + } - PlaceholderMatch other = (PlaceholderMatch) obj; - return Objects.equals(this.pluginNamespace, other.pluginNamespace) && - Objects.equals(this.identifier, other.identifier) && - Objects.equals(this.argument, other.argument); - } + PlaceholderMatch other = (PlaceholderMatch) obj; + return Objects.equals(this.pluginNamespace, other.pluginNamespace) && + Objects.equals(this.identifier, other.identifier) && + Objects.equals(this.argument, other.argument); + } - @Override - public int hashCode() { - return Objects.hash(pluginNamespace, identifier, argument); - } + @Override + public int hashCode() { + return Objects.hash(pluginNamespace, identifier, argument); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/scanner/PlaceholderScanner.java b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/scanner/PlaceholderScanner.java index 15ca214..b00ad9b 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/placeholder/scanner/PlaceholderScanner.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/placeholder/scanner/PlaceholderScanner.java @@ -12,91 +12,91 @@ import java.util.function.Predicate; public class PlaceholderScanner { - private final String input; - private final int inputLength; + private final String input; + private final int inputLength; - private int lastAppendIndex; - private int placeholderStartIndex; - private int index; - private boolean stopExecution; + private int lastAppendIndex; + private int placeholderStartIndex; + private int index; + private boolean stopExecution; - public PlaceholderScanner(String input) { - this.input = input; - this.inputLength = input.length(); - } + public PlaceholderScanner(String input) { + this.input = input; + this.inputLength = input.length(); + } - public boolean anyMatch(Predicate predicate) { - AtomicBoolean matchFound = new AtomicBoolean(false); + public boolean anyMatch(Predicate predicate) { + AtomicBoolean matchFound = new AtomicBoolean(false); - scan(identifier -> { - if (predicate.test(identifier)) { - matchFound.set(true); - stopExecution = true; - } - }); + scan(identifier -> { + if (predicate.test(identifier)) { + matchFound.set(true); + stopExecution = true; + } + }); - return matchFound.get(); - } + return matchFound.get(); + } - public String replace(Function replaceFunction) { - StringBuilder output = new StringBuilder(); + public String replace(Function replaceFunction) { + StringBuilder output = new StringBuilder(); - scan(identifier -> { - String replacement = replaceFunction.apply(identifier); + scan(identifier -> { + String replacement = replaceFunction.apply(identifier); - if (replacement != null) { - // Append preceding text and replacement - output.append(input, lastAppendIndex, placeholderStartIndex); - output.append(replacement); - lastAppendIndex = index + 1; // Start next append after the closing tag - } + if (replacement != null) { + // Append preceding text and replacement + output.append(input, lastAppendIndex, placeholderStartIndex); + output.append(replacement); + lastAppendIndex = index + 1; // Start next append after the closing tag + } - // Else, if no replacement is found, ignore the placeholder replacement and proceed normally - }); + // Else, if no replacement is found, ignore the placeholder replacement and proceed normally + }); - // Append trailing text - if (lastAppendIndex < inputLength) { - output.append(input, lastAppendIndex, inputLength); - } + // Append trailing text + if (lastAppendIndex < inputLength) { + output.append(input, lastAppendIndex, inputLength); + } - return output.toString(); - } + return output.toString(); + } - private void scan(Consumer matchCallback) { - index = 0; - placeholderStartIndex = 0; - lastAppendIndex = 0; + private void scan(Consumer matchCallback) { + index = 0; + placeholderStartIndex = 0; + lastAppendIndex = 0; - boolean insidePlaceholder = false; + boolean insidePlaceholder = false; - while (index < inputLength) { - char currentChar = input.charAt(index); + while (index < inputLength) { + char currentChar = input.charAt(index); - if (insidePlaceholder) { - if (currentChar == '}') { - // If the placeholder is "{player}" then the identifier is "player" - String placeholderContent = input.substring(placeholderStartIndex + 1, index); // Skip the opening tag - matchCallback.accept(PlaceholderMatch.parse(placeholderContent)); - if (!stopExecution) { - return; - } + if (insidePlaceholder) { + if (currentChar == '}') { + // If the placeholder is "{player}" then the identifier is "player" + String placeholderContent = input.substring(placeholderStartIndex + 1, index); // Skip the opening tag + matchCallback.accept(PlaceholderMatch.parse(placeholderContent)); + if (!stopExecution) { + return; + } - insidePlaceholder = false; - placeholderStartIndex = 0; + insidePlaceholder = false; + placeholderStartIndex = 0; - } else if (currentChar == '{') { - // Nested placeholder, ignore wrapping placeholder and update placeholder start index - placeholderStartIndex = index; - } - } else { - if (currentChar == '{') { - insidePlaceholder = true; - placeholderStartIndex = index; - } - } + } else if (currentChar == '{') { + // Nested placeholder, ignore wrapping placeholder and update placeholder start index + placeholderStartIndex = index; + } + } else { + if (currentChar == '{') { + insidePlaceholder = true; + placeholderStartIndex = index; + } + } - index++; - } - } + index++; + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/task/TickingTask.java b/plugin/src/main/java/me/filoghost/chestcommands/task/TickingTask.java index 7627b9e..716f1be 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/task/TickingTask.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/task/TickingTask.java @@ -14,30 +14,30 @@ import org.bukkit.entity.Player; public class TickingTask implements Runnable { - private long currentTick; + private long currentTick; - @Override - public void run() { - updateMenus(); - PlaceholderManager.onTick(); + @Override + public void run() { + updateMenus(); + PlaceholderManager.onTick(); - currentTick++; - } + currentTick++; + } - private void updateMenus() { - for (Player player : Bukkit.getOnlinePlayers()) { - DefaultMenuView menuView = MenuManager.getOpenMenuView(player); + private void updateMenus() { + for (Player player : Bukkit.getOnlinePlayers()) { + DefaultMenuView menuView = MenuManager.getOpenMenuView(player); - if (menuView == null || !(menuView.getMenu() instanceof InternalMenu)) { - continue; - } + if (menuView == null || !(menuView.getMenu() instanceof InternalMenu)) { + continue; + } - int refreshTicks = ((InternalMenu) menuView.getMenu()).getRefreshTicks(); + int refreshTicks = ((InternalMenu) menuView.getMenu()).getRefreshTicks(); - if (refreshTicks > 0 && currentTick % refreshTicks == 0) { - menuView.refresh(); - } - } - } + if (refreshTicks > 0 && currentTick % refreshTicks == 0) { + menuView.refresh(); + } + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/Utils.java b/plugin/src/main/java/me/filoghost/chestcommands/util/Utils.java index 91fd013..2f0844a 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/Utils.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/Utils.java @@ -9,19 +9,19 @@ import me.filoghost.fcommons.Strings; public class Utils { - public static String formatEnum(Enum enumValue) { - return Strings.capitalizeFully(enumValue.name().replace("_", " ")); - } + public static String formatEnum(Enum enumValue) { + return Strings.capitalizeFully(enumValue.name().replace("_", " ")); + } - public static String addYamlExtension(String fileName) { - if (fileName == null) { - return null; - } - if (fileName.toLowerCase().endsWith(".yml")) { - return fileName; - } else { - return fileName + ".yml"; - } - } + public static String addYamlExtension(String fileName) { + if (fileName == null) { + return null; + } + if (fileName.toLowerCase().endsWith(".yml")) { + return fileName; + } else { + return fileName + ".yml"; + } + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTByte.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTByte.java index 91be0e2..9619d4e 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTByte.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTByte.java @@ -10,54 +10,54 @@ package me.filoghost.chestcommands.util.nbt; */ public final class NBTByte extends NBTTag implements Cloneable { - private byte value; + private byte value; - public NBTByte(byte value) { - this.value = value; - } + public NBTByte(byte value) { + this.value = value; + } - @Override - public Byte getValue() { - return value; - } + @Override + public Byte getValue() { + return value; + } - public byte getByteValue() { - return value; - } + public byte getByteValue() { + return value; + } - public void setByteValue(byte value) { - this.value = value; - } + public void setByteValue(byte value) { + this.value = value; + } - @Override - public NBTType getType() { - return NBTType.BYTE; - } + @Override + public NBTType getType() { + return NBTType.BYTE; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTByte && equals((NBTByte) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTByte && equals((NBTByte) obj); + } - public boolean equals(NBTByte tag) { - return this.value == tag.value; - } + public boolean equals(NBTByte tag) { + return this.value == tag.value; + } - @Override - public int hashCode() { - return Byte.hashCode(value); - } + @Override + public int hashCode() { + return Byte.hashCode(value); + } - @Override - public String toMSONString() { - return Byte.toUnsignedInt(value) + "b"; - } + @Override + public String toMSONString() { + return Byte.toUnsignedInt(value) + "b"; + } - @Override - public NBTByte clone() { - return new NBTByte(value); - } + @Override + public NBTByte clone() { + return new NBTByte(value); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTByteArray.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTByteArray.java index bf71e86..1b4175e 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTByteArray.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTByteArray.java @@ -12,58 +12,58 @@ import java.util.Arrays; */ public final class NBTByteArray extends NBTTag { - private final byte[] value; + private final byte[] value; - public NBTByteArray(byte[] value) { - this.value = value; - } + public NBTByteArray(byte[] value) { + this.value = value; + } - public NBTByteArray(Number[] numbers) { - this.value = new byte[numbers.length]; - for (int i = 0; i < numbers.length; i++) - value[i] = numbers[i].byteValue(); - } + public NBTByteArray(Number[] numbers) { + this.value = new byte[numbers.length]; + for (int i = 0; i < numbers.length; i++) + value[i] = numbers[i].byteValue(); + } - /** - * Returns the length of this array. - * - * @return the length of this array - */ - public int length() { - return value.length; - } + /** + * Returns the length of this array. + * + * @return the length of this array + */ + public int length() { + return value.length; + } - @Override - public byte[] getValue() { - return value; - } + @Override + public byte[] getValue() { + return value; + } - @Override - public NBTType getType() { - return NBTType.BYTE_ARRAY; - } + @Override + public NBTType getType() { + return NBTType.BYTE_ARRAY; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTByteArray && equals((NBTByteArray) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTByteArray && equals((NBTByteArray) obj); + } - public boolean equals(NBTByteArray tag) { - return Arrays.equals(this.value, tag.value); - } + public boolean equals(NBTByteArray tag) { + return Arrays.equals(this.value, tag.value); + } - @Override - public String toMSONString() { - StringBuilder stringbuilder = new StringBuilder("[B;"); - for (int i = 0; i < this.value.length; i++) { - if (i != 0) { - stringbuilder.append(','); - } - stringbuilder.append(this.value[i]).append('B'); - } - return stringbuilder.append(']').toString(); - } + @Override + public String toMSONString() { + StringBuilder stringbuilder = new StringBuilder("[B;"); + for (int i = 0; i < this.value.length; i++) { + if (i != 0) { + stringbuilder.append(','); + } + stringbuilder.append(this.value[i]).append('B'); + } + return stringbuilder.append(']').toString(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTCompound.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTCompound.java index 23341a4..bf8a0e5 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTCompound.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTCompound.java @@ -20,422 +20,422 @@ import java.util.regex.Pattern; */ public final class NBTCompound extends NBTTag { - private static final Pattern SIMPLE_STRING = Pattern.compile("[A-Za-z0-9._+-]+"); + private static final Pattern SIMPLE_STRING = Pattern.compile("[A-Za-z0-9._+-]+"); - private final Map value; + private final Map value; - public NBTCompound(Map value) { - this.value = new LinkedHashMap<>(value); - } + public NBTCompound(Map value) { + this.value = new LinkedHashMap<>(value); + } - public NBTCompound() { - this.value = new LinkedHashMap<>(); - } + public NBTCompound() { + this.value = new LinkedHashMap<>(); + } - // GETTERS + // GETTERS - /** - * Returns the size of this compound. - * - * @return the size of this compound - */ - public int size() { - return value.size(); - } + /** + * Returns the size of this compound. + * + * @return the size of this compound + */ + public int size() { + return value.size(); + } - @Override - public Map getValue() { - return value; - } + @Override + public Map getValue() { + return value; + } - @Override - public NBTType getType() { - return NBTType.COMPOUND; - } + @Override + public NBTType getType() { + return NBTType.COMPOUND; + } - /** - * Returns a tag named with the given key. - * - * @param key the key - * @return a byte - * @throws NoSuchElementException if there is no tag with given name - */ - public NBTTag getTag(String key) { - if (!hasKey(key)) throw new NoSuchElementException(key); - return value.get(key); - } + /** + * Returns a tag named with the given key. + * + * @param key the key + * @return a byte + * @throws NoSuchElementException if there is no tag with given name + */ + public NBTTag getTag(String key) { + if (!hasKey(key)) throw new NoSuchElementException(key); + return value.get(key); + } - /** - * Returns a byte named with the given key. - * - * @param key the key - * @return a byte - * @throws NoSuchElementException if there is no byte with given name - */ - public byte getByte(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTByte)) throw new NoSuchElementException(key); - return ((NBTByte) tag).getValue(); - } + /** + * Returns a byte named with the given key. + * + * @param key the key + * @return a byte + * @throws NoSuchElementException if there is no byte with given name + */ + public byte getByte(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTByte)) throw new NoSuchElementException(key); + return ((NBTByte) tag).getValue(); + } - /** - * Returns an short named with the given key. - * - * @param key the key - * @return an short - * @throws NoSuchElementException if there is no short with given name - */ - public short getShort(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTShort)) throw new NoSuchElementException(key); - return ((NBTShort) tag).getValue(); - } + /** + * Returns an short named with the given key. + * + * @param key the key + * @return an short + * @throws NoSuchElementException if there is no short with given name + */ + public short getShort(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTShort)) throw new NoSuchElementException(key); + return ((NBTShort) tag).getValue(); + } - /** - * Returns an int named with the given key. - * - * @param key the key - * @return an int - * @throws NoSuchElementException if there is no int with given name - */ - public int getInt(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTInt)) throw new NoSuchElementException(key); - return ((NBTInt) tag).getValue(); - } + /** + * Returns an int named with the given key. + * + * @param key the key + * @return an int + * @throws NoSuchElementException if there is no int with given name + */ + public int getInt(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTInt)) throw new NoSuchElementException(key); + return ((NBTInt) tag).getValue(); + } - /** - * Returns an long named with the given key. - * - * @param key the key - * @return an long - * @throws NoSuchElementException if there is no long with given name - */ - public long getLong(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTLong)) throw new NoSuchElementException(key); - return ((NBTLong) tag).getValue(); - } + /** + * Returns an long named with the given key. + * + * @param key the key + * @return an long + * @throws NoSuchElementException if there is no long with given name + */ + public long getLong(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTLong)) throw new NoSuchElementException(key); + return ((NBTLong) tag).getValue(); + } - /** - * Returns float named with the given key. - * - * @param key the key - * @return a float - * @throws NoSuchElementException if there is no float with given name - */ - public float getFloat(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTFloat)) throw new NoSuchElementException(key); - return ((NBTFloat) tag).getValue(); - } + /** + * Returns float named with the given key. + * + * @param key the key + * @return a float + * @throws NoSuchElementException if there is no float with given name + */ + public float getFloat(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTFloat)) throw new NoSuchElementException(key); + return ((NBTFloat) tag).getValue(); + } - /** - * Returns a double named with the given key. - * - * @param key the key - * @return a double - * @throws NoSuchElementException if there is no int with given name - */ - public double getDouble(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTDouble)) throw new NoSuchElementException(key); - return ((NBTDouble) tag).getValue(); - } + /** + * Returns a double named with the given key. + * + * @param key the key + * @return a double + * @throws NoSuchElementException if there is no int with given name + */ + public double getDouble(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTDouble)) throw new NoSuchElementException(key); + return ((NBTDouble) tag).getValue(); + } - /** - * Returns a byte array named with the given key. - * - * @param key the key - * @return a byte array - * @throws NoSuchElementException if there is no int with given name - */ - public byte[] getByteArray(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTByteArray)) throw new NoSuchElementException(key); - return ((NBTByteArray) tag).getValue(); - } + /** + * Returns a byte array named with the given key. + * + * @param key the key + * @return a byte array + * @throws NoSuchElementException if there is no int with given name + */ + public byte[] getByteArray(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTByteArray)) throw new NoSuchElementException(key); + return ((NBTByteArray) tag).getValue(); + } - /** - * Returns a string named with the given key. - * - * @param key the key - * @return a string - * @throws NoSuchElementException if there is no int with given name - */ - public String getString(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTString)) throw new NoSuchElementException(key); - return ((NBTString) tag).getValue(); - } + /** + * Returns a string named with the given key. + * + * @param key the key + * @return a string + * @throws NoSuchElementException if there is no int with given name + */ + public String getString(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTString)) throw new NoSuchElementException(key); + return ((NBTString) tag).getValue(); + } - /** - * Returns a list named with the given key. - * - * @param key the key - * @return a list - * @throws NoSuchElementException if there is no int with given name - */ - public List getList(String key) { - return getTagList(key).getValue(); - } + /** + * Returns a list named with the given key. + * + * @param key the key + * @return a list + * @throws NoSuchElementException if there is no int with given name + */ + public List getList(String key) { + return getTagList(key).getValue(); + } - /** - * Returns a list named with the given key. - * - * @param key the key - * @return a list - * @throws NoSuchElementException if there is no list with given name - */ - public NBTList getTagList(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTList)) throw new NoSuchElementException(key); - return (NBTList) tag; - } + /** + * Returns a list named with the given key. + * + * @param key the key + * @return a list + * @throws NoSuchElementException if there is no list with given name + */ + public NBTList getTagList(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTList)) throw new NoSuchElementException(key); + return (NBTList) tag; + } - /** - * Returns a list named with the given key. - * - * @param key the key - * @return a list - * @throws NoSuchElementException if there is no compound with given name - */ - public Map getCompound(String key) { - return getCompoundTag(key).getValue(); - } + /** + * Returns a list named with the given key. + * + * @param key the key + * @return a list + * @throws NoSuchElementException if there is no compound with given name + */ + public Map getCompound(String key) { + return getCompoundTag(key).getValue(); + } - /** - * Returns a compound named with the given key. - * - * @param key the key - * @return a compound - * @throws NoSuchElementException if there is no compound with given name - */ - public NBTCompound getCompoundTag(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTCompound)) throw new NoSuchElementException(key); - return (NBTCompound) tag; - } + /** + * Returns a compound named with the given key. + * + * @param key the key + * @return a compound + * @throws NoSuchElementException if there is no compound with given name + */ + public NBTCompound getCompoundTag(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTCompound)) throw new NoSuchElementException(key); + return (NBTCompound) tag; + } - /** - * Returns an int array named with the given key. - * - * @param key the key - * @return a int array - * @throws NoSuchElementException if there is no int array with given name - */ - public int[] getIntArray(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTIntArray)) throw new NoSuchElementException(key); - return ((NBTIntArray) tag).getValue(); - } + /** + * Returns an int array named with the given key. + * + * @param key the key + * @return a int array + * @throws NoSuchElementException if there is no int array with given name + */ + public int[] getIntArray(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTIntArray)) throw new NoSuchElementException(key); + return ((NBTIntArray) tag).getValue(); + } - /** - * Returns a long array named with the given key. - * - * @param key the key - * @return a int array - * @throws NoSuchElementException if there is no int array with given name - */ - public long[] getLongArray(String key) { - NBTTag tag = value.get(key); - if (!(tag instanceof NBTLongArray)) throw new NoSuchElementException(key); - return ((NBTLongArray) tag).getValue(); - } + /** + * Returns a long array named with the given key. + * + * @param key the key + * @return a int array + * @throws NoSuchElementException if there is no int array with given name + */ + public long[] getLongArray(String key) { + NBTTag tag = value.get(key); + if (!(tag instanceof NBTLongArray)) throw new NoSuchElementException(key); + return ((NBTLongArray) tag).getValue(); + } - /** - * Returns an immutable set containing all the keys in this compound. - * - * @return an immutable set - */ - public Set getKeys() { - return Collections.unmodifiableSet(value.keySet()); - } + /** + * Returns an immutable set containing all the keys in this compound. + * + * @return an immutable set + */ + public Set getKeys() { + return Collections.unmodifiableSet(value.keySet()); + } - // PREDICATES + // PREDICATES - /** - * Returns whether this compound is empty. - * - * @return whether this compound is empty - */ - public boolean isEmpty() { - return value.isEmpty(); - } + /** + * Returns whether this compound is empty. + * + * @return whether this compound is empty + */ + public boolean isEmpty() { + return value.isEmpty(); + } - /** - * Returns whether this compound tag contains the given key. - * - * @param key the given key - * @return true if the tag contains the given key - */ - public boolean hasKey(String key) { - return value.containsKey(key); - } + /** + * Returns whether this compound tag contains the given key. + * + * @param key the given key + * @return true if the tag contains the given key + */ + public boolean hasKey(String key) { + return value.containsKey(key); + } - /** - * Returns whether this compound tag contains the given key and its value is of a given type. - * - * @param key the given key - * @param type the type of the value - * @return true if the tag contains an entry with given key and of given type - */ - public boolean hasKeyOfType(String key, NBTType type) { - Objects.requireNonNull(type); - return value.containsKey(key) && value.get(key).getType() == type; - } + /** + * Returns whether this compound tag contains the given key and its value is of a given type. + * + * @param key the given key + * @param type the type of the value + * @return true if the tag contains an entry with given key and of given type + */ + public boolean hasKeyOfType(String key, NBTType type) { + Objects.requireNonNull(type); + return value.containsKey(key) && value.get(key).getType() == type; + } - // MUTATORS + // MUTATORS - /** - * Put the given name and its corresponding tag into the compound tag. - * - * @param name the tag name - * @param tag the tag value - */ - public void put(String name, NBTTag tag) { - this.value.put(name, tag); - } + /** + * Put the given name and its corresponding tag into the compound tag. + * + * @param name the tag name + * @param tag the tag value + */ + public void put(String name, NBTTag tag) { + this.value.put(name, tag); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putByteArray(String key, byte[] value) { - put(key, new NBTByteArray(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putByteArray(String key, byte[] value) { + put(key, new NBTByteArray(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putByte(String key, byte value) { - put(key, new NBTByte(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putByte(String key, byte value) { + put(key, new NBTByte(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putDouble(String key, double value) { - put(key, new NBTDouble(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putDouble(String key, double value) { + put(key, new NBTDouble(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putFloat(String key, float value) { - put(key, new NBTFloat(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putFloat(String key, float value) { + put(key, new NBTFloat(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putIntArray(String key, int[] value) { - put(key, new NBTIntArray(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putIntArray(String key, int[] value) { + put(key, new NBTIntArray(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putLongArray(String key, long[] value) { - put(key, new NBTLongArray(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putLongArray(String key, long[] value) { + put(key, new NBTLongArray(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the valu - */ - public void putInt(String key, int value) { - put(key, new NBTInt(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the valu + */ + public void putInt(String key, int value) { + put(key, new NBTInt(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putLong(String key, long value) { - put(key, new NBTLong(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putLong(String key, long value) { + put(key, new NBTLong(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putShort(String key, short value) { - put(key, new NBTShort(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putShort(String key, short value) { + put(key, new NBTShort(value)); + } - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void putString(String key, String value) { - put(key, new NBTString(value)); - } + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void putString(String key, String value) { + put(key, new NBTString(value)); + } - // ITERATION + // ITERATION - /** - * Performs an action for every pair of keys and tags. - * - * @param action the action - */ - public void forEach(BiConsumer action) { - this.value.forEach(action); - } + /** + * Performs an action for every pair of keys and tags. + * + * @param action the action + */ + public void forEach(BiConsumer action) { + this.value.forEach(action); + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTCompound && equals((NBTCompound) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTCompound && equals((NBTCompound) obj); + } - public boolean equals(NBTCompound tag) { - return this.isEmpty() && tag.isEmpty() - || this.value.equals(tag.value); - } + public boolean equals(NBTCompound tag) { + return this.isEmpty() && tag.isEmpty() + || this.value.equals(tag.value); + } - @Override - public String toMSONString() { - StringBuilder builder = new StringBuilder("{"); - Set keys = this.value.keySet(); + @Override + public String toMSONString() { + StringBuilder builder = new StringBuilder("{"); + Set keys = this.value.keySet(); - for (String key : keys) { - if (builder.length() > 1) { - builder.append(','); - } - builder - .append(SIMPLE_STRING.matcher(key).matches() ? key : NBTString.toMSONString(key)) - .append(':') - .append(this.value.get(key).toMSONString()); - } + for (String key : keys) { + if (builder.length() > 1) { + builder.append(','); + } + builder + .append(SIMPLE_STRING.matcher(key).matches() ? key : NBTString.toMSONString(key)) + .append(':') + .append(this.value.get(key).toMSONString()); + } - return builder.append("}").toString(); - } + return builder.append("}").toString(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTDouble.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTDouble.java index 2245a48..89f3d47 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTDouble.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTDouble.java @@ -10,54 +10,54 @@ package me.filoghost.chestcommands.util.nbt; */ public final class NBTDouble extends NBTTag implements Cloneable { - private double value; + private double value; - public NBTDouble(double value) { - this.value = value; - } + public NBTDouble(double value) { + this.value = value; + } - @Override - public Double getValue() { - return value; - } + @Override + public Double getValue() { + return value; + } - public double getDoubleValue() { - return value; - } + public double getDoubleValue() { + return value; + } - public void setDoubleValue(double value) { - this.value = value; - } + public void setDoubleValue(double value) { + this.value = value; + } - @Override - public NBTType getType() { - return NBTType.DOUBLE; - } + @Override + public NBTType getType() { + return NBTType.DOUBLE; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTDouble && equals((NBTDouble) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTDouble && equals((NBTDouble) obj); + } - public boolean equals(NBTDouble tag) { - return this.value == tag.value; - } + public boolean equals(NBTDouble tag) { + return this.value == tag.value; + } - @Override - public int hashCode() { - return Double.hashCode(value); - } + @Override + public int hashCode() { + return Double.hashCode(value); + } - @Override - public String toMSONString() { - return value + "d"; - } + @Override + public String toMSONString() { + return value + "d"; + } - @Override - public NBTDouble clone() { - return new NBTDouble(value); - } + @Override + public NBTDouble clone() { + return new NBTDouble(value); + } } \ No newline at end of file diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTFloat.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTFloat.java index 75cb101..9eabb32 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTFloat.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTFloat.java @@ -10,54 +10,54 @@ package me.filoghost.chestcommands.util.nbt; */ public final class NBTFloat extends NBTTag implements Cloneable { - private float value; + private float value; - public NBTFloat(float value) { - this.value = value; - } + public NBTFloat(float value) { + this.value = value; + } - @Override - public Float getValue() { - return value; - } + @Override + public Float getValue() { + return value; + } - public float getFloatValue() { - return value; - } + public float getFloatValue() { + return value; + } - public void setFloatValue(float value) { - this.value = value; - } + public void setFloatValue(float value) { + this.value = value; + } - @Override - public NBTType getType() { - return NBTType.FLOAT; - } + @Override + public NBTType getType() { + return NBTType.FLOAT; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTFloat && equals((NBTFloat) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTFloat && equals((NBTFloat) obj); + } - public boolean equals(NBTFloat tag) { - return this.value == tag.value; - } + public boolean equals(NBTFloat tag) { + return this.value == tag.value; + } - @Override - public int hashCode() { - return Float.hashCode(value); - } + @Override + public int hashCode() { + return Float.hashCode(value); + } - @Override - public String toMSONString() { - return value + "f"; - } + @Override + public String toMSONString() { + return value + "f"; + } - @Override - public NBTFloat clone() { - return new NBTFloat(value); - } + @Override + public NBTFloat clone() { + return new NBTFloat(value); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTInt.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTInt.java index 7fa95eb..0c88ee4 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTInt.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTInt.java @@ -10,54 +10,54 @@ package me.filoghost.chestcommands.util.nbt; */ public final class NBTInt extends NBTTag implements Cloneable { - private int value; + private int value; - public NBTInt(int value) { - this.value = value; - } + public NBTInt(int value) { + this.value = value; + } - @Override - public Integer getValue() { - return value; - } + @Override + public Integer getValue() { + return value; + } - public int getIntValue() { - return value; - } + public int getIntValue() { + return value; + } - public void setIntValue(int value) { - this.value = value; - } + public void setIntValue(int value) { + this.value = value; + } - @Override - public NBTType getType() { - return NBTType.INT; - } + @Override + public NBTType getType() { + return NBTType.INT; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTInt && equals((NBTInt) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTInt && equals((NBTInt) obj); + } - public boolean equals(NBTInt tag) { - return this.value == tag.value; - } + public boolean equals(NBTInt tag) { + return this.value == tag.value; + } - @Override - public int hashCode() { - return Integer.hashCode(value); - } + @Override + public int hashCode() { + return Integer.hashCode(value); + } - @Override - public String toMSONString() { - return Integer.toString(value); - } + @Override + public String toMSONString() { + return Integer.toString(value); + } - @Override - public NBTInt clone() { - return new NBTInt(value); - } + @Override + public NBTInt clone() { + return new NBTInt(value); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTIntArray.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTIntArray.java index bf07c9d..0d75a64 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTIntArray.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTIntArray.java @@ -13,68 +13,68 @@ import java.util.Objects; */ public final class NBTIntArray extends NBTTag implements Cloneable { - private final int[] value; + private final int[] value; - /** - * Creates the tag with an empty name. - * - * @param value the value of the tag - */ - public NBTIntArray(int[] value) { - this.value = Objects.requireNonNull(value); - } + /** + * Creates the tag with an empty name. + * + * @param value the value of the tag + */ + public NBTIntArray(int[] value) { + this.value = Objects.requireNonNull(value); + } - public NBTIntArray(Number[] numbers) { - this.value = new int[numbers.length]; - for (int i = 0; i < numbers.length; i++) - value[i] = numbers[i].intValue(); - } + public NBTIntArray(Number[] numbers) { + this.value = new int[numbers.length]; + for (int i = 0; i < numbers.length; i++) + value[i] = numbers[i].intValue(); + } - /** - * Returns the length of this array. - * - * @return the length of this array - */ - public int length() { - return value.length; - } + /** + * Returns the length of this array. + * + * @return the length of this array + */ + public int length() { + return value.length; + } - @Override - public int[] getValue() { - return value; - } + @Override + public int[] getValue() { + return value; + } - @Override - public NBTType getType() { - return NBTType.INT_ARRAY; - } + @Override + public NBTType getType() { + return NBTType.INT_ARRAY; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTIntArray && equals((NBTIntArray) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTIntArray && equals((NBTIntArray) obj); + } - public boolean equals(NBTIntArray tag) { - return Arrays.equals(this.value, tag.value); - } + public boolean equals(NBTIntArray tag) { + return Arrays.equals(this.value, tag.value); + } - @Override - public String toMSONString() { - StringBuilder stringbuilder = new StringBuilder("[I;"); - for (int i = 0; i < this.value.length; i++) { - if (i != 0) { - stringbuilder.append(','); - } - stringbuilder.append(this.value[i]); - } - return stringbuilder.append(']').toString(); - } + @Override + public String toMSONString() { + StringBuilder stringbuilder = new StringBuilder("[I;"); + for (int i = 0; i < this.value.length; i++) { + if (i != 0) { + stringbuilder.append(','); + } + stringbuilder.append(this.value[i]); + } + return stringbuilder.append(']').toString(); + } - @Override - public NBTIntArray clone() { - return new NBTIntArray(value); - } + @Override + public NBTIntArray clone() { + return new NBTIntArray(value); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTList.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTList.java index 7c8d5c7..c702bd4 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTList.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTList.java @@ -17,177 +17,177 @@ import java.util.NoSuchElementException; */ public final class NBTList extends NBTTag implements Iterable, Cloneable { - private NBTType type; + private NBTType type; - private final List list = new ArrayList<>(); + private final List list = new ArrayList<>(); - /** - * Creates the list with a type and a series of elements. - * - * @param type the type of tag - * @param value the value of the tag - */ - public NBTList(NBTType type, List value) { - this.type = type; - for (NBTTag entry : value) { - this.add(entry); - } - } + /** + * Creates the list with a type and a series of elements. + * + * @param type the type of tag + * @param value the value of the tag + */ + public NBTList(NBTType type, List value) { + this.type = type; + for (NBTTag entry : value) { + this.add(entry); + } + } - /** - * Creates the list with a type and a series of elements. - * - * @param type the type of tag - * @param value the value of the tag - */ - public NBTList(NBTType type, NBTTag... value) { - this(type, Arrays.asList(value)); - } + /** + * Creates the list with a type and a series of elements. + * + * @param type the type of tag + * @param value the value of the tag + */ + public NBTList(NBTType type, NBTTag... value) { + this(type, Arrays.asList(value)); + } - /** - * Creates an empty list with a type. - * - * @param type the type of tag or null if the list has no type yet - */ - public NBTList(NBTType type) { - this.type = type; - } + /** + * Creates an empty list with a type. + * + * @param type the type of tag or null if the list has no type yet + */ + public NBTList(NBTType type) { + this.type = type; + } - /** - * Creates an empty list without a type. - */ - public NBTList() { - this(null); - } + /** + * Creates an empty list without a type. + */ + public NBTList() { + this(null); + } - // GETTERS + // GETTERS - /** - * Returns the size of this list. - * - * @return the size of this list - */ - public int size() { - return list.size(); - } + /** + * Returns the size of this list. + * + * @return the size of this list + */ + public int size() { + return list.size(); + } - @Override - public List getValue() { - return list; - } + @Override + public List getValue() { + return list; + } - @Override - public NBTType getType() { - return NBTType.LIST; - } + @Override + public NBTType getType() { + return NBTType.LIST; + } - /** - * Gets the type of elements in this list. - * - * @return The type of elements in this list. - */ - public NBTType getElementType() { - return type; - } + /** + * Gets the type of elements in this list. + * + * @return The type of elements in this list. + */ + public NBTType getElementType() { + return type; + } - /** - * Returns a tag named with the given index. - * - * @param index the index - * @return a byte - * @throws NoSuchElementException if there is no tag with given index - */ - public NBTTag get(int index) { - return list.get(index); - } + /** + * Returns a tag named with the given index. + * + * @param index the index + * @return a byte + * @throws NoSuchElementException if there is no tag with given index + */ + public NBTTag get(int index) { + return list.get(index); + } - // PREDICATES + // PREDICATES - /** - * Returns whether this list is empty. - * - * @return whether this list is empty - */ - public boolean isEmpty() { - return list.isEmpty(); - } + /** + * Returns whether this list is empty. + * + * @return whether this list is empty + */ + public boolean isEmpty() { + return list.isEmpty(); + } - // MUTATORS + // MUTATORS - /** - * Add the given tag. - * - * @param value the tag - */ - public void add(NBTTag value) { - if (this.type == null) - this.type = value.getType(); - else if (this.type != value.getType()) - throw new IllegalArgumentException(value.getType() + " is not of expected type " + type); - list.add(value); - } + /** + * Add the given tag. + * + * @param value the tag + */ + public void add(NBTTag value) { + if (this.type == null) + this.type = value.getType(); + else if (this.type != value.getType()) + throw new IllegalArgumentException(value.getType() + " is not of expected type " + type); + list.add(value); + } - /** - * Add the given tag at the given index in the list. - * - * @param value the tag - */ - public void add(int index, NBTTag value) { - if (index < 0 || index >= list.size()) - throw new IndexOutOfBoundsException(Integer.toString(index)); - if (this.type == null) - this.type = value.getType(); - else if (this.type != value.getType()) - throw new IllegalArgumentException(value.getType() + " is not of expected type " + type); - list.add(index, value); - } + /** + * Add the given tag at the given index in the list. + * + * @param value the tag + */ + public void add(int index, NBTTag value) { + if (index < 0 || index >= list.size()) + throw new IndexOutOfBoundsException(Integer.toString(index)); + if (this.type == null) + this.type = value.getType(); + else if (this.type != value.getType()) + throw new IllegalArgumentException(value.getType() + " is not of expected type " + type); + list.add(index, value); + } - /** - * Add all the tags in the given list. - * - * @param values a list of tags - */ - public void addAll(Collection values) { - for (NBTTag entry : values) { - this.add(entry); - } - } + /** + * Add all the tags in the given list. + * + * @param values a list of tags + */ + public void addAll(Collection values) { + for (NBTTag entry : values) { + this.add(entry); + } + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTList && equals((NBTList) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTList && equals((NBTList) obj); + } - public boolean equals(NBTList tag) { - return this.isEmpty() && tag.isEmpty() - || this.type == tag.type && this.list.equals(tag.list); - } + public boolean equals(NBTList tag) { + return this.isEmpty() && tag.isEmpty() + || this.type == tag.type && this.list.equals(tag.list); + } - @Override - public Iterator iterator() { - return list.iterator(); - } + @Override + public Iterator iterator() { + return list.iterator(); + } - @Override - public String toMSONString() { - StringBuilder builder = new StringBuilder("["); - Iterator iter = iterator(); + @Override + public String toMSONString() { + StringBuilder builder = new StringBuilder("["); + Iterator iter = iterator(); - boolean first = true; - while (iter.hasNext()) { - if (first) first = false; - else builder.append(','); - builder.append(iter.next().toMSONString()); - } + boolean first = true; + while (iter.hasNext()) { + if (first) first = false; + else builder.append(','); + builder.append(iter.next().toMSONString()); + } - return builder.append("]").toString(); - } + return builder.append("]").toString(); + } - @Override - public NBTList clone() { - return new NBTList(type, list); - } + @Override + public NBTList clone() { + return new NBTList(type, list); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTLong.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTLong.java index 33cca56..23fe818 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTLong.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTLong.java @@ -10,54 +10,54 @@ package me.filoghost.chestcommands.util.nbt; */ public final class NBTLong extends NBTTag implements Cloneable { - private long value; + private long value; - public NBTLong(long value) { - this.value = value; - } + public NBTLong(long value) { + this.value = value; + } - @Override - public Long getValue() { - return value; - } + @Override + public Long getValue() { + return value; + } - public long getLongValue() { - return value; - } + public long getLongValue() { + return value; + } - public void setLongValue(long value) { - this.value = value; - } + public void setLongValue(long value) { + this.value = value; + } - @Override - public NBTType getType() { - return NBTType.LONG; - } + @Override + public NBTType getType() { + return NBTType.LONG; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTLong && equals((NBTLong) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTLong && equals((NBTLong) obj); + } - public boolean equals(NBTLong tag) { - return this.value == tag.value; - } + public boolean equals(NBTLong tag) { + return this.value == tag.value; + } - @Override - public int hashCode() { - return Long.hashCode(value); - } + @Override + public int hashCode() { + return Long.hashCode(value); + } - @Override - public String toMSONString() { - return value + "L"; - } + @Override + public String toMSONString() { + return value + "L"; + } - @Override - public NBTLong clone() { - return new NBTLong(value); - } + @Override + public NBTLong clone() { + return new NBTLong(value); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTLongArray.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTLongArray.java index d605bc1..6540759 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTLongArray.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTLongArray.java @@ -12,63 +12,63 @@ import java.util.Arrays; */ public final class NBTLongArray extends NBTTag { - private final long[] value; + private final long[] value; - /** - * Creates the tag with an empty name. - * - * @param value the value of the tag - */ - public NBTLongArray(long... value) { - this.value = value; - } + /** + * Creates the tag with an empty name. + * + * @param value the value of the tag + */ + public NBTLongArray(long... value) { + this.value = value; + } - public NBTLongArray(Number[] numbers) { - this.value = new long[numbers.length]; - for (int i = 0; i < numbers.length; i++) - value[i] = numbers[i].longValue(); - } + public NBTLongArray(Number[] numbers) { + this.value = new long[numbers.length]; + for (int i = 0; i < numbers.length; i++) + value[i] = numbers[i].longValue(); + } - /** - * Returns the length of this array. - * - * @return the length of this array - */ - public int length() { - return value.length; - } + /** + * Returns the length of this array. + * + * @return the length of this array + */ + public int length() { + return value.length; + } - @Override - public long[] getValue() { - return value; - } + @Override + public long[] getValue() { + return value; + } - @Override - public NBTType getType() { - return NBTType.LONG_ARRAY; - } + @Override + public NBTType getType() { + return NBTType.LONG_ARRAY; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTLongArray && equals((NBTLongArray) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTLongArray && equals((NBTLongArray) obj); + } - public boolean equals(NBTLongArray tag) { - return Arrays.equals(this.value, tag.value); - } + public boolean equals(NBTLongArray tag) { + return Arrays.equals(this.value, tag.value); + } - @Override - public String toMSONString() { - StringBuilder stringbuilder = new StringBuilder("[I;"); - for (int i = 0; i < this.value.length; i++) { - if (i != 0) { - stringbuilder.append(','); - } - stringbuilder.append(this.value[i]); - } - return stringbuilder.append(']').toString(); - } + @Override + public String toMSONString() { + StringBuilder stringbuilder = new StringBuilder("[I;"); + for (int i = 0; i < this.value.length; i++) { + if (i != 0) { + stringbuilder.append(','); + } + stringbuilder.append(this.value[i]); + } + return stringbuilder.append(']').toString(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTShort.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTShort.java index 5287a78..2355360 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTShort.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTShort.java @@ -10,54 +10,54 @@ package me.filoghost.chestcommands.util.nbt; */ public final class NBTShort extends NBTTag implements Cloneable { - private short value; + private short value; - public NBTShort(short value) { - this.value = value; - } + public NBTShort(short value) { + this.value = value; + } - @Override - public Short getValue() { - return value; - } + @Override + public Short getValue() { + return value; + } - public short getShortValue() { - return value; - } + public short getShortValue() { + return value; + } - public void setShortValue(short value) { - this.value = value; - } + public void setShortValue(short value) { + this.value = value; + } - @Override - public NBTType getType() { - return NBTType.SHORT; - } + @Override + public NBTType getType() { + return NBTType.SHORT; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NBTShort && equals((NBTShort) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NBTShort && equals((NBTShort) obj); + } - public boolean equals(NBTShort tag) { - return this.value == tag.value; - } + public boolean equals(NBTShort tag) { + return this.value == tag.value; + } - @Override - public int hashCode() { - return Short.hashCode(value); - } + @Override + public int hashCode() { + return Short.hashCode(value); + } - @Override - public String toMSONString() { - return value + "s"; - } + @Override + public String toMSONString() { + return value + "s"; + } - @Override - public NBTShort clone() { - return new NBTShort(value); - } + @Override + public NBTShort clone() { + return new NBTShort(value); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTString.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTString.java index 7a8572a..3a93f6f 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTString.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTString.java @@ -10,62 +10,62 @@ package me.filoghost.chestcommands.util.nbt; */ public final class NBTString extends NBTTag implements Cloneable { - private String value; + private String value; - public NBTString(String value) { - setValue(value); - } + public NBTString(String value) { + setValue(value); + } - @Override - public String getValue() { - return value; - } + @Override + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } - @Override - public NBTType getType() { - return NBTType.STRING; - } + @Override + public NBTType getType() { + return NBTType.STRING; + } - // MISC + // MISC - @Override - public int hashCode() { - return value.hashCode(); - } + @Override + public int hashCode() { + return value.hashCode(); + } - @Override - public String toMSONString() { - return toMSONString(value); - } + @Override + public String toMSONString() { + return toMSONString(value); + } - @Override - public NBTString clone() { - return new NBTString(value); - } + @Override + public NBTString clone() { + return new NBTString(value); + } - // UTIL + // UTIL - /** - * Converts a regular string into a Mojangson string by surrounding it with quotes and escaping backslashes and - * quotes inside it. - * - * @param str the string - * @return the Mojangson string - */ - public static String toMSONString(String str) { - StringBuilder builder = new StringBuilder("\""); - char[] chars = str.toCharArray(); - for (char c : chars) { - if ((c == '\\') || (c == '"')) { - builder.append('\\'); - } - builder.append(c); - } - return builder.append('\"').toString(); - } + /** + * Converts a regular string into a Mojangson string by surrounding it with quotes and escaping backslashes and + * quotes inside it. + * + * @param str the string + * @return the Mojangson string + */ + public static String toMSONString(String str) { + StringBuilder builder = new StringBuilder("\""); + char[] chars = str.toCharArray(); + for (char c : chars) { + if ((c == '\\') || (c == '"')) { + builder.append('\\'); + } + builder.append(c); + } + return builder.append('\"').toString(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTTag.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTTag.java index e57168c..ae3d6f2 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTTag.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTTag.java @@ -10,56 +10,56 @@ package me.filoghost.chestcommands.util.nbt; */ public abstract class NBTTag { - /** - * Gets the value of this tag. - * - * @return the value of this tag - */ - public abstract Object getValue(); + /** + * Gets the value of this tag. + * + * @return the value of this tag + */ + public abstract Object getValue(); - /** - * Returns the type of this tag. - * - * @return the type of this tag - */ - public abstract NBTType getType(); + /** + * Returns the type of this tag. + * + * @return the type of this tag + */ + public abstract NBTType getType(); - /** - * Convenience method for getting the id of this tag's type. - * - * @return the type id - */ - public byte getTypeId() { - return getType().getId(); - } + /** + * Convenience method for getting the id of this tag's type. + * + * @return the type id + */ + public byte getTypeId() { + return getType().getId(); + } - /** - * Returns a Mojangson string depicting this NBT tag. - * - * @return a Mojangson string depicting this NBT tag - */ - public abstract String toMSONString(); + /** + * Returns a Mojangson string depicting this NBT tag. + * + * @return a Mojangson string depicting this NBT tag + */ + public abstract String toMSONString(); - // MISC + // MISC - @Override - public boolean equals(Object obj) { - if (obj instanceof NBTTag) { - NBTTag tag = (NBTTag) obj; - return this.getType() == tag.getType() - && this.getValue().equals(tag.getValue()); - } - return false; - } + @Override + public boolean equals(Object obj) { + if (obj instanceof NBTTag) { + NBTTag tag = (NBTTag) obj; + return this.getType() == tag.getType() + && this.getValue().equals(tag.getValue()); + } + return false; + } - @Override - public int hashCode() { - return getValue().hashCode(); - } + @Override + public int hashCode() { + return getValue().hashCode(); + } - @Override - public String toString() { - return toMSONString(); - } + @Override + public String toString() { + return toMSONString(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTType.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTType.java index 636d9e9..e53acfa 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTType.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/NBTType.java @@ -19,179 +19,179 @@ package me.filoghost.chestcommands.util.nbt; *

*/ public enum NBTType { - /** - * Used to mark the end of compounds tags. May also be the type of empty list tags. - * - * @since NBT Version 19132 - */ - END("TAG_End", false, false, false), + /** + * Used to mark the end of compounds tags. May also be the type of empty list tags. + * + * @since NBT Version 19132 + */ + END("TAG_End", false, false, false), - /** - * A signed integer (8 bits). Sometimes used for booleans. (-128 to 127) - * - * @since NBT Version 19132 - */ - BYTE("TAG_Byte", true, true, false), + /** + * A signed integer (8 bits). Sometimes used for booleans. (-128 to 127) + * + * @since NBT Version 19132 + */ + BYTE("TAG_Byte", true, true, false), - /** - * A signed integer (16 bits). (-215 to 215-1) - * - * @since NBT Version 19132 - */ - SHORT("TAG_Short", true, true, false), + /** + * A signed integer (16 bits). (-215 to 215-1) + * + * @since NBT Version 19132 + */ + SHORT("TAG_Short", true, true, false), - /** - * A signed integer (32 bits). (-231 to 231-1) - * - * @since NBT Version 19132 - */ - INT("TAG_Int", true, true, false), + /** + * A signed integer (32 bits). (-231 to 231-1) + * + * @since NBT Version 19132 + */ + INT("TAG_Int", true, true, false), - /** - * A signed integer (64 bits). (-263 to 263-1) - * - * @since NBT Version 19132 - */ - LONG("TAG_Long", true, true, false), + /** + * A signed integer (64 bits). (-263 to 263-1) + * + * @since NBT Version 19132 + */ + LONG("TAG_Long", true, true, false), - /** - * A signed (IEEE 754-2008) floating point number (32 bits). - * - * @since NBT Version 19132 - */ - FLOAT("TAG_Float", true, true, false), + /** + * A signed (IEEE 754-2008) floating point number (32 bits). + * + * @since NBT Version 19132 + */ + FLOAT("TAG_Float", true, true, false), - /** - * A signed (IEEE 754-2008) floating point number (64 bits). - * - * @since NBT Version 19132 - */ - DOUBLE("TAG_Double", true, true, false), + /** + * A signed (IEEE 754-2008) floating point number (64 bits). + * + * @since NBT Version 19132 + */ + DOUBLE("TAG_Double", true, true, false), - /** - * An array of {@link #BYTE} with maximum length of {@link Integer#MAX_VALUE}. - * - * @since NBT Version 19132 - */ - BYTE_ARRAY("TAG_Byte_Array", false, false, true), + /** + * An array of {@link #BYTE} with maximum length of {@link Integer#MAX_VALUE}. + * + * @since NBT Version 19132 + */ + BYTE_ARRAY("TAG_Byte_Array", false, false, true), - /** - * UTF-8 encoded string. - * - * @since NBT Version 19132 - */ - STRING("TAG_String", true, false, false), + /** + * UTF-8 encoded string. + * + * @since NBT Version 19132 + */ + STRING("TAG_String", true, false, false), - /** - * A list of unnamed tags of equal type. - * - * @since NBT Version 19132 - */ - LIST("TAG_List", false, false, false), + /** + * A list of unnamed tags of equal type. + * + * @since NBT Version 19132 + */ + LIST("TAG_List", false, false, false), - /** - * Compound of named tags followed by {@link #END}. - * - * @since NBT Version 19132 - */ - COMPOUND("TAG_Compound", false, false, false), + /** + * Compound of named tags followed by {@link #END}. + * + * @since NBT Version 19132 + */ + COMPOUND("TAG_Compound", false, false, false), - /** - * An array of {@link #BYTE} with maximum length of {@link Integer#MAX_VALUE}. - * - * @since NBT Version 19132 - */ - INT_ARRAY("TAG_Int_Array", false, false, true), + /** + * An array of {@link #BYTE} with maximum length of {@link Integer#MAX_VALUE}. + * + * @since NBT Version 19132 + */ + INT_ARRAY("TAG_Int_Array", false, false, true), - /** - * An array of {@link #LONG} with maximum length of {@link Integer#MAX_VALUE}. - * - * @since NBT Version 19133 - */ - LONG_ARRAY("TAG_Long_Array", false, false, true); + /** + * An array of {@link #LONG} with maximum length of {@link Integer#MAX_VALUE}. + * + * @since NBT Version 19133 + */ + LONG_ARRAY("TAG_Long_Array", false, false, true); - private final String name; - private final boolean numeric, primitive, array; - private final byte id; + private final String name; + private final boolean numeric, primitive, array; + private final byte id; - NBTType(String name, boolean primitive, boolean numeric, boolean array) { - this.name = name; - this.id = (byte) ordinal(); - this.numeric = numeric; - this.primitive = primitive; - this.array = array; - } + NBTType(String name, boolean primitive, boolean numeric, boolean array) { + this.name = name; + this.id = (byte) ordinal(); + this.numeric = numeric; + this.primitive = primitive; + this.array = array; + } - /** - * Returns the type with the given id. - * - * @param id the id - * @return the type - */ - public static NBTType getById(byte id) { - return values()[id]; - } + /** + * Returns the type with the given id. + * + * @param id the id + * @return the type + */ + public static NBTType getById(byte id) { + return values()[id]; + } - /** - *

- * Returns the id of this tag type. - *

- *

- * Although this method is currently equivalent to {@link #ordinal()}, it should always be used in its stead, - * since it is not guaranteed that this behavior will remain consistent. - *

- * - * @return the id - */ - public byte getId() { - return id; - } + /** + *

+ * Returns the id of this tag type. + *

+ *

+ * Although this method is currently equivalent to {@link #ordinal()}, it should always be used in its stead, + * since it is not guaranteed that this behavior will remain consistent. + *

+ * + * @return the id + */ + public byte getId() { + return id; + } - /** - * Returns the name of this type. - * - * @return the name - */ - public String getName() { - return name; - } + /** + * Returns the name of this type. + * + * @return the name + */ + public String getName() { + return name; + } - /** - *

- * Returns whether this tag type is numeric. - *

- *

- * All tag types with payloads that are representable as a {@link Number} are compliant with this definition. - *

- * - * @return whether this type is numeric - */ - public boolean isNumeric() { - return numeric; - } + /** + *

+ * Returns whether this tag type is numeric. + *

+ *

+ * All tag types with payloads that are representable as a {@link Number} are compliant with this definition. + *

+ * + * @return whether this type is numeric + */ + public boolean isNumeric() { + return numeric; + } - /** - * Returns whether this tag type is primitive, meaning that it is not a {@link NBTByteArray}, {@link NBTIntArray}, - * {@link NBTList}, {@link NBTCompound}. - * - * @return whether this type is numeric - */ - public boolean isPrimitive() { - return primitive; - } + /** + * Returns whether this tag type is primitive, meaning that it is not a {@link NBTByteArray}, {@link NBTIntArray}, + * {@link NBTList}, {@link NBTCompound}. + * + * @return whether this type is numeric + */ + public boolean isPrimitive() { + return primitive; + } - /** - * Returns whether this tag type is is an array type such as {@link NBTByteArray} or {@link NBTIntArray}. - * - * @return whether this type is an array type - */ - public boolean isArray() { - return array; - } + /** + * Returns whether this tag type is is an array type such as {@link NBTByteArray} or {@link NBTIntArray}. + * + * @return whether this type is an array type + */ + public boolean isArray() { + return array; + } - @Override - public String toString() { - return getName(); - } + @Override + public String toString() { + return getName(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/parser/MojangsonParseException.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/parser/MojangsonParseException.java index 3fd8cac..54289d1 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/parser/MojangsonParseException.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/parser/MojangsonParseException.java @@ -9,22 +9,22 @@ import java.io.IOException; public class MojangsonParseException extends IOException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public MojangsonParseException(String msg, String content, int index) { - super(msg + " at character " + index + ": " + printErrorLoc(content, index)); - } + public MojangsonParseException(String msg, String content, int index) { + super(msg + " at character " + index + ": " + printErrorLoc(content, index)); + } - private static String printErrorLoc(String content, int index) { - StringBuilder builder = new StringBuilder(); - int i = Math.min(content.length(), index); - if (i > 35) { - builder.append("..."); - } - builder.append(content, Math.max(0, i - 35), i); - builder.append("<--[HERE]"); + private static String printErrorLoc(String content, int index) { + StringBuilder builder = new StringBuilder(); + int i = Math.min(content.length(), index); + if (i > 35) { + builder.append("..."); + } + builder.append(content, Math.max(0, i - 35), i); + builder.append("<--[HERE]"); - return builder.toString(); - } + return builder.toString(); + } } diff --git a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/parser/MojangsonParser.java b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/parser/MojangsonParser.java index e07a864..8550081 100644 --- a/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/parser/MojangsonParser.java +++ b/plugin/src/main/java/me/filoghost/chestcommands/util/nbt/parser/MojangsonParser.java @@ -5,6 +5,9 @@ */ package me.filoghost.chestcommands.util.nbt.parser; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; import me.filoghost.chestcommands.util.nbt.NBTByte; import me.filoghost.chestcommands.util.nbt.NBTByteArray; import me.filoghost.chestcommands.util.nbt.NBTCompound; @@ -20,361 +23,357 @@ import me.filoghost.chestcommands.util.nbt.NBTString; import me.filoghost.chestcommands.util.nbt.NBTTag; import me.filoghost.chestcommands.util.nbt.NBTType; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - public final class MojangsonParser { - private static final Pattern - DOUBLE_NS = Pattern.compile("[-+]?(?:[0-9]+[.]|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?", Pattern.CASE_INSENSITIVE), - DOUBLE_S = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?d", Pattern.CASE_INSENSITIVE), - FLOAT = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?f", Pattern.CASE_INSENSITIVE), - BYTE = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)b", Pattern.CASE_INSENSITIVE), - LONG = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)l", Pattern.CASE_INSENSITIVE), - SHORT = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)s", Pattern.CASE_INSENSITIVE), - INT = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)"); + private static final Pattern + DOUBLE_NS = Pattern.compile("[-+]?(?:[0-9]+[.]|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?", Pattern.CASE_INSENSITIVE), + DOUBLE_S = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?d", Pattern.CASE_INSENSITIVE), + FLOAT = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?f", Pattern.CASE_INSENSITIVE), + BYTE = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)b", Pattern.CASE_INSENSITIVE), + LONG = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)l", Pattern.CASE_INSENSITIVE), + SHORT = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)s", Pattern.CASE_INSENSITIVE), + INT = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)"); - private final String str; - private int index; + private final String str; + private int index; - public static NBTCompound parse(String mson) throws MojangsonParseException { - return new MojangsonParser(mson).parseRootCompound(); - } + public static NBTCompound parse(String mson) throws MojangsonParseException { + return new MojangsonParser(mson).parseRootCompound(); + } - private MojangsonParser(String str) { - this.str = str; - } + private MojangsonParser(String str) { + this.str = str; + } - // PARSE + // PARSE - private NBTCompound parseRootCompound() throws MojangsonParseException { - skipWhitespace(); - NBTCompound result = parseCompound(); - expectNoTrail(); - return result; - } + private NBTCompound parseRootCompound() throws MojangsonParseException { + skipWhitespace(); + NBTCompound result = parseCompound(); + expectNoTrail(); + return result; + } - private String parseCompoundKey() throws MojangsonParseException { - skipWhitespace(); - if (!hasNext()) { - throw parseException("Expected key"); - } - return currentChar() == '"' ? parseQuotedString() : parseSimpleString(); - } + private String parseCompoundKey() throws MojangsonParseException { + skipWhitespace(); + if (!hasNext()) { + throw parseException("Expected key"); + } + return currentChar() == '"' ? parseQuotedString() : parseSimpleString(); + } - private NBTTag parseStringOrLiteral() throws MojangsonParseException { - skipWhitespace(); - if (currentChar() == '"') - return new NBTString(parseQuotedString()); - String str = parseSimpleString(); - if (str.isEmpty()) - throw parseException("Expected value"); - return parseLiteral(str); - } + private NBTTag parseStringOrLiteral() throws MojangsonParseException { + skipWhitespace(); + if (currentChar() == '"') + return new NBTString(parseQuotedString()); + String str = parseSimpleString(); + if (str.isEmpty()) + throw parseException("Expected value"); + return parseLiteral(str); + } - private NBTTag parseLiteral(String str) { - try { - if (FLOAT.matcher(str).matches()) { - return new NBTFloat(Float.parseFloat(str.substring(0, str.length() - 1))); - } - if (BYTE.matcher(str).matches()) { - return new NBTByte(Byte.parseByte(str.substring(0, str.length() - 1))); - } - if (LONG.matcher(str).matches()) { - return new NBTLong(Long.parseLong(str.substring(0, str.length() - 1))); - } - if (SHORT.matcher(str).matches()) { - return new NBTShort(Short.parseShort(str.substring(0, str.length() - 1))); - } - if (INT.matcher(str).matches()) { - return new NBTInt(Integer.parseInt(str)); - } - if (DOUBLE_S.matcher(str).matches()) { - return new NBTDouble(Double.parseDouble(str.substring(0, str.length() - 1))); - } - if (DOUBLE_NS.matcher(str).matches()) { - return new NBTDouble(Double.parseDouble(str)); - } - if ("true".equalsIgnoreCase(str)) { - return new NBTByte((byte) 1); - } - if ("false".equalsIgnoreCase(str)) { - return new NBTByte((byte) 0); - } - } catch (NumberFormatException ex) { - return new NBTString(str); - } - return new NBTString(str); - } + private NBTTag parseLiteral(String str) { + try { + if (FLOAT.matcher(str).matches()) { + return new NBTFloat(Float.parseFloat(str.substring(0, str.length() - 1))); + } + if (BYTE.matcher(str).matches()) { + return new NBTByte(Byte.parseByte(str.substring(0, str.length() - 1))); + } + if (LONG.matcher(str).matches()) { + return new NBTLong(Long.parseLong(str.substring(0, str.length() - 1))); + } + if (SHORT.matcher(str).matches()) { + return new NBTShort(Short.parseShort(str.substring(0, str.length() - 1))); + } + if (INT.matcher(str).matches()) { + return new NBTInt(Integer.parseInt(str)); + } + if (DOUBLE_S.matcher(str).matches()) { + return new NBTDouble(Double.parseDouble(str.substring(0, str.length() - 1))); + } + if (DOUBLE_NS.matcher(str).matches()) { + return new NBTDouble(Double.parseDouble(str)); + } + if ("true".equalsIgnoreCase(str)) { + return new NBTByte((byte) 1); + } + if ("false".equalsIgnoreCase(str)) { + return new NBTByte((byte) 0); + } + } catch (NumberFormatException ex) { + return new NBTString(str); + } + return new NBTString(str); + } - private String parseQuotedString() throws MojangsonParseException { - int j = ++this.index; - StringBuilder builder = null; - boolean escape = false; + private String parseQuotedString() throws MojangsonParseException { + int j = ++this.index; + StringBuilder builder = null; + boolean escape = false; - while (hasNext()) { - char c = nextChar(); - if (escape) { - if ((c != '\\') && (c != '"')) { - throw parseException("Invalid escape of '" + c + "'"); - } - escape = false; - } else { - if (c == '\\') { - escape = true; - if (builder != null) { - continue; - } - builder = new StringBuilder(this.str.substring(j, this.index - 1)); - continue; - } - if (c == '"') { - return builder == null ? this.str.substring(j, this.index - 1) : builder.toString(); - } - } - if (builder != null) { - builder.append(c); - } - } - throw parseException("Missing termination quote"); - } + while (hasNext()) { + char c = nextChar(); + if (escape) { + if ((c != '\\') && (c != '"')) { + throw parseException("Invalid escape of '" + c + "'"); + } + escape = false; + } else { + if (c == '\\') { + escape = true; + if (builder != null) { + continue; + } + builder = new StringBuilder(this.str.substring(j, this.index - 1)); + continue; + } + if (c == '"') { + return builder == null ? this.str.substring(j, this.index - 1) : builder.toString(); + } + } + if (builder != null) { + builder.append(c); + } + } + throw parseException("Missing termination quote"); + } - private String parseSimpleString() { - int j = this.index; - while (hasNext() && isSimpleChar(currentChar())) { - this.index += 1; - } - return this.str.substring(j, this.index); - } + private String parseSimpleString() { + int j = this.index; + while (hasNext() && isSimpleChar(currentChar())) { + this.index += 1; + } + return this.str.substring(j, this.index); + } - private NBTTag parseAnything() throws MojangsonParseException { - skipWhitespace(); - if (!hasNext()) - throw parseException("Expected value"); + private NBTTag parseAnything() throws MojangsonParseException { + skipWhitespace(); + if (!hasNext()) + throw parseException("Expected value"); - int c = currentChar(); - if (c == '{') - return parseCompound(); - else if (c == '[') - return parseDetectedArray(); - else - return parseStringOrLiteral(); - } + int c = currentChar(); + if (c == '{') + return parseCompound(); + else if (c == '[') + return parseDetectedArray(); + else + return parseStringOrLiteral(); + } - private NBTTag parseDetectedArray() throws MojangsonParseException { - if (hasCharsLeft(2) && getChar(1) != '"' && getChar(2) == ';') { - return parseNumArray(); - } - return parseList(); - } + private NBTTag parseDetectedArray() throws MojangsonParseException { + if (hasCharsLeft(2) && getChar(1) != '"' && getChar(2) == ';') { + return parseNumArray(); + } + return parseList(); + } - private NBTCompound parseCompound() throws MojangsonParseException { - expectChar('{'); + private NBTCompound parseCompound() throws MojangsonParseException { + expectChar('{'); - NBTCompound compound = new NBTCompound(); + NBTCompound compound = new NBTCompound(); - skipWhitespace(); - while ((hasNext()) && (currentChar() != '}')) { - String str = parseCompoundKey(); - if (str.isEmpty()) { - throw parseException("Expected non-empty key"); - } - expectChar(':'); + skipWhitespace(); + while ((hasNext()) && (currentChar() != '}')) { + String str = parseCompoundKey(); + if (str.isEmpty()) { + throw parseException("Expected non-empty key"); + } + expectChar(':'); - compound.put(str, parseAnything()); - if (!advanceToNextArrayElement()) { - break; - } - if (!hasNext()) { - throw parseException("Expected key"); - } - } - expectChar('}'); + compound.put(str, parseAnything()); + if (!advanceToNextArrayElement()) { + break; + } + if (!hasNext()) { + throw parseException("Expected key"); + } + } + expectChar('}'); - return compound; - } + return compound; + } - private NBTList parseList() throws MojangsonParseException { - expectChar('['); + private NBTList parseList() throws MojangsonParseException { + expectChar('['); - skipWhitespace(); - if (!hasNext()) { - throw parseException("Expected value"); - } - NBTList list = new NBTList(); - NBTType listType = null; + skipWhitespace(); + if (!hasNext()) { + throw parseException("Expected value"); + } + NBTList list = new NBTList(); + NBTType listType = null; - while (currentChar() != ']') { - NBTTag element = parseAnything(); - NBTType elementType = element.getType(); + while (currentChar() != ']') { + NBTTag element = parseAnything(); + NBTType elementType = element.getType(); - if (listType == null) { - listType = elementType; - } else if (elementType != listType) { - throw parseException("Unable to insert " + elementType + " into ListTag of type " + listType); - } - list.add(element); - if (!advanceToNextArrayElement()) { - break; - } - if (!hasNext()) { - throw parseException("Expected value"); - } - } - expectChar(']'); + if (listType == null) { + listType = elementType; + } else if (elementType != listType) { + throw parseException("Unable to insert " + elementType + " into ListTag of type " + listType); + } + list.add(element); + if (!advanceToNextArrayElement()) { + break; + } + if (!hasNext()) { + throw parseException("Expected value"); + } + } + expectChar(']'); - return list; - } + return list; + } - private NBTTag parseNumArray() throws MojangsonParseException { - expectChar('['); - char arrayType = nextChar(); - expectChar(';'); - //nextChar(); semicolon ignored by Mojang + private NBTTag parseNumArray() throws MojangsonParseException { + expectChar('['); + char arrayType = nextChar(); + expectChar(';'); + //nextChar(); semicolon ignored by Mojang - skipWhitespace(); - if (!hasNext()) { - throw parseException("Expected value"); - } - if (arrayType == 'B') - return new NBTByteArray(parseNumArray(NBTType.BYTE_ARRAY, NBTType.BYTE)); - else if (arrayType == 'L') - return new NBTLongArray(parseNumArray(NBTType.LONG_ARRAY, NBTType.LONG)); - else if (arrayType == 'I') - return new NBTIntArray(parseNumArray(NBTType.INT_ARRAY, NBTType.INT)); - throw parseException("Invalid array type '" + arrayType + "' found"); - } + skipWhitespace(); + if (!hasNext()) { + throw parseException("Expected value"); + } + if (arrayType == 'B') + return new NBTByteArray(parseNumArray(NBTType.BYTE_ARRAY, NBTType.BYTE)); + else if (arrayType == 'L') + return new NBTLongArray(parseNumArray(NBTType.LONG_ARRAY, NBTType.LONG)); + else if (arrayType == 'I') + return new NBTIntArray(parseNumArray(NBTType.INT_ARRAY, NBTType.INT)); + throw parseException("Invalid array type '" + arrayType + "' found"); + } - private Number[] parseNumArray(NBTType arrayType, NBTType primType) throws MojangsonParseException { - List result = new ArrayList<>(); - while (currentChar() != ']') { - NBTTag element = parseAnything(); - NBTType elementType = element.getType(); + private Number[] parseNumArray(NBTType arrayType, NBTType primType) throws MojangsonParseException { + List result = new ArrayList<>(); + while (currentChar() != ']') { + NBTTag element = parseAnything(); + NBTType elementType = element.getType(); - if (elementType != primType) { - throw parseException("Unable to insert " + elementType + " into " + arrayType); - } - if (primType == NBTType.BYTE) { - result.add(((NBTByte) element).getValue()); - } else if (primType == NBTType.LONG) { - result.add(((NBTLong) element).getValue()); - } else { - result.add(((NBTInt) element).getValue()); - } - if (!advanceToNextArrayElement()) { - break; - } - if (!hasNext()) { - throw parseException("Expected value"); - } - } - expectChar(']'); + if (elementType != primType) { + throw parseException("Unable to insert " + elementType + " into " + arrayType); + } + if (primType == NBTType.BYTE) { + result.add(((NBTByte) element).getValue()); + } else if (primType == NBTType.LONG) { + result.add(((NBTLong) element).getValue()); + } else { + result.add(((NBTInt) element).getValue()); + } + if (!advanceToNextArrayElement()) { + break; + } + if (!hasNext()) { + throw parseException("Expected value"); + } + } + expectChar(']'); - return result.toArray(new Number[0]); - } + return result.toArray(new Number[0]); + } - // CHARACTER NAVIGATION + // CHARACTER NAVIGATION - private boolean advanceToNextArrayElement() { - skipWhitespace(); - if (hasNext() && currentChar() == ',') { - this.index += 1; - skipWhitespace(); - return true; - } - return false; - } + private boolean advanceToNextArrayElement() { + skipWhitespace(); + if (hasNext() && currentChar() == ',') { + this.index += 1; + skipWhitespace(); + return true; + } + return false; + } - private void skipWhitespace() { - while (hasNext() && Character.isWhitespace(currentChar())) { - this.index += 1; - } - } + private void skipWhitespace() { + while (hasNext() && Character.isWhitespace(currentChar())) { + this.index += 1; + } + } - private boolean hasCharsLeft(int paramInt) { - return this.index + paramInt < this.str.length(); - } + private boolean hasCharsLeft(int paramInt) { + return this.index + paramInt < this.str.length(); + } - private boolean hasNext() { - return hasCharsLeft(0); - } + private boolean hasNext() { + return hasCharsLeft(0); + } - /** - * Returns the character in the string at the current index plus a given offset. - * - * @param offset the offset - * @return the character at the offset - */ - private char getChar(int offset) { - return this.str.charAt(this.index + offset); - } + /** + * Returns the character in the string at the current index plus a given offset. + * + * @param offset the offset + * @return the character at the offset + */ + private char getChar(int offset) { + return this.str.charAt(this.index + offset); + } - /** - * Returns the current character. - * - * @return the current character - */ - private char currentChar() { - return getChar(0); - } + /** + * Returns the current character. + * + * @return the current character + */ + private char currentChar() { + return getChar(0); + } - /** - * Returns the current character and increments the index. - * - * @return the current character - */ - private char nextChar() { - return this.str.charAt(this.index++); - } + /** + * Returns the current character and increments the index. + * + * @return the current character + */ + private char nextChar() { + return this.str.charAt(this.index++); + } - // UTIL + // UTIL - /** - * Verifies whether the current character is of given value and whether the parser can advance. If these conditions - * are met, the parser advances by one. If these conditions are not met, an exception is thrown. - * - * @param c the expected character - * @throws MojangsonParseException if {@link #currentChar()} does not equal {@code c} or if {@link #hasNext()} - * returns false - */ - private void expectChar(char c) throws MojangsonParseException { - skipWhitespace(); + /** + * Verifies whether the current character is of given value and whether the parser can advance. If these conditions + * are met, the parser advances by one. If these conditions are not met, an exception is thrown. + * + * @param c the expected character + * @throws MojangsonParseException if {@link #currentChar()} does not equal {@code c} or if {@link #hasNext()} + * returns false + */ + private void expectChar(char c) throws MojangsonParseException { + skipWhitespace(); - boolean hasNext = hasNext(); - if (hasNext && currentChar() == c) { - this.index += 1; - return; - } - throw new MojangsonParseException("Expected '" + c + "' but got '" + (hasNext ? Character.valueOf(currentChar()) : "") + "'", this.str, this.index + 1); - } + boolean hasNext = hasNext(); + if (hasNext && currentChar() == c) { + this.index += 1; + return; + } + throw new MojangsonParseException("Expected '" + c + "' but got '" + (hasNext ? Character.valueOf(currentChar()) : "") + "'", this.str, this.index + 1); + } - /** - * Verifies that the string has ended or that all characters from the next character on only consists of whitespace. - * - * @throws MojangsonParseException if the following characters contain a non-whitespace character - */ - private void expectNoTrail() throws MojangsonParseException { - skipWhitespace(); - if (hasNext()) { - this.index++; - throw parseException("Trailing data found"); - } - } + /** + * Verifies that the string has ended or that all characters from the next character on only consists of whitespace. + * + * @throws MojangsonParseException if the following characters contain a non-whitespace character + */ + private void expectNoTrail() throws MojangsonParseException { + skipWhitespace(); + if (hasNext()) { + this.index++; + throw parseException("Trailing data found"); + } + } - private MojangsonParseException parseException(String paramString) { - return new MojangsonParseException(paramString, this.str, this.index); - } + private MojangsonParseException parseException(String paramString) { + return new MojangsonParseException(paramString, this.str, this.index); + } - private static boolean isSimpleChar(char paramChar) { - return (paramChar >= '0' && paramChar <= '9') - || (paramChar >= 'A' && paramChar <= 'Z') - || (paramChar >= 'a' && paramChar <= 'z') - || paramChar == '_' - || paramChar == '-' - || paramChar == '.' - || paramChar == '+'; - } + private static boolean isSimpleChar(char paramChar) { + return (paramChar >= '0' && paramChar <= '9') + || (paramChar >= 'A' && paramChar <= 'Z') + || (paramChar >= 'a' && paramChar <= 'z') + || paramChar == '_' + || paramChar == '-' + || paramChar == '.' + || paramChar == '+'; + } } diff --git a/pom.xml b/pom.xml index 7de791d..aad2f46 100644 --- a/pom.xml +++ b/pom.xml @@ -1,226 +1,226 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - me.filoghost.chestcommands - chestcommands-parent - ChestCommands Parent - 4.0.0-SNAPSHOT - pom + me.filoghost.chestcommands + chestcommands-parent + ChestCommands Parent + 4.0.0-SNAPSHOT + pom - https://dev.bukkit.org/projects/chest-commands - - - GNU General Public License, Version 3 - https://www.gnu.org/licenses/gpl-3.0.txt - repo - - + https://dev.bukkit.org/projects/chest-commands + + + GNU General Public License, Version 3 + https://www.gnu.org/licenses/gpl-3.0.txt + repo + + - - https://github.com/filoghost/ChestCommands - scm:git:git://github.com:filoghost/ChestCommands.git - scm:git:git@github.com:filoghost/ChestCommands.git - - - - codemc-snapshots - https://repo.codemc.io/repository/maven-snapshots/ - - - codemc-releases - https://repo.codemc.io/repository/maven-releases/ - - + + https://github.com/filoghost/ChestCommands + scm:git:git://github.com:filoghost/ChestCommands.git + scm:git:git@github.com:filoghost/ChestCommands.git + + + + codemc-snapshots + https://repo.codemc.io/repository/maven-snapshots/ + + + codemc-releases + https://repo.codemc.io/repository/maven-releases/ + + - - UTF-8 - 1.8 - 1.8 - true - + + UTF-8 + 1.8 + 1.8 + true + - - api - plugin - + + api + plugin + - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + - - vault-repo - http://nexus.hc.to/content/repositories/pub_releases - + + vault-repo + http://nexus.hc.to/content/repositories/pub_releases + - - confuser-repo - https://ci.frostcast.net/plugin/repository/everything/ - + + confuser-repo + https://ci.frostcast.net/plugin/repository/everything/ + - - codemc-repo - https://repo.codemc.io/repository/maven-public/ - + + codemc-repo + https://repo.codemc.io/repository/maven-public/ + - - placeholderapi-repo - https://repo.extendedclip.com/content/repositories/placeholderapi/ - - + + placeholderapi-repo + https://repo.extendedclip.com/content/repositories/placeholderapi/ + + - - - - org.bukkit - bukkit - 1.8-R0.1-SNAPSHOT - provided - + + + + org.bukkit + bukkit + 1.8-R0.1-SNAPSHOT + provided + - - net.milkbowl.vault - VaultAPI - 1.6 - provided - + + net.milkbowl.vault + VaultAPI + 1.6 + provided + - - me.confuser - BarAPI - 3.5 - provided - + + me.confuser + BarAPI + 3.5 + provided + - - me.clip - placeholderapi - 2.9.2 - provided - + + me.clip + placeholderapi + 2.9.2 + provided + - - org.bstats - bstats-bukkit-lite - 1.7 - + + org.bstats + bstats-bukkit-lite + 1.7 + - - me.filoghost.updatechecker - updatechecker - 1.0.1 - + + me.filoghost.updatechecker + updatechecker + 1.0.1 + - - me.filoghost.fcommons - fcommons - 1.0.0 - + + me.filoghost.fcommons + fcommons + 1.0.0 + - - ${project.groupId} - chestcommands-api - ${project.version} - - - + + ${project.groupId} + chestcommands-api + ${project.version} + + + - - clean package + + clean package - - - - org.apache.maven.plugins - maven-jar-plugin - 3.2.0 - - - false - - false - - - - + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + + false + + false + + + + - - org.apache.maven.plugins - maven-shade-plugin - 3.2.3 - + + org.apache.maven.plugins + maven-shade-plugin + 3.2.3 + - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.1.1 - + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.1 + - - org.apache.maven.plugins - maven-enforcer-plugin - 3.0.0-M3 - + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M3 + - - org.codehaus.mojo - build-helper-maven-plugin - 3.2.0 - - - + + org.codehaus.mojo + build-helper-maven-plugin + 3.2.0 + + + - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle/checkstyle.xml - checkstyle/suppressions.xml - checkstyle/header.txt - - ${project.basedir} - - checkstyle/**/*, pom.xml, src/main/java/**/*.java - - - - checkstyle-check - validate - - check - - - - + + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle/checkstyle.xml + checkstyle/suppressions.xml + checkstyle/header.txt + + ${project.basedir} + + checkstyle/**/*, pom.xml, src/main/java/**/*.java + + + + checkstyle-check + validate + + check + + + + - - org.apache.maven.plugins - maven-enforcer-plugin - - - - enforce - - - - - - [3.6.0,) - - - [1.8,) - - - - - - - - + + org.apache.maven.plugins + maven-enforcer-plugin + + + + enforce + + + + + + [3.6.0,) + + + [1.8,) + + + + + + + +