From 042d9be11117c039f2538e8626d0f17becbb6561 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Tue, 24 May 2022 18:25:52 -0700 Subject: [PATCH 01/53] Re-org classes by usage --- pom.xml | 2 +- .../java/org/shanerx/tradeshop/TradeShop.java | 36 +++++----- .../tradeshop/commands/CommandCaller.java | 2 +- .../tradeshop/commands/CommandRunner.java | 38 +++++----- .../tradeshop/commands/CommandTabCaller.java | 2 +- .../commands/CommandTabCompleter.java | 6 +- .../shanerx/tradeshop/commands/Commands.java | 4 +- .../tradeshop/commands/EditCommand.java | 16 ++--- .../tradeshop/commands/WhatCommand.java | 14 ++-- .../{utils => data}/config/ConfigManager.java | 2 +- .../{utils => data}/config/Language.java | 4 +- .../{utils => data}/config/Message.java | 8 +-- .../config/MessageSection.java | 2 +- .../{utils => data}/config/Setting.java | 4 +- .../config/SettingSection.java | 2 +- .../{utils => data}/config/Variable.java | 2 +- .../data => data/storage}/DataStorage.java | 18 ++--- .../data => data/storage}/DataType.java | 2 +- .../storage}/Json/JsonConfiguration.java | 2 +- .../storage}/Json/LinkageConfiguration.java | 6 +- .../storage}/Json/PlayerConfiguration.java | 4 +- .../storage}/Json/ShopConfiguration.java | 10 +-- .../tradeshop/enumys/package-info.java | 6 -- .../events/HopperShopAccessEvent.java | 29 +++++++- .../framework/events/PlayerPreTradeEvent.java | 12 ++-- .../events/PlayerPrepareTradeEvent.java | 14 ++-- .../events/PlayerShopChangeEvent.java | 33 +++++++-- .../events/PlayerShopCloseEvent.java | 31 ++++++++- .../events/PlayerShopCreateEvent.java | 29 +++++++- .../events/PlayerShopDestroyEvent.java | 4 +- .../events/PlayerShopInventoryOpenEvent.java | 31 ++++++++- .../framework/events/PlayerShopOpenEvent.java | 31 ++++++++- .../events/PlayerSuccessfulTradeEvent.java | 2 +- .../events/TradeShopReloadEvent.java | 6 +- .../{objects => item}/IllegalItemList.java | 4 +- .../NonObtainableMaterials.java | 2 +- .../{objects => item}/ShopItemStack.java | 8 +-- .../ShopItemStackSettingKeys.java | 4 +- .../tradeshop/objects/WorldlessLocation.java | 19 ----- .../JoinEventListener.java | 10 ++- .../{enumys => player}/PermStatus.java | 2 +- .../{enumys => player}/Permissions.java | 2 +- .../{objects => player}/PlayerSetting.java | 7 +- .../{enumys => player}/ShopRole.java | 2 +- .../{objects => player}/ShopUser.java | 3 +- .../{enumys => shop}/ExchangeStatus.java | 2 +- .../tradeshop/{objects => shop}/Shop.java | 15 ++-- .../{objects => shop}/ShopChest.java | 10 +-- .../tradeshop/{enumys => shop}/ShopSign.java | 12 ++-- .../{enumys => shop}/ShopStatus.java | 4 +- .../{enumys => shop}/ShopStorage.java | 14 ++-- .../tradeshop/{enumys => shop}/ShopType.java | 8 ++- .../listeners/ShopCreateListener.java | 20 +++--- .../listeners/ShopProtectionListener.java | 18 ++--- .../listeners/ShopRestockListener.java | 6 +- .../listeners/ShopTradeListener.java | 20 +++--- .../IllegalWorldException.java | 4 +- .../{objects => shoplocation}/ShopChunk.java | 2 +- .../ShopLocation.java | 3 +- .../WorldlessLocation.java} | 32 ++++++--- .../{objects => utils}/ListManager.java | 12 ++-- .../tradeshop/utils/MetricsManager.java | 4 +- .../org/shanerx/tradeshop/utils/Tuple.java | 67 ------------------ .../org/shanerx/tradeshop/utils/Utils.java | 23 ++++--- .../{objects => utils/debug}/Debug.java | 5 +- .../{enumys => utils/debug}/DebugLevels.java | 2 +- .../utils/{ => objects}/ObjectHolder.java | 2 +- .../tradeshop/utils/objects/Tuple.java | 69 +++++++++++++++++++ .../BukkitVersion.java | 2 +- .../{ => versionmanagement}/Expirer.java | 6 +- .../{ => versionmanagement}/Updater.java | 2 +- 71 files changed, 492 insertions(+), 349 deletions(-) rename src/main/java/org/shanerx/tradeshop/{utils => data}/config/ConfigManager.java (99%) rename src/main/java/org/shanerx/tradeshop/{utils => data}/config/Language.java (98%) rename src/main/java/org/shanerx/tradeshop/{utils => data}/config/Message.java (98%) rename src/main/java/org/shanerx/tradeshop/{utils => data}/config/MessageSection.java (99%) rename src/main/java/org/shanerx/tradeshop/{utils => data}/config/Setting.java (99%) rename src/main/java/org/shanerx/tradeshop/{utils => data}/config/SettingSection.java (99%) rename src/main/java/org/shanerx/tradeshop/{utils => data}/config/Variable.java (97%) rename src/main/java/org/shanerx/tradeshop/{utils/data => data/storage}/DataStorage.java (92%) rename src/main/java/org/shanerx/tradeshop/{utils/data => data/storage}/DataType.java (96%) rename src/main/java/org/shanerx/tradeshop/{utils/data => data/storage}/Json/JsonConfiguration.java (98%) rename src/main/java/org/shanerx/tradeshop/{utils/data => data/storage}/Json/LinkageConfiguration.java (95%) rename src/main/java/org/shanerx/tradeshop/{utils/data => data/storage}/Json/PlayerConfiguration.java (95%) rename src/main/java/org/shanerx/tradeshop/{utils/data => data/storage}/Json/ShopConfiguration.java (96%) delete mode 100644 src/main/java/org/shanerx/tradeshop/enumys/package-info.java rename src/main/java/org/shanerx/tradeshop/{objects => item}/IllegalItemList.java (98%) rename src/main/java/org/shanerx/tradeshop/{enumys => item}/NonObtainableMaterials.java (98%) rename src/main/java/org/shanerx/tradeshop/{objects => item}/ShopItemStack.java (99%) rename src/main/java/org/shanerx/tradeshop/{enumys => item}/ShopItemStackSettingKeys.java (96%) delete mode 100644 src/main/java/org/shanerx/tradeshop/objects/WorldlessLocation.java rename src/main/java/org/shanerx/tradeshop/{listeners => player}/JoinEventListener.java (88%) rename src/main/java/org/shanerx/tradeshop/{enumys => player}/PermStatus.java (96%) rename src/main/java/org/shanerx/tradeshop/{enumys => player}/Permissions.java (98%) rename src/main/java/org/shanerx/tradeshop/{objects => player}/PlayerSetting.java (98%) rename src/main/java/org/shanerx/tradeshop/{enumys => player}/ShopRole.java (97%) rename src/main/java/org/shanerx/tradeshop/{objects => player}/ShopUser.java (97%) rename src/main/java/org/shanerx/tradeshop/{enumys => shop}/ExchangeStatus.java (97%) rename src/main/java/org/shanerx/tradeshop/{objects => shop}/Shop.java (98%) rename src/main/java/org/shanerx/tradeshop/{objects => shop}/ShopChest.java (96%) rename src/main/java/org/shanerx/tradeshop/{enumys => shop}/ShopSign.java (90%) rename src/main/java/org/shanerx/tradeshop/{enumys => shop}/ShopStatus.java (96%) rename src/main/java/org/shanerx/tradeshop/{enumys => shop}/ShopStorage.java (92%) rename src/main/java/org/shanerx/tradeshop/{enumys => shop}/ShopType.java (91%) rename src/main/java/org/shanerx/tradeshop/{ => shop}/listeners/ShopCreateListener.java (91%) rename src/main/java/org/shanerx/tradeshop/{ => shop}/listeners/ShopProtectionListener.java (96%) rename src/main/java/org/shanerx/tradeshop/{ => shop}/listeners/ShopRestockListener.java (93%) rename src/main/java/org/shanerx/tradeshop/{ => shop}/listeners/ShopTradeListener.java (96%) rename src/main/java/org/shanerx/tradeshop/{exceptions => shoplocation}/IllegalWorldException.java (93%) rename src/main/java/org/shanerx/tradeshop/{objects => shoplocation}/ShopChunk.java (98%) rename src/main/java/org/shanerx/tradeshop/{objects => shoplocation}/ShopLocation.java (96%) rename src/main/java/org/shanerx/tradeshop/{objects/package-info.java => shoplocation/WorldlessLocation.java} (67%) rename src/main/java/org/shanerx/tradeshop/{objects => utils}/ListManager.java (96%) delete mode 100644 src/main/java/org/shanerx/tradeshop/utils/Tuple.java rename src/main/java/org/shanerx/tradeshop/{objects => utils/debug}/Debug.java (95%) rename src/main/java/org/shanerx/tradeshop/{enumys => utils/debug}/DebugLevels.java (98%) rename src/main/java/org/shanerx/tradeshop/utils/{ => objects}/ObjectHolder.java (96%) create mode 100644 src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java rename src/main/java/org/shanerx/tradeshop/utils/{ => versionmanagement}/BukkitVersion.java (98%) rename src/main/java/org/shanerx/tradeshop/utils/{ => versionmanagement}/Expirer.java (97%) rename src/main/java/org/shanerx/tradeshop/utils/{ => versionmanagement}/Updater.java (99%) diff --git a/pom.xml b/pom.xml index 30b97525..6a6930e6 100644 --- a/pom.xml +++ b/pom.xml @@ -63,7 +63,7 @@ org.shanerx tradeshop - 2.5.1-STABLE + 2.6.0-DEV jar TradeShop https://tradeshop.github.io/ diff --git a/src/main/java/org/shanerx/tradeshop/TradeShop.java b/src/main/java/org/shanerx/tradeshop/TradeShop.java index ded24daf..2d691ccf 100644 --- a/src/main/java/org/shanerx/tradeshop/TradeShop.java +++ b/src/main/java/org/shanerx/tradeshop/TradeShop.java @@ -30,25 +30,25 @@ import org.bukkit.plugin.java.JavaPlugin; import org.shanerx.tradeshop.commands.CommandCaller; import org.shanerx.tradeshop.commands.CommandTabCaller; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.enumys.ShopSign; -import org.shanerx.tradeshop.enumys.ShopStorage; -import org.shanerx.tradeshop.listeners.JoinEventListener; -import org.shanerx.tradeshop.listeners.ShopCreateListener; -import org.shanerx.tradeshop.listeners.ShopProtectionListener; -import org.shanerx.tradeshop.listeners.ShopRestockListener; -import org.shanerx.tradeshop.listeners.ShopTradeListener; -import org.shanerx.tradeshop.objects.Debug; -import org.shanerx.tradeshop.objects.ListManager; -import org.shanerx.tradeshop.utils.BukkitVersion; -import org.shanerx.tradeshop.utils.Expirer; +import org.shanerx.tradeshop.data.config.ConfigManager; +import org.shanerx.tradeshop.data.config.Language; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.storage.DataStorage; +import org.shanerx.tradeshop.data.storage.DataType; +import org.shanerx.tradeshop.player.JoinEventListener; +import org.shanerx.tradeshop.shop.ShopSign; +import org.shanerx.tradeshop.shop.ShopStorage; +import org.shanerx.tradeshop.shop.listeners.ShopCreateListener; +import org.shanerx.tradeshop.shop.listeners.ShopProtectionListener; +import org.shanerx.tradeshop.shop.listeners.ShopRestockListener; +import org.shanerx.tradeshop.shop.listeners.ShopTradeListener; +import org.shanerx.tradeshop.utils.ListManager; import org.shanerx.tradeshop.utils.MetricsManager; -import org.shanerx.tradeshop.utils.Updater; -import org.shanerx.tradeshop.utils.config.ConfigManager; -import org.shanerx.tradeshop.utils.config.Language; -import org.shanerx.tradeshop.utils.config.Setting; -import org.shanerx.tradeshop.utils.data.DataStorage; -import org.shanerx.tradeshop.utils.data.DataType; +import org.shanerx.tradeshop.utils.debug.Debug; +import org.shanerx.tradeshop.utils.debug.DebugLevels; +import org.shanerx.tradeshop.utils.versionmanagement.BukkitVersion; +import org.shanerx.tradeshop.utils.versionmanagement.Expirer; +import org.shanerx.tradeshop.utils.versionmanagement.Updater; public class TradeShop extends JavaPlugin { diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java index 7f8e3464..3b6f562f 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java @@ -29,7 +29,7 @@ import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.utils.config.Message; +import org.shanerx.tradeshop.data.config.Message; /** * This class is used for calling command methods from CommandRunner diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java index 53516a36..032f754c 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java @@ -36,32 +36,32 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.enumys.PermStatus; -import org.shanerx.tradeshop.enumys.Permissions; -import org.shanerx.tradeshop.enumys.ShopRole; -import org.shanerx.tradeshop.enumys.ShopStatus; -import org.shanerx.tradeshop.enumys.ShopType; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.config.Variable; +import org.shanerx.tradeshop.data.storage.DataType; import org.shanerx.tradeshop.framework.ShopChange; import org.shanerx.tradeshop.framework.events.PlayerShopChangeEvent; import org.shanerx.tradeshop.framework.events.PlayerShopCloseEvent; import org.shanerx.tradeshop.framework.events.PlayerShopCreateEvent; import org.shanerx.tradeshop.framework.events.PlayerShopOpenEvent; import org.shanerx.tradeshop.framework.events.TradeShopReloadEvent; -import org.shanerx.tradeshop.objects.IllegalItemList; -import org.shanerx.tradeshop.objects.PlayerSetting; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopChest; -import org.shanerx.tradeshop.objects.ShopItemStack; -import org.shanerx.tradeshop.objects.ShopLocation; -import org.shanerx.tradeshop.objects.ShopUser; -import org.shanerx.tradeshop.utils.ObjectHolder; -import org.shanerx.tradeshop.utils.Tuple; +import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.player.PermStatus; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.PlayerSetting; +import org.shanerx.tradeshop.player.ShopRole; +import org.shanerx.tradeshop.player.ShopUser; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopChest; +import org.shanerx.tradeshop.shop.ShopStatus; +import org.shanerx.tradeshop.shop.ShopType; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Message; -import org.shanerx.tradeshop.utils.config.Setting; -import org.shanerx.tradeshop.utils.config.Variable; -import org.shanerx.tradeshop.utils.data.DataType; +import org.shanerx.tradeshop.utils.debug.DebugLevels; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; +import org.shanerx.tradeshop.utils.objects.Tuple; public class CommandRunner extends Utils { diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java index a788afa9..202ebbca 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java @@ -29,7 +29,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.utils.config.Message; +import org.shanerx.tradeshop.data.config.Message; import java.util.ArrayList; import java.util.Collections; diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCompleter.java b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCompleter.java index 51baaa01..88cbaee8 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCompleter.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCompleter.java @@ -29,10 +29,10 @@ import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.ShopType; -import org.shanerx.tradeshop.objects.Shop; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopType; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Setting; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/shanerx/tradeshop/commands/Commands.java b/src/main/java/org/shanerx/tradeshop/commands/Commands.java index 718aab30..1d8b540b 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/Commands.java +++ b/src/main/java/org/shanerx/tradeshop/commands/Commands.java @@ -28,8 +28,8 @@ import com.google.common.collect.Lists; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.shanerx.tradeshop.enumys.PermStatus; -import org.shanerx.tradeshop.enumys.Permissions; +import org.shanerx.tradeshop.player.PermStatus; +import org.shanerx.tradeshop.player.Permissions; import java.util.List; diff --git a/src/main/java/org/shanerx/tradeshop/commands/EditCommand.java b/src/main/java/org/shanerx/tradeshop/commands/EditCommand.java index 69b33035..cb6d32f9 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/EditCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/EditCommand.java @@ -37,14 +37,14 @@ import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.inventory.meta.ItemMeta; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.Permissions; -import org.shanerx.tradeshop.enumys.ShopItemStackSettingKeys; -import org.shanerx.tradeshop.enumys.ShopRole; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopItemStack; -import org.shanerx.tradeshop.objects.ShopUser; -import org.shanerx.tradeshop.utils.ObjectHolder; -import org.shanerx.tradeshop.utils.config.Message; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.ShopRole; +import org.shanerx.tradeshop.player.ShopUser; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; import java.util.ArrayList; import java.util.HashSet; diff --git a/src/main/java/org/shanerx/tradeshop/commands/WhatCommand.java b/src/main/java/org/shanerx/tradeshop/commands/WhatCommand.java index 6710e681..6cc2ec99 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/WhatCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/WhatCommand.java @@ -35,13 +35,13 @@ import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.Permissions; -import org.shanerx.tradeshop.enumys.ShopItemStackSettingKeys; -import org.shanerx.tradeshop.enumys.ShopType; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopItemStack; -import org.shanerx.tradeshop.utils.config.Message; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopType; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/shanerx/tradeshop/utils/config/ConfigManager.java b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java similarity index 99% rename from src/main/java/org/shanerx/tradeshop/utils/config/ConfigManager.java rename to src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java index fa086e71..0c7e7294 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/config/ConfigManager.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils.config; +package org.shanerx.tradeshop.data.config; import com.google.common.base.CaseFormat; import com.google.common.base.Charsets; diff --git a/src/main/java/org/shanerx/tradeshop/utils/config/Language.java b/src/main/java/org/shanerx/tradeshop/data/config/Language.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/utils/config/Language.java rename to src/main/java/org/shanerx/tradeshop/data/config/Language.java index aeb0d9d3..9b37db76 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/config/Language.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Language.java @@ -23,11 +23,11 @@ * */ -package org.shanerx.tradeshop.utils.config; +package org.shanerx.tradeshop.data.config; import org.bukkit.configuration.file.YamlConfiguration; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.DebugLevels; +import org.shanerx.tradeshop.utils.debug.DebugLevels; import java.io.File; import java.io.InputStream; diff --git a/src/main/java/org/shanerx/tradeshop/utils/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/utils/config/Message.java rename to src/main/java/org/shanerx/tradeshop/data/config/Message.java index aaba7126..2a6caedb 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -23,17 +23,17 @@ * */ -package org.shanerx.tradeshop.utils.config; +package org.shanerx.tradeshop.data.config; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.objects.Debug; -import org.shanerx.tradeshop.objects.ShopItemStack; -import org.shanerx.tradeshop.utils.Tuple; +import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.debug.Debug; +import org.shanerx.tradeshop.utils.objects.Tuple; import org.yaml.snakeyaml.Yaml; import java.util.Arrays; diff --git a/src/main/java/org/shanerx/tradeshop/utils/config/MessageSection.java b/src/main/java/org/shanerx/tradeshop/data/config/MessageSection.java similarity index 99% rename from src/main/java/org/shanerx/tradeshop/utils/config/MessageSection.java rename to src/main/java/org/shanerx/tradeshop/data/config/MessageSection.java index 501f128b..922017f8 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/config/MessageSection.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/MessageSection.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils.config; +package org.shanerx.tradeshop.data.config; import org.bukkit.Bukkit; import org.shanerx.tradeshop.TradeShop; diff --git a/src/main/java/org/shanerx/tradeshop/utils/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java similarity index 99% rename from src/main/java/org/shanerx/tradeshop/utils/config/Setting.java rename to src/main/java/org/shanerx/tradeshop/data/config/Setting.java index fb9613f7..2557e63a 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -23,11 +23,11 @@ * */ -package org.shanerx.tradeshop.utils.config; +package org.shanerx.tradeshop.data.config; import org.bukkit.Bukkit; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.objects.IllegalItemList; +import org.shanerx.tradeshop.item.IllegalItemList; import org.yaml.snakeyaml.Yaml; import java.util.Arrays; diff --git a/src/main/java/org/shanerx/tradeshop/utils/config/SettingSection.java b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java similarity index 99% rename from src/main/java/org/shanerx/tradeshop/utils/config/SettingSection.java rename to src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java index f8fb6788..84c0a62f 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/config/SettingSection.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils.config; +package org.shanerx.tradeshop.data.config; import org.bukkit.Bukkit; import org.shanerx.tradeshop.TradeShop; diff --git a/src/main/java/org/shanerx/tradeshop/utils/config/Variable.java b/src/main/java/org/shanerx/tradeshop/data/config/Variable.java similarity index 97% rename from src/main/java/org/shanerx/tradeshop/utils/config/Variable.java rename to src/main/java/org/shanerx/tradeshop/data/config/Variable.java index 0c32a0ce..6566f3bd 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/config/Variable.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Variable.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils.config; +package org.shanerx.tradeshop.data.config; public enum Variable { diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java similarity index 92% rename from src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java rename to src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java index 2bcc19a2..ce55ac6a 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java @@ -23,19 +23,19 @@ * */ -package org.shanerx.tradeshop.utils.data; +package org.shanerx.tradeshop.data.storage; import org.bukkit.Chunk; import org.bukkit.World; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.objects.PlayerSetting; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopChunk; -import org.shanerx.tradeshop.objects.ShopLocation; +import org.shanerx.tradeshop.data.storage.Json.LinkageConfiguration; +import org.shanerx.tradeshop.data.storage.Json.PlayerConfiguration; +import org.shanerx.tradeshop.data.storage.Json.ShopConfiguration; +import org.shanerx.tradeshop.player.PlayerSetting; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shoplocation.ShopChunk; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.data.Json.LinkageConfiguration; -import org.shanerx.tradeshop.utils.data.Json.PlayerConfiguration; -import org.shanerx.tradeshop.utils.data.Json.ShopConfiguration; +import org.shanerx.tradeshop.utils.debug.DebugLevels; import java.io.File; import java.util.UUID; diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/DataType.java b/src/main/java/org/shanerx/tradeshop/data/storage/DataType.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/utils/data/DataType.java rename to src/main/java/org/shanerx/tradeshop/data/storage/DataType.java index b814175f..b200e99e 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/DataType.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/DataType.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils.data; +package org.shanerx.tradeshop.data.storage; public enum DataType { FLATFILE, diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/Json/JsonConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonConfiguration.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/utils/data/Json/JsonConfiguration.java rename to src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonConfiguration.java index 4c3a5ac1..3080720e 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/Json/JsonConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonConfiguration.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils.data.Json; +package org.shanerx.tradeshop.data.storage.Json; import com.google.gson.Gson; import com.google.gson.GsonBuilder; diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/Json/LinkageConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/LinkageConfiguration.java similarity index 95% rename from src/main/java/org/shanerx/tradeshop/utils/data/Json/LinkageConfiguration.java rename to src/main/java/org/shanerx/tradeshop/data/storage/Json/LinkageConfiguration.java index 02141872..ce465e11 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/Json/LinkageConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/LinkageConfiguration.java @@ -23,12 +23,12 @@ * */ -package org.shanerx.tradeshop.utils.data.Json; +package org.shanerx.tradeshop.data.storage.Json; import com.google.gson.reflect.TypeToken; import org.bukkit.World; -import org.shanerx.tradeshop.objects.ShopChest; -import org.shanerx.tradeshop.objects.ShopLocation; +import org.shanerx.tradeshop.shop.ShopChest; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/Json/PlayerConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/PlayerConfiguration.java similarity index 95% rename from src/main/java/org/shanerx/tradeshop/utils/data/Json/PlayerConfiguration.java rename to src/main/java/org/shanerx/tradeshop/data/storage/Json/PlayerConfiguration.java index c06440e1..b67f9987 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/Json/PlayerConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/PlayerConfiguration.java @@ -23,10 +23,10 @@ * */ -package org.shanerx.tradeshop.utils.data.Json; +package org.shanerx.tradeshop.data.storage.Json; import com.google.gson.reflect.TypeToken; -import org.shanerx.tradeshop.objects.PlayerSetting; +import org.shanerx.tradeshop.player.PlayerSetting; import java.util.Map; import java.util.UUID; diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/Json/ShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/utils/data/Json/ShopConfiguration.java rename to src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java index c10e24c0..57160746 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/Json/ShopConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java @@ -23,16 +23,16 @@ * */ -package org.shanerx.tradeshop.utils.data.Json; +package org.shanerx.tradeshop.data.storage.Json; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gson.JsonElement; import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopChunk; -import org.shanerx.tradeshop.objects.ShopItemStack; -import org.shanerx.tradeshop.objects.ShopLocation; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shoplocation.ShopChunk; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import java.io.File; import java.util.ArrayList; diff --git a/src/main/java/org/shanerx/tradeshop/enumys/package-info.java b/src/main/java/org/shanerx/tradeshop/enumys/package-info.java deleted file mode 100644 index 5d2c2bc5..00000000 --- a/src/main/java/org/shanerx/tradeshop/enumys/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * This package contains all the enum types the plugin's internal API makes use of. - * We are including them into the javadocs so that you can have a full picture of the - * plugin's API, since the TSAF makes use of it. - */ -package org.shanerx.tradeshop.enumys; \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/HopperShopAccessEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/HopperShopAccessEvent.java index 1c59ddf0..713e67df 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/HopperShopAccessEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/HopperShopAccessEvent.java @@ -1,10 +1,35 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + package org.shanerx.tradeshop.framework.events; import org.bukkit.event.HandlerList; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.objects.Shop; +import org.shanerx.tradeshop.shop.Shop; /** * This event is is fired when a hopper attempts to modify the contents of a shop's inventory. @@ -22,7 +47,7 @@ public enum HopperDirection { private static final HandlerList handlers = new HandlerList(); private Shop shop; private boolean isForbidden; - private HopperDirection dir; + private final HopperDirection dir; /** * Constructor for the object. diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerPreTradeEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerPreTradeEvent.java index 45d3021b..b8ad8774 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerPreTradeEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerPreTradeEvent.java @@ -32,8 +32,8 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopItemStack; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.shop.Shop; import java.util.List; @@ -45,10 +45,10 @@ public class PlayerPreTradeEvent extends PlayerInteractEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); - private Shop shop; - private List product; - private List cost; - private Block clickedBlock; + private final Shop shop; + private final List product; + private final List cost; + private final Block clickedBlock; private boolean cancelled; /** diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerPrepareTradeEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerPrepareTradeEvent.java index aad8d84e..741ea6db 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerPrepareTradeEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerPrepareTradeEvent.java @@ -32,8 +32,8 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopItemStack; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.shop.Shop; import java.util.List; @@ -45,12 +45,12 @@ public class PlayerPrepareTradeEvent extends PlayerInteractEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); - private Shop shop; - private List product; - private List cost; - private Block clickedBlock; + private final Shop shop; + private final List product; + private final List cost; + private final Block clickedBlock; private boolean cancelled; - + /** * Constructor for the object. * @param who The {@link org.bukkit.entity.Player} object representing the player who is attempting the trade. diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java index c12cfd1d..1b5ce695 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java @@ -1,3 +1,28 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + package org.shanerx.tradeshop.framework.events; import org.bukkit.entity.Player; @@ -5,17 +30,17 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.shanerx.tradeshop.framework.ShopChange; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.utils.ObjectHolder; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; /** * This class represents a {@link org.bukkit.event.Cancellable} event, which gets fired when someone is about to * modify shop information such as product, cost, managers and members. */ public class PlayerShopChangeEvent extends PlayerEvent implements Cancellable { - + private static final HandlerList handlers = new HandlerList(); - private Shop shop; + private final Shop shop; private ObjectHolder what; private boolean cancelled; diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCloseEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCloseEvent.java index a44a0887..e9b8145d 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCloseEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCloseEvent.java @@ -1,19 +1,44 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + package org.shanerx.tradeshop.framework.events; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -import org.shanerx.tradeshop.objects.Shop; +import org.shanerx.tradeshop.shop.Shop; /** * This class represents the event which is fired when the owner of a shop closes the shop. * Since it implements {@link org.bukkit.event.Cancellable}, it is possible to cancel the event. */ public class PlayerShopCloseEvent extends PlayerEvent implements Cancellable { - + private static final HandlerList handlers = new HandlerList(); - private Shop shop; + private final Shop shop; private boolean cancelled; /** diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCreateEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCreateEvent.java index b089e487..218f1199 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCreateEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCreateEvent.java @@ -1,10 +1,35 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + package org.shanerx.tradeshop.framework.events; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -import org.shanerx.tradeshop.objects.Shop; +import org.shanerx.tradeshop.shop.Shop; /** * This class represents the event being fired upon shop creation. It implements {@link org.bukkit.event.Cancellable}, @@ -14,7 +39,7 @@ public class PlayerShopCreateEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled; - private Shop shop; + private final Shop shop; /** * Constructor for the object. diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopDestroyEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopDestroyEvent.java index 7f17245d..0074fb5d 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopDestroyEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopDestroyEvent.java @@ -29,7 +29,7 @@ import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -import org.shanerx.tradeshop.objects.Shop; +import org.shanerx.tradeshop.shop.Shop; /** * This class represents the event being fired upon shop creation. It implements {@link org.bukkit.event.Cancellable}, @@ -39,7 +39,7 @@ public class PlayerShopDestroyEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled, destroyBlock; - private Shop shop; + private final Shop shop; /** * Constructor for the object. diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopInventoryOpenEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopInventoryOpenEvent.java index d0dc9122..edc90f9d 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopInventoryOpenEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopInventoryOpenEvent.java @@ -1,3 +1,28 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + package org.shanerx.tradeshop.framework.events; import org.bukkit.block.Block; @@ -8,16 +33,16 @@ import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.objects.Shop; +import org.shanerx.tradeshop.shop.Shop; /** * This class represents the event being fired when someone who has the required permissions attempts to open a shop. * It implements {@link org.bukkit.event.Cancellable}, which makes it possible to cancel the event. */ public class PlayerShopInventoryOpenEvent extends PlayerInteractEvent implements Cancellable { - + private static final HandlerList handlers = new HandlerList(); - private Shop shop; + private final Shop shop; private boolean cancelled; /** diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopOpenEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopOpenEvent.java index 22b4d228..19fa9a5e 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopOpenEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopOpenEvent.java @@ -1,19 +1,44 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + package org.shanerx.tradeshop.framework.events; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -import org.shanerx.tradeshop.objects.Shop; +import org.shanerx.tradeshop.shop.Shop; /** * This class represents the event which is fired when the owner of a shop opens the shop. * Since it implements {@link org.bukkit.event.Cancellable}, it is possible to cancel the event. */ public class PlayerShopOpenEvent extends PlayerEvent implements Cancellable { - + private static final HandlerList handlers = new HandlerList(); - private Shop shop; + private final Shop shop; private boolean cancelled; /** diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerSuccessfulTradeEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerSuccessfulTradeEvent.java index 19a0051a..7d488155 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerSuccessfulTradeEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerSuccessfulTradeEvent.java @@ -32,7 +32,7 @@ import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.objects.Shop; +import org.shanerx.tradeshop.shop.Shop; import java.util.List; diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/TradeShopReloadEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/TradeShopReloadEvent.java index db8d3f2c..9d2ea57c 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/TradeShopReloadEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/TradeShopReloadEvent.java @@ -30,9 +30,9 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.server.ServerEvent; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.objects.Debug; -import org.shanerx.tradeshop.objects.ListManager; -import org.shanerx.tradeshop.utils.data.DataStorage; +import org.shanerx.tradeshop.data.storage.DataStorage; +import org.shanerx.tradeshop.utils.ListManager; +import org.shanerx.tradeshop.utils.debug.Debug; // TODO javadocs for TradeShopReloadEvent public class TradeShopReloadEvent extends ServerEvent { diff --git a/src/main/java/org/shanerx/tradeshop/objects/IllegalItemList.java b/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/objects/IllegalItemList.java rename to src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java index 3f4e1f99..55bc1a37 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/IllegalItemList.java +++ b/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java @@ -23,11 +23,11 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.item; import org.bukkit.Material; -import org.shanerx.tradeshop.enumys.DebugLevels; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.debug.DebugLevels; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/shanerx/tradeshop/enumys/NonObtainableMaterials.java b/src/main/java/org/shanerx/tradeshop/item/NonObtainableMaterials.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/enumys/NonObtainableMaterials.java rename to src/main/java/org/shanerx/tradeshop/item/NonObtainableMaterials.java index d6dc7610..da6583f8 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/NonObtainableMaterials.java +++ b/src/main/java/org/shanerx/tradeshop/item/NonObtainableMaterials.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.item; public enum NonObtainableMaterials { CARROTS, diff --git a/src/main/java/org/shanerx/tradeshop/objects/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java similarity index 99% rename from src/main/java/org/shanerx/tradeshop/objects/ShopItemStack.java rename to src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index e77fb81a..7db0e2a1 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.item; import com.google.common.collect.Lists; import com.google.gson.Gson; @@ -43,10 +43,10 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.enumys.ShopItemStackSettingKeys; -import org.shanerx.tradeshop.utils.ObjectHolder; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.debug.Debug; +import org.shanerx.tradeshop.utils.debug.DebugLevels; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import java.io.ByteArrayInputStream; diff --git a/src/main/java/org/shanerx/tradeshop/enumys/ShopItemStackSettingKeys.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/enumys/ShopItemStackSettingKeys.java rename to src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java index 630eeab8..09d0c312 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/ShopItemStackSettingKeys.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java @@ -23,9 +23,9 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.item; -import org.shanerx.tradeshop.utils.ObjectHolder; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; public enum ShopItemStackSettingKeys { diff --git a/src/main/java/org/shanerx/tradeshop/objects/WorldlessLocation.java b/src/main/java/org/shanerx/tradeshop/objects/WorldlessLocation.java deleted file mode 100644 index 53e5a86b..00000000 --- a/src/main/java/org/shanerx/tradeshop/objects/WorldlessLocation.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.shanerx.tradeshop.objects; - -import org.bukkit.Location; -import org.bukkit.World; - -public class WorldlessLocation { - - private double x, y, z; - - public WorldlessLocation(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - public Location getLocation(World w) { - return new Location(w, x, y, z); - } -} diff --git a/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java b/src/main/java/org/shanerx/tradeshop/player/JoinEventListener.java similarity index 88% rename from src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java rename to src/main/java/org/shanerx/tradeshop/player/JoinEventListener.java index bb84d9a2..67d765e5 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java +++ b/src/main/java/org/shanerx/tradeshop/player/JoinEventListener.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.listeners; +package org.shanerx.tradeshop.player; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -31,12 +31,10 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.Permissions; -import org.shanerx.tradeshop.objects.PlayerSetting; -import org.shanerx.tradeshop.utils.BukkitVersion; -import org.shanerx.tradeshop.utils.Updater; +import org.shanerx.tradeshop.data.config.Message; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Message; +import org.shanerx.tradeshop.utils.versionmanagement.BukkitVersion; +import org.shanerx.tradeshop.utils.versionmanagement.Updater; public class JoinEventListener extends Utils implements Listener { diff --git a/src/main/java/org/shanerx/tradeshop/enumys/PermStatus.java b/src/main/java/org/shanerx/tradeshop/player/PermStatus.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/enumys/PermStatus.java rename to src/main/java/org/shanerx/tradeshop/player/PermStatus.java index af4aff7d..cdf7c644 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/PermStatus.java +++ b/src/main/java/org/shanerx/tradeshop/player/PermStatus.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.player; public enum PermStatus { GOOD, diff --git a/src/main/java/org/shanerx/tradeshop/enumys/Permissions.java b/src/main/java/org/shanerx/tradeshop/player/Permissions.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/enumys/Permissions.java rename to src/main/java/org/shanerx/tradeshop/player/Permissions.java index 3502cf54..62b87417 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/Permissions.java +++ b/src/main/java/org/shanerx/tradeshop/player/Permissions.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.player; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java rename to src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java index f9c622bc..1cf5f09d 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java +++ b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.player; import com.google.common.collect.Sets; import com.google.gson.Gson; @@ -34,9 +34,10 @@ import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.enumys.ShopRole; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Setting; import java.io.Serializable; import java.util.HashSet; diff --git a/src/main/java/org/shanerx/tradeshop/enumys/ShopRole.java b/src/main/java/org/shanerx/tradeshop/player/ShopRole.java similarity index 97% rename from src/main/java/org/shanerx/tradeshop/enumys/ShopRole.java rename to src/main/java/org/shanerx/tradeshop/player/ShopRole.java index 7cd9c25b..ca8c96d6 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/ShopRole.java +++ b/src/main/java/org/shanerx/tradeshop/player/ShopRole.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.player; @SuppressWarnings("unused") public enum ShopRole { diff --git a/src/main/java/org/shanerx/tradeshop/objects/ShopUser.java b/src/main/java/org/shanerx/tradeshop/player/ShopUser.java similarity index 97% rename from src/main/java/org/shanerx/tradeshop/objects/ShopUser.java rename to src/main/java/org/shanerx/tradeshop/player/ShopUser.java index 9af04f16..d1b02eb3 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ShopUser.java +++ b/src/main/java/org/shanerx/tradeshop/player/ShopUser.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.player; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; @@ -32,7 +32,6 @@ import org.bukkit.OfflinePlayer; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; -import org.shanerx.tradeshop.enumys.ShopRole; import java.io.Serializable; import java.util.UUID; diff --git a/src/main/java/org/shanerx/tradeshop/enumys/ExchangeStatus.java b/src/main/java/org/shanerx/tradeshop/shop/ExchangeStatus.java similarity index 97% rename from src/main/java/org/shanerx/tradeshop/enumys/ExchangeStatus.java rename to src/main/java/org/shanerx/tradeshop/shop/ExchangeStatus.java index 95517257..99fcaacd 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/ExchangeStatus.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ExchangeStatus.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.shop; //Enum for return from space checks public enum ExchangeStatus { diff --git a/src/main/java/org/shanerx/tradeshop/objects/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/objects/Shop.java rename to src/main/java/org/shanerx/tradeshop/shop/Shop.java index 87dbb070..fe151efe 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.shop; import com.google.gson.Gson; import net.md_5.bungee.api.ChatColor; @@ -37,12 +37,15 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.ShopRole; -import org.shanerx.tradeshop.enumys.ShopStatus; -import org.shanerx.tradeshop.enumys.ShopType; -import org.shanerx.tradeshop.utils.Tuple; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.player.PlayerSetting; +import org.shanerx.tradeshop.player.ShopRole; +import org.shanerx.tradeshop.player.ShopUser; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.utils.objects.Tuple; import java.io.Serializable; import java.util.ArrayList; diff --git a/src/main/java/org/shanerx/tradeshop/objects/ShopChest.java b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/objects/ShopChest.java rename to src/main/java/org/shanerx/tradeshop/shop/ShopChest.java index 7ffc367d..45a8bed4 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ShopChest.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.shop; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -39,9 +39,11 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.persistence.PersistentDataType; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.exceptions.IllegalWorldException; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.shoplocation.IllegalWorldException; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.debug.DebugLevels; import java.util.HashMap; import java.util.List; @@ -50,7 +52,7 @@ public class ShopChest extends Utils { - private final transient static TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); + private final static TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); private ShopLocation shopSign; private final Location loc; private Block chest; diff --git a/src/main/java/org/shanerx/tradeshop/enumys/ShopSign.java b/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java similarity index 90% rename from src/main/java/org/shanerx/tradeshop/enumys/ShopSign.java rename to src/main/java/org/shanerx/tradeshop/shop/ShopSign.java index b21f1a56..10ae2863 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/ShopSign.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java @@ -23,11 +23,12 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.shop; import org.bukkit.Material; -import org.shanerx.tradeshop.utils.BukkitVersion; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.debug.DebugLevels; +import org.shanerx.tradeshop.utils.versionmanagement.BukkitVersion; import java.util.ArrayList; import java.util.Arrays; @@ -53,7 +54,8 @@ enum Signs { CRIMSON_WALL_SIGN("1.16.0", ""), WARPED_WALL_SIGN("1.16.0", ""); - private List minVer = Arrays.asList(new Integer[3]), maxVer = Arrays.asList(new Integer[3]); + private final List minVer = Arrays.asList(new Integer[3]); + private final List maxVer = Arrays.asList(new Integer[3]); private boolean hasMin = true, hasMax = true; Signs(String minVersion, String maxVersion) { @@ -106,8 +108,8 @@ public String getMaxVersionAsString() { public class ShopSign extends Utils { - private BukkitVersion version = new BukkitVersion(); - private ArrayList signTypes = new ArrayList<>(); + private final BukkitVersion version = new BukkitVersion(); + private final ArrayList signTypes = new ArrayList<>(); public ShopSign() { for (Signs type : Signs.values()) { diff --git a/src/main/java/org/shanerx/tradeshop/enumys/ShopStatus.java b/src/main/java/org/shanerx/tradeshop/shop/ShopStatus.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/enumys/ShopStatus.java rename to src/main/java/org/shanerx/tradeshop/shop/ShopStatus.java index fdc60ae0..0c30fc4c 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/ShopStatus.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopStatus.java @@ -23,10 +23,10 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.shop; import org.bukkit.ChatColor; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.data.config.Setting; public enum ShopStatus { diff --git a/src/main/java/org/shanerx/tradeshop/enumys/ShopStorage.java b/src/main/java/org/shanerx/tradeshop/shop/ShopStorage.java similarity index 92% rename from src/main/java/org/shanerx/tradeshop/enumys/ShopStorage.java rename to src/main/java/org/shanerx/tradeshop/shop/ShopStorage.java index d6f2bc20..c60499e4 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/ShopStorage.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopStorage.java @@ -23,12 +23,13 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.shop; import com.google.common.collect.Lists; import org.bukkit.Material; -import org.shanerx.tradeshop.utils.BukkitVersion; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.debug.DebugLevels; +import org.shanerx.tradeshop.utils.versionmanagement.BukkitVersion; import java.util.ArrayList; import java.util.Arrays; @@ -37,8 +38,8 @@ public class ShopStorage extends Utils { - private BukkitVersion version = new BukkitVersion(); - private HashMap storageTypes = new HashMap<>(); + private final BukkitVersion version = new BukkitVersion(); + private final HashMap storageTypes = new HashMap<>(); public ShopStorage() { for (Storages type : Storages.values()) { @@ -93,10 +94,11 @@ public enum Storages { SHULKER_BOX("1.11.0", "", 1, Lists.newArrayList(Material.SHULKER_BOX, Material.WHITE_SHULKER_BOX, Material.ORANGE_SHULKER_BOX, Material.MAGENTA_SHULKER_BOX, Material.LIGHT_BLUE_SHULKER_BOX, Material.YELLOW_SHULKER_BOX, Material.LIME_SHULKER_BOX, Material.PINK_SHULKER_BOX, Material.GRAY_SHULKER_BOX, Material.LIGHT_GRAY_SHULKER_BOX, Material.CYAN_SHULKER_BOX, Material.PURPLE_SHULKER_BOX, Material.BLUE_SHULKER_BOX, Material.BROWN_SHULKER_BOX, Material.GREEN_SHULKER_BOX, Material.RED_SHULKER_BOX, Material.BLACK_SHULKER_BOX)), SMOKER("1.14.0", "", 10, Lists.newArrayList(Material.SMOKER)); - private List minVer = Arrays.asList(new Integer[3]), maxVer = Arrays.asList(new Integer[3]); + private final List minVer = Arrays.asList(new Integer[3]); + private final List maxVer = Arrays.asList(new Integer[3]); private boolean hasMin = true, hasMax = true; private int weight = 10; - private List typeMaterials; + private final List typeMaterials; Storages(String minVersion, String maxVersion, int weight, List typeMaterials) { if (minVersion.equalsIgnoreCase("")) diff --git a/src/main/java/org/shanerx/tradeshop/enumys/ShopType.java b/src/main/java/org/shanerx/tradeshop/shop/ShopType.java similarity index 91% rename from src/main/java/org/shanerx/tradeshop/enumys/ShopType.java rename to src/main/java/org/shanerx/tradeshop/shop/ShopType.java index 9b2e0092..69af9931 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/ShopType.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopType.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.shop; import com.google.gson.Gson; import org.bukkit.Bukkit; @@ -32,7 +32,9 @@ import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.ShopRole; import java.io.Serializable; @@ -45,7 +47,7 @@ public enum ShopType implements Serializable { BITRADE(Setting.BITRADESHOP_HEADER.getString(), Permissions.CREATEBI); - private final transient static TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); + private final static TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); private final String key; private final transient Permissions perm; diff --git a/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java similarity index 91% rename from src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java rename to src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java index f7903f30..1af79caa 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.listeners; +package org.shanerx.tradeshop.shop.listeners; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -35,17 +35,17 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.enumys.ShopRole; -import org.shanerx.tradeshop.enumys.ShopType; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.framework.events.PlayerShopCreateEvent; -import org.shanerx.tradeshop.objects.IllegalItemList; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopChest; -import org.shanerx.tradeshop.objects.ShopUser; -import org.shanerx.tradeshop.utils.Tuple; +import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.player.ShopRole; +import org.shanerx.tradeshop.player.ShopUser; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopChest; +import org.shanerx.tradeshop.shop.ShopType; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Message; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.utils.objects.Tuple; @SuppressWarnings("unused") public class ShopCreateListener extends Utils implements Listener { diff --git a/src/main/java/org/shanerx/tradeshop/listeners/ShopProtectionListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/listeners/ShopProtectionListener.java rename to src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java index 21aa816b..68804d90 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/ShopProtectionListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.listeners; +package org.shanerx.tradeshop.shop.listeners; import org.bukkit.Bukkit; import org.bukkit.block.Block; @@ -43,18 +43,18 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.enumys.Permissions; -import org.shanerx.tradeshop.enumys.ShopType; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.framework.events.HopperShopAccessEvent; import org.shanerx.tradeshop.framework.events.PlayerShopDestroyEvent; import org.shanerx.tradeshop.framework.events.PlayerShopInventoryOpenEvent; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopChest; -import org.shanerx.tradeshop.objects.ShopLocation; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopChest; +import org.shanerx.tradeshop.shop.ShopType; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Message; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.utils.debug.DebugLevels; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/shanerx/tradeshop/listeners/ShopRestockListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopRestockListener.java similarity index 93% rename from src/main/java/org/shanerx/tradeshop/listeners/ShopRestockListener.java rename to src/main/java/org/shanerx/tradeshop/shop/listeners/ShopRestockListener.java index 07abb6b1..02d5b258 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/ShopRestockListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopRestockListener.java @@ -23,15 +23,15 @@ * */ -package org.shanerx.tradeshop.listeners; +package org.shanerx.tradeshop.shop.listeners; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryCloseEvent; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopChest; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopChest; import org.shanerx.tradeshop.utils.Utils; public class ShopRestockListener extends Utils implements Listener { diff --git a/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java rename to src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java index df54afef..20e6dd34 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.listeners; +package org.shanerx.tradeshop.shop.listeners; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -39,19 +39,19 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.shanerx.tradeshop.enumys.ExchangeStatus; -import org.shanerx.tradeshop.enumys.Permissions; -import org.shanerx.tradeshop.enumys.ShopType; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.config.Variable; import org.shanerx.tradeshop.framework.events.PlayerPreTradeEvent; import org.shanerx.tradeshop.framework.events.PlayerPrepareTradeEvent; import org.shanerx.tradeshop.framework.events.PlayerSuccessfulTradeEvent; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopLocation; -import org.shanerx.tradeshop.utils.Tuple; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.shop.ExchangeStatus; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopType; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Message; -import org.shanerx.tradeshop.utils.config.Setting; -import org.shanerx.tradeshop.utils.config.Variable; +import org.shanerx.tradeshop.utils.objects.Tuple; import java.util.Collections; import java.util.HashMap; diff --git a/src/main/java/org/shanerx/tradeshop/exceptions/IllegalWorldException.java b/src/main/java/org/shanerx/tradeshop/shoplocation/IllegalWorldException.java similarity index 93% rename from src/main/java/org/shanerx/tradeshop/exceptions/IllegalWorldException.java rename to src/main/java/org/shanerx/tradeshop/shoplocation/IllegalWorldException.java index 65342eda..e0be6587 100644 --- a/src/main/java/org/shanerx/tradeshop/exceptions/IllegalWorldException.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/IllegalWorldException.java @@ -23,9 +23,7 @@ * */ -package org.shanerx.tradeshop.exceptions; - -import org.shanerx.tradeshop.objects.WorldlessLocation; +package org.shanerx.tradeshop.shoplocation; public class IllegalWorldException extends IllegalStateException { diff --git a/src/main/java/org/shanerx/tradeshop/objects/ShopChunk.java b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/objects/ShopChunk.java rename to src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java index e8087089..dfc3c8a2 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ShopChunk.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.shoplocation; import org.bukkit.Bukkit; import org.bukkit.Chunk; diff --git a/src/main/java/org/shanerx/tradeshop/objects/ShopLocation.java b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/objects/ShopLocation.java rename to src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java index c2cd5091..654b8622 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ShopLocation.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java @@ -23,13 +23,12 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.shoplocation; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; -import org.shanerx.tradeshop.exceptions.IllegalWorldException; import java.io.Serializable; diff --git a/src/main/java/org/shanerx/tradeshop/objects/package-info.java b/src/main/java/org/shanerx/tradeshop/shoplocation/WorldlessLocation.java similarity index 67% rename from src/main/java/org/shanerx/tradeshop/objects/package-info.java rename to src/main/java/org/shanerx/tradeshop/shoplocation/WorldlessLocation.java index 2b0d03f0..a0dbdef7 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/package-info.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/WorldlessLocation.java @@ -23,14 +23,24 @@ * */ -/** - * This class contains all the classes of the core of the plugin. - * The reason we are adding them to the docs are that the custom event framework - * makes use of the {@link org.shanerx.tradeshop.objects.Shop} class, - * and should only be used for read purposes, ie. accessing getters. - * - * - * NOTE: DO NOT ATTEMPT TO CHANGE THE PLUGIN'S INTERNAL DATA, NOT EVEN WITH SETTER METHODS, - * IF YOU DO NOT POSSESS AN UNDERSTANDING OF THE INTERNAL WORKINGS OF THE PLUGIN! - */ -package org.shanerx.tradeshop.objects; \ No newline at end of file +package org.shanerx.tradeshop.shoplocation; + +import org.bukkit.Location; +import org.bukkit.World; + +public class WorldlessLocation { + + private final double x; + private final double y; + private final double z; + + public WorldlessLocation(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public Location getLocation(World w) { + return new Location(w, x, y, z); + } +} diff --git a/src/main/java/org/shanerx/tradeshop/objects/ListManager.java b/src/main/java/org/shanerx/tradeshop/utils/ListManager.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/objects/ListManager.java rename to src/main/java/org/shanerx/tradeshop/utils/ListManager.java index f1ebb319..92c5c62e 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ListManager.java +++ b/src/main/java/org/shanerx/tradeshop/utils/ListManager.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.utils; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; @@ -31,11 +31,11 @@ import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.enumys.NonObtainableMaterials; -import org.shanerx.tradeshop.enumys.ShopStorage; -import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.item.NonObtainableMaterials; +import org.shanerx.tradeshop.shop.ShopStorage; +import org.shanerx.tradeshop.utils.debug.DebugLevels; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java b/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java index 58965d4a..78f34f32 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java +++ b/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java @@ -33,8 +33,8 @@ import org.bstats.charts.SingleLineChart; import org.bukkit.World; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.utils.config.Message; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; import java.util.Arrays; import java.util.HashMap; diff --git a/src/main/java/org/shanerx/tradeshop/utils/Tuple.java b/src/main/java/org/shanerx/tradeshop/utils/Tuple.java deleted file mode 100644 index 0aad5610..00000000 --- a/src/main/java/org/shanerx/tradeshop/utils/Tuple.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2016-2019 - * SparklingComet @ http://shanerx.org - * KillerOfPie @ http://killerofpie.github.io - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * NOTICE: All modifications made by others to the source code belong - * to the respective contributor. No contributor should be held liable for - * any damages of any kind, whether be material or moral, which were - * caused by their contribution(s) to the project. See the full License for more information. - */ - -package org.shanerx.tradeshop.utils; - -import com.google.gson.Gson; -import com.google.gson.annotations.SerializedName; - -import java.io.Serializable; - -public class Tuple implements Serializable { - - @SerializedName("right") - private R r; - @SerializedName("left") - private L l; - - public Tuple() { - } - - public Tuple(L l, R r) { - this.r = r; - this.l = l; - } - - public Tuple(Tuple t) { - this.r = t.r; - this.l = t.l; - } - - public R getRight() { - return r; - } - - public L getLeft() { - return l; - } - - public String serialize() { - return new Gson().toJson(this); - } - - @Override - public String toString() { - return serialize(); - } -} \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 01d293d3..9496bcca 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -40,17 +40,18 @@ import org.bukkit.material.MaterialData; import org.bukkit.plugin.PluginDescriptionFile; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.enumys.ExchangeStatus; -import org.shanerx.tradeshop.enumys.ShopType; -import org.shanerx.tradeshop.objects.Debug; -import org.shanerx.tradeshop.objects.IllegalItemList; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopChest; -import org.shanerx.tradeshop.objects.ShopItemStack; -import org.shanerx.tradeshop.objects.ShopLocation; -import org.shanerx.tradeshop.utils.config.Message; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.shop.ExchangeStatus; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopChest; +import org.shanerx.tradeshop.shop.ShopType; +import org.shanerx.tradeshop.shoplocation.ShopLocation; +import org.shanerx.tradeshop.utils.debug.Debug; +import org.shanerx.tradeshop.utils.debug.DebugLevels; +import org.shanerx.tradeshop.utils.objects.Tuple; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/shanerx/tradeshop/objects/Debug.java b/src/main/java/org/shanerx/tradeshop/utils/debug/Debug.java similarity index 95% rename from src/main/java/org/shanerx/tradeshop/objects/Debug.java rename to src/main/java/org/shanerx/tradeshop/utils/debug/Debug.java index ff6aa403..6ff76df3 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/Debug.java +++ b/src/main/java/org/shanerx/tradeshop/utils/debug/Debug.java @@ -23,11 +23,10 @@ * */ -package org.shanerx.tradeshop.objects; +package org.shanerx.tradeshop.utils.debug; import org.bukkit.Bukkit; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.utils.config.Setting; +import org.shanerx.tradeshop.data.config.Setting; import java.util.logging.Level; diff --git a/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java b/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java rename to src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java index 65167eb3..d09bacbc 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java +++ b/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.enumys; +package org.shanerx.tradeshop.utils.debug; import java.util.logging.Level; diff --git a/src/main/java/org/shanerx/tradeshop/utils/ObjectHolder.java b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java similarity index 96% rename from src/main/java/org/shanerx/tradeshop/utils/ObjectHolder.java rename to src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java index 5fef81db..084e7b2d 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/ObjectHolder.java +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils; +package org.shanerx.tradeshop.utils.objects; public class ObjectHolder { diff --git a/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java b/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java new file mode 100644 index 00000000..181e9c3a --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java @@ -0,0 +1,69 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.utils.objects; + +import com.google.gson.Gson; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class Tuple implements Serializable { + + @SerializedName("right") + private R r; + @SerializedName("left") + private L l; + + public Tuple() { + } + + public Tuple(L l, R r) { + this.r = r; + this.l = l; + } + + public Tuple(Tuple t) { + this.r = t.r; + this.l = t.l; + } + + public R getRight() { + return r; + } + + public L getLeft() { + return l; + } + + public String serialize() { + return new Gson().toJson(this); + } + + @Override + public String toString() { + return serialize(); + } +} \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/BukkitVersion.java b/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/BukkitVersion.java similarity index 98% rename from src/main/java/org/shanerx/tradeshop/utils/BukkitVersion.java rename to src/main/java/org/shanerx/tradeshop/utils/versionmanagement/BukkitVersion.java index d37d2f28..813f4380 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/BukkitVersion.java +++ b/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/BukkitVersion.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils; +package org.shanerx.tradeshop.utils.versionmanagement; import org.bukkit.Bukkit; diff --git a/src/main/java/org/shanerx/tradeshop/utils/Expirer.java b/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/Expirer.java similarity index 97% rename from src/main/java/org/shanerx/tradeshop/utils/Expirer.java rename to src/main/java/org/shanerx/tradeshop/utils/versionmanagement/Expirer.java index c8bd0203..686c1d13 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Expirer.java +++ b/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/Expirer.java @@ -23,14 +23,14 @@ * */ -package org.shanerx.tradeshop.utils; +package org.shanerx.tradeshop.utils.versionmanagement; import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.scheduler.BukkitScheduler; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.enumys.DebugLevels; -import org.shanerx.tradeshop.enumys.Permissions; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.utils.debug.DebugLevels; import java.io.InputStreamReader; import java.time.Duration; diff --git a/src/main/java/org/shanerx/tradeshop/utils/Updater.java b/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/Updater.java similarity index 99% rename from src/main/java/org/shanerx/tradeshop/utils/Updater.java rename to src/main/java/org/shanerx/tradeshop/utils/versionmanagement/Updater.java index d85bd006..9ca0bb21 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Updater.java +++ b/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/Updater.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils; +package org.shanerx.tradeshop.utils.versionmanagement; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginDescriptionFile; From cb9704bc59828b5222cdc96ce8bdfea6f1029503 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Tue, 24 May 2022 18:26:19 -0700 Subject: [PATCH 02/53] Re-org classes by usage + Missed package-info --- .../tradeshop/shoplocation/package-info.java | 29 ++++++++++++++++++ .../tradeshop/utils/debug/package-info.java | 29 ++++++++++++++++++ .../tradeshop/utils/objects/package-info.java | 30 +++++++++++++++++++ .../utils/versionmanagement/package-info.java | 30 +++++++++++++++++++ 4 files changed, 118 insertions(+) create mode 100644 src/main/java/org/shanerx/tradeshop/shoplocation/package-info.java create mode 100644 src/main/java/org/shanerx/tradeshop/utils/debug/package-info.java create mode 100644 src/main/java/org/shanerx/tradeshop/utils/objects/package-info.java create mode 100644 src/main/java/org/shanerx/tradeshop/utils/versionmanagement/package-info.java diff --git a/src/main/java/org/shanerx/tradeshop/shoplocation/package-info.java b/src/main/java/org/shanerx/tradeshop/shoplocation/package-info.java new file mode 100644 index 00000000..a20a6449 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/package-info.java @@ -0,0 +1,29 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +/** + * The classes in this package handle location data for usage across the plugin + */ +package org.shanerx.tradeshop.shoplocation; \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/debug/package-info.java b/src/main/java/org/shanerx/tradeshop/utils/debug/package-info.java new file mode 100644 index 00000000..64b839e6 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/debug/package-info.java @@ -0,0 +1,29 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +/** + * The classes in this package are used to simplify and manage debug output for Tradeshop. + */ +package org.shanerx.tradeshop.utils.debug; \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/objects/package-info.java b/src/main/java/org/shanerx/tradeshop/utils/objects/package-info.java new file mode 100644 index 00000000..d1e78632 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/package-info.java @@ -0,0 +1,30 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +/** + * The classes in this package are used for generic object holding/combining, + * Feel free to implement them within your project as external dependencies. + */ +package org.shanerx.tradeshop.utils.objects; \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/package-info.java b/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/package-info.java new file mode 100644 index 00000000..5c013d64 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/versionmanagement/package-info.java @@ -0,0 +1,30 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +/** + * The classes in this package are used for checking/comparing versions of this plugin, as well as bukkit. + * All Classes except for BukkitVersion.java are plugin specific and should not be used outside of Tradeshop. + */ +package org.shanerx.tradeshop.utils.versionmanagement; \ No newline at end of file From 8f652a863d8a9dcad92ec78d74acc1542e283185 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Tue, 24 May 2022 21:23:32 -0700 Subject: [PATCH 03/53] Separation of CommandRunner.java and DRY'd Shop item methods --- .../tradeshop/commands/CommandCaller.java | 67 +- .../tradeshop/commands/CommandRunner.java | 1148 ----------------- .../commands/commandrunners/AdminCommand.java | 140 ++ .../commandrunners/BasicTextCommand.java | 103 ++ .../commandrunners/CommandRunner.java | 96 ++ .../commandrunners/CreateCommand.java | 196 +++ .../{ => commandrunners}/EditCommand.java | 26 +- .../commands/commandrunners/GUICommand.java | 70 + .../commandrunners/GeneralPlayerCommand.java | 109 ++ .../commands/commandrunners/ShopCommand.java | 147 +++ .../commandrunners/ShopItemCommand.java | 262 ++++ .../commandrunners/ShopUserCommand.java | 210 +++ .../{ => commandrunners}/WhatCommand.java | 22 +- .../tradeshop/data/config/Message.java | 2 +- .../tradeshop/item/IllegalItemList.java | 7 - .../shanerx/tradeshop/item/ShopItemSide.java | 43 + .../java/org/shanerx/tradeshop/shop/Shop.java | 436 +++---- .../shop/listeners/ShopCreateListener.java | 20 +- .../shop/listeners/ShopTradeListener.java | 27 +- .../shanerx/tradeshop/utils/ListManager.java | 8 +- .../org/shanerx/tradeshop/utils/Utils.java | 24 +- src/main/resources/Lang/en-us.yml | 6 +- 22 files changed, 1658 insertions(+), 1511 deletions(-) delete mode 100644 src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/BasicTextCommand.java create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/CommandRunner.java create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/CreateCommand.java rename src/main/java/org/shanerx/tradeshop/commands/{ => commandrunners}/EditCommand.java (95%) create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/GeneralPlayerCommand.java create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopCommand.java create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java create mode 100644 src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java rename src/main/java/org/shanerx/tradeshop/commands/{ => commandrunners}/WhatCommand.java (92%) create mode 100644 src/main/java/org/shanerx/tradeshop/item/ShopItemSide.java diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java index 3b6f562f..c64cafa2 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java @@ -29,7 +29,18 @@ import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.commandrunners.AdminCommand; +import org.shanerx.tradeshop.commands.commandrunners.BasicTextCommand; +import org.shanerx.tradeshop.commands.commandrunners.CommandRunner; +import org.shanerx.tradeshop.commands.commandrunners.CreateCommand; +import org.shanerx.tradeshop.commands.commandrunners.EditCommand; +import org.shanerx.tradeshop.commands.commandrunners.GeneralPlayerCommand; +import org.shanerx.tradeshop.commands.commandrunners.ShopCommand; +import org.shanerx.tradeshop.commands.commandrunners.ShopItemCommand; +import org.shanerx.tradeshop.commands.commandrunners.ShopUserCommand; +import org.shanerx.tradeshop.commands.commandrunners.WhatCommand; import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.item.ShopItemSide; /** * This class is used for calling command methods from CommandRunner @@ -73,94 +84,94 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String switch (command) { case HELP: - cmdRnnr.help(); + new BasicTextCommand(plugin, cmdPass).help(); break; case BUGS: - cmdRnnr.bugs(); + new BasicTextCommand(plugin, cmdPass).bugs(); break; case SETUP: - cmdRnnr.setup(); + new BasicTextCommand(plugin, cmdPass).setup(); break; case RELOAD: - cmdRnnr.reload(); + new AdminCommand(plugin, cmdPass).reload(); break; case ADD_PRODUCT: - cmdRnnr.addProduct(); + new ShopItemCommand(plugin, cmdPass, ShopItemSide.PRODUCT).addSide(); break; case ADD_COST: - cmdRnnr.addCost(); + new ShopItemCommand(plugin, cmdPass, ShopItemSide.COST).addSide(); break; case OPEN: - cmdRnnr.open(); + new ShopCommand(plugin, cmdPass).open(); break; case CLOSE: - cmdRnnr.close(); + new ShopCommand(plugin, cmdPass).close(); break; case SWITCH: - cmdRnnr.switchShop(); + new ShopCommand(plugin, cmdPass).switchShop(); break; case WHAT: new WhatCommand(plugin, cmdPass).what(); break; case WHO: - cmdRnnr.who(); + new ShopUserCommand(plugin, cmdPass).who(); break; case ADD_MANAGER: - cmdRnnr.addManager(); + new ShopUserCommand(plugin, cmdPass).addManager(); break; case REMOVE_USER: - cmdRnnr.removeUser(); + new ShopUserCommand(plugin, cmdPass).removeUser(); break; case ADD_MEMBER: - cmdRnnr.addMember(); + new ShopUserCommand(plugin, cmdPass).addMember(); break; case MULTI: - cmdRnnr.multi(); + new GeneralPlayerCommand(plugin, cmdPass).multi(); break; case SET_PRODUCT: - cmdRnnr.setProduct(); + new ShopItemCommand(plugin, cmdPass, ShopItemSide.PRODUCT).setSide(); break; case SET_COST: - cmdRnnr.setCost(); + new ShopItemCommand(plugin, cmdPass, ShopItemSide.COST).setSide(); break; case LIST_PRODUCT: - cmdRnnr.listProduct(); + new ShopItemCommand(plugin, cmdPass, ShopItemSide.PRODUCT).listSide(); break; case LIST_COST: - cmdRnnr.listCost(); + new ShopItemCommand(plugin, cmdPass, ShopItemSide.COST).listSide(); break; case REMOVE_PRODUCT: - cmdRnnr.removeProduct(); + new ShopItemCommand(plugin, cmdPass, ShopItemSide.PRODUCT).removeSide(); break; case REMOVE_COST: - cmdRnnr.removeCost(); + new ShopItemCommand(plugin, cmdPass, ShopItemSide.COST).removeSide(); break; case PLAYER_LEVEL: - cmdRnnr.playerLevel(); + new AdminCommand(plugin, cmdPass).playerLevel(); break; case STATUS: - cmdRnnr.status(); + new GeneralPlayerCommand(plugin, cmdPass).status(); break; case EDIT: new EditCommand(plugin, cmdPass).edit(); break; case TOGGLE_STATUS: - cmdRnnr.toggleStatus(); + new GeneralPlayerCommand(plugin, cmdPass).toggleStatus(); break; case CREATE_TRADE: - cmdRnnr.createTrade(); + new CreateCommand(plugin, cmdPass).createTrade(); break; case CREATE_BITRADE: - cmdRnnr.createBiTrade(); + new CreateCommand(plugin, cmdPass).createBiTrade(); break; case CREATE_ITRADE: - cmdRnnr.createITrade(); + new CreateCommand(plugin, cmdPass).createITrade(); break; case TOGGLE_ADMIN: - cmdRnnr.toggleAdmin(); + new AdminCommand(plugin, cmdPass).toggleAdmin(); break; case ADMIN: - cmdRnnr.admin(); + new AdminCommand(plugin, cmdPass).admin(); break; } diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java deleted file mode 100644 index 032f754c..00000000 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java +++ /dev/null @@ -1,1148 +0,0 @@ -/* - * - * Copyright (c) 2016-2019 - * SparklingComet @ http://shanerx.org - * KillerOfPie @ http://killerofpie.github.io - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * NOTICE: All modifications made by others to the source code belong - * to the respective contributor. No contributor should be held liable for - * any damages of any kind, whether be material or moral, which were - * caused by their contribution(s) to the project. See the full License for more information. - * - */ - -package org.shanerx.tradeshop.commands; - -import de.themoep.inventorygui.GuiPageElement; -import de.themoep.inventorygui.InventoryGui; -import de.themoep.inventorygui.StaticGuiElement; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.data.config.Message; -import org.shanerx.tradeshop.data.config.Setting; -import org.shanerx.tradeshop.data.config.Variable; -import org.shanerx.tradeshop.data.storage.DataType; -import org.shanerx.tradeshop.framework.ShopChange; -import org.shanerx.tradeshop.framework.events.PlayerShopChangeEvent; -import org.shanerx.tradeshop.framework.events.PlayerShopCloseEvent; -import org.shanerx.tradeshop.framework.events.PlayerShopCreateEvent; -import org.shanerx.tradeshop.framework.events.PlayerShopOpenEvent; -import org.shanerx.tradeshop.framework.events.TradeShopReloadEvent; -import org.shanerx.tradeshop.item.IllegalItemList; -import org.shanerx.tradeshop.item.ShopItemStack; -import org.shanerx.tradeshop.player.PermStatus; -import org.shanerx.tradeshop.player.Permissions; -import org.shanerx.tradeshop.player.PlayerSetting; -import org.shanerx.tradeshop.player.ShopRole; -import org.shanerx.tradeshop.player.ShopUser; -import org.shanerx.tradeshop.shop.Shop; -import org.shanerx.tradeshop.shop.ShopChest; -import org.shanerx.tradeshop.shop.ShopStatus; -import org.shanerx.tradeshop.shop.ShopType; -import org.shanerx.tradeshop.shoplocation.ShopLocation; -import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.debug.DebugLevels; -import org.shanerx.tradeshop.utils.objects.ObjectHolder; -import org.shanerx.tradeshop.utils.objects.Tuple; - -public class CommandRunner extends Utils { - - protected final TradeShop plugin; - protected final CommandPass command; - protected Player pSender; - - protected final GuiPageElement PREV_BUTTON = new GuiPageElement('p', new ItemStack(Material.POTION), GuiPageElement.PageAction.PREVIOUS, "Go to previous page (%prevpage%)"), - NEXT_BUTTON = new GuiPageElement('n', new ItemStack(Material.SPLASH_POTION), GuiPageElement.PageAction.NEXT, "Go to next page (%nextpage%)"); - protected final StaticGuiElement CANCEL_BUTTON = new StaticGuiElement('c', new ItemStack(Material.END_CRYSTAL), click3 -> { - InventoryGui.goBack(pSender); - return true; - }, "Cancel Changes"), - BACK_BUTTON = new StaticGuiElement('b', new ItemStack(Material.END_CRYSTAL), click3 -> { - InventoryGui.goBack(pSender); - return true; - }, "Back"); - protected final String[] MENU_LAYOUT = {"a b c"}, - EDIT_LAYOUT = {"aggggggga", "ap c s na"}, - ITEM_LAYOUT = {"aggggggga", "aggggggga", "a cbs a"}, - WHAT_MENU = {"141125333", "1aaa2bbb3", "11p123n33"}; - - public CommandRunner(TradeShop instance, CommandPass command) { - this.plugin = instance; - this.command = command; - - if (command.getSender() instanceof Player) { - pSender = (Player) command.getSender(); - } - } - - /** - * Builds and sends the sender the help message - */ - public void help() { - if (command.argsSize() == 2) { - usage(command.getArgAt(1)); - return; - } - - StringBuilder sb = new StringBuilder(); - - sb.append("\n&2") - .append(getPluginName()) - .append(" ") - .append(getVersion()) - .append(" by ").append(pdf.getAuthors().get(0)).append(" & ").append(pdf.getAuthors().get(1)) - .append("\n\n&b/tradeshop &f &f Display help message\n"); - - for (Commands c : Commands.values()) { - if (c.checkPerm(command.getSender()) == PermStatus.GOOD) { - sb.append(plugin.getMessageManager().colour(String.format("&b/ts %s &f %s\n", c.getFirstName(), c.getDescription()))); - } - } - - sb.append("\n "); - command.sendMessage(colorize(sb.toString())); - } - - public void usage(String subcmd) { - Commands cmd = Commands.getType(subcmd); - if (cmd == null) { - command.sendMessage(plugin.getMessageManager().colour(String.format("&4Cannot find usages for &c%s&r", subcmd))); - return; - } - command.sendMessage(plugin.getMessageManager().colour(String.format("&6Showing help for &c%s&r\n&bUsage:&e %s \n&bAliases: %s\n&bDescription:&e %s", subcmd, cmd.getUsage(), cmd.getAliases(), cmd.getDescription()))); - } - - /** - * Sends the sender the bug message - */ - public void bugs() { - command.sendMessage("\n&a[&eTradeShop&a] \n&2To report any bugs to the author, either send a PM on &cSpigot &2- &egoo.gl/s6Jk23 &2or open an issue on &cGitHub &2-&e goo.gl/X4qqyg\n"); - } - - /** - * Sends the sender the setup message - */ - public void setup() { - Message.SETUP_HELP.sendMessage(pSender, new Tuple<>(Variable.HEADER.toString(), Setting.TRADESHOP_HEADER.getString())); - } - - /** - * Reloads the plugin and sends success message - */ - public void reload() { - plugin.getLanguage().reload(); - plugin.getSettingManager().reload(); - plugin.getMessageManager().reload(); - plugin.getListManager().reload(); - plugin.getDebugger().reload(); - try { - plugin.getDataStorage().reload(DataType.valueOf(Setting.DATA_STORAGE_TYPE.getString().toUpperCase())); - } catch (IllegalArgumentException iae) { - debugger.log("Config value for data storage set to an invalid value: " + Setting.DATA_STORAGE_TYPE.getString(), DebugLevels.DATA_ERROR); - debugger.log("TradeShop will now disable...", DebugLevels.DATA_ERROR); - plugin.getServer().getPluginManager().disablePlugin(plugin); - return; - } - - command.sendMessage(Setting.MESSAGE_PREFIX.getString() + "&6The configuration files have been reloaded!"); - Bukkit.getPluginManager().callEvent(new TradeShopReloadEvent(plugin, command.getSender())); - } - - /** - * Lists products with their index - */ - public void listProduct() { - Shop shop = findShop(); - - if (shop == null) - return; - - StringBuilder sb = new StringBuilder(); - int counter = 1; - - for (ShopItemStack itm : shop.getProduct()) { - sb.append(String.format("&b[&f%d&b] &2- &f%s\n", counter, itm.getCleanItemName())); - counter++; - } - - Message.SHOP_ITEM_LIST.sendMessage(pSender, new Tuple<>(Variable.TYPE.toString(), "products"), new Tuple<>(Variable.LIST.toString(), sb.toString())); - } - - /** - * Lists costs with their index - */ - public void listCost() { - Shop shop = findShop(); - - if (shop == null) - return; - - StringBuilder sb = new StringBuilder(); - int counter = 1; - - for (ShopItemStack itm : shop.getCost()) { - sb.append(String.format("&b[&f%d&b] &2- &f%s\n", counter, itm.getCleanItemName())); - counter++; - } - - Message.SHOP_ITEM_LIST.sendMessage(pSender, new Tuple<>(Variable.TYPE.toString(), "costs"), new Tuple<>(Variable.LIST.toString(), sb.toString())); - } - - /** - * Removes product at index - */ - public void removeProduct() { - Shop shop = findShop(); - - if (shop == null) - return; - - int index = 0; - - if (isInt(command.getArgAt(1))) { - index = Integer.parseInt(command.getArgAt(1)) - 1; - } else { - Message.INVALID_ARGUMENTS.sendMessage(pSender); - return; - } - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.REMOVE_PRODUCT, new ObjectHolder(index)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - if (shop.removeProduct(index)) - Message.ITEM_REMOVED.sendMessage(pSender); - else - Message.ITEM_NOT_REMOVED.sendMessage(pSender); - } - - /** - * Removes cost at index - */ - public void removeCost() { - Shop shop = findShop(); - - if (shop == null) - return; - - int index; - - if (isInt(command.getArgAt(1))) { - index = Integer.parseInt(command.getArgAt(1)) - 1; - } else { - Message.INVALID_ARGUMENTS.sendMessage(pSender); - return; - } - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.REMOVE_COST, new ObjectHolder(index)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - if (shop.removeCost(index)) - Message.ITEM_REMOVED.sendMessage(pSender); - else - Message.ITEM_NOT_REMOVED.sendMessage(pSender); - } - - /** - * Sets a product to a Shop - *

- * With no variables sent will use the amount and data of the held item for product - *

- *

- * If the player uses a int in the first variable they can change the amount for the item they are holding - *

- *

- * With 2 variables used the player can use an amount and material to set the sign instead of a held item - *

- */ - public void setProduct() { - Shop shop = findShop(); - - if (shop == null) - return; - - int amount = 0; - Material mat = null; - - if (command.hasArgAt(1) && isInt(command.getArgAt(1))) { - amount = Integer.parseInt(command.getArgAt(1)); - } - - if (command.hasArgAt(2) && Material.getMaterial(command.getArgAt(2).toUpperCase()) != null) { - mat = Material.getMaterial(command.getArgAt(2).toUpperCase()); - } - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - ItemStack itemInHand; - - if (mat == null) { - itemInHand = pSender.getInventory().getItemInMainHand().clone(); - } else { - itemInHand = new ItemStack(mat, 1); - } - - if (itemInHand.getType() == Material.AIR) { - Message.HELD_EMPTY.sendMessage(pSender); - return; - } - - if (isIllegal(IllegalItemList.TradeItemType.PRODUCT, itemInHand.getType())) { - Message.ILLEGAL_ITEM.sendMessage(pSender); - return; - } - - if (!(shop.getShopType().isITrade() && shop.getInventoryLocation() == null) && itemInHand.getType().toString().endsWith("SHULKER_BOX") && shop.getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")) { - Message.NO_SHULKER_COST.sendMessage(pSender); - return; - } - - if (amount > 0) { - itemInHand.setAmount(amount); - } - - if (Math.ceil((double) itemInHand.getAmount() / (double) itemInHand.getMaxStackSize()) > Setting.MAX_ITEMS_PER_TRADE_SIDE.getInt()) { - Message.TOO_MANY_ITEMS.sendMessage(pSender, new Tuple<>(Variable.SIDE.toString(), "product")); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.SET_PRODUCT, new ObjectHolder(itemInHand)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - shop.setProduct(itemInHand); - - Message.ITEM_ADDED.sendMessage(pSender); - } - - /** - * Adds a product to a Shop - *

- * With no variables sent will use the amount and data of the held item for product - *

- *

- * If the player uses a int in the first variable they can change the amount for the item they are holding - *

- *

- * With 2 variables used the player can use an amount and material to set the sign instead of a held item - *

- */ - public void addProduct() { - Shop shop = findShop(); - - if (shop == null) - return; - - int amount = 0; - Material mat = null; - - if (command.hasArgAt(1) && isInt(command.getArgAt(1))) { - amount = Integer.parseInt(command.getArgAt(1)); - } - - if (command.hasArgAt(2) && Material.getMaterial(command.getArgAt(2).toUpperCase()) != null) { - mat = Material.getMaterial(command.getArgAt(2).toUpperCase()); - } - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - ItemStack itemInHand; - - if (mat == null) { - itemInHand = pSender.getInventory().getItemInMainHand().clone(); - } else { - itemInHand = new ItemStack(mat, 1); - } - - if (itemInHand.getType() == Material.AIR) { - Message.HELD_EMPTY.sendMessage(pSender); - return; - } - - if (isIllegal(IllegalItemList.TradeItemType.PRODUCT, itemInHand.getType())) { - Message.ILLEGAL_ITEM.sendMessage(pSender); - return; - } - - if (!(shop.getShopType().isITrade() && shop.getInventoryLocation() == null) && itemInHand.getType().toString().endsWith("SHULKER_BOX") && shop.getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")) { - Message.NO_SHULKER_COST.sendMessage(pSender); - return; - } - - if (amount > 0) { - itemInHand.setAmount(amount); - } - - if (shop.getProduct().size() + Math.ceil((double) itemInHand.getAmount() / (double) itemInHand.getMaxStackSize()) > Setting.MAX_ITEMS_PER_TRADE_SIDE.getInt()) { - Message.TOO_MANY_ITEMS.sendMessage(pSender, new Tuple<>(Variable.SIDE.toString(), "product")); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.ADD_PRODUCT, new ObjectHolder(itemInHand)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - shop.addProduct(itemInHand); - - Message.ITEM_ADDED.sendMessage(pSender); - } - - /** - * Sets the item to the shop - *

- * With no variables sent will use the amount and data of the held item for cost - *

- *

- * If the player uses a int in the first variable they can change the amount for the item they are holding - *

- *

- * With 2 variables used the player can use an amount and material to set the sign instead of a held item - *

- */ - public void setCost() { - Shop shop = findShop(); - - if (shop == null) - return; - - int amount = 0; - Material mat = null; - - if (command.hasArgAt(1) && isInt(command.getArgAt(1))) { - amount = Integer.parseInt(command.getArgAt(1)); - } - - if (command.hasArgAt(2) && Material.getMaterial(command.getArgAt(2).toUpperCase()) != null) { - mat = Material.getMaterial(command.getArgAt(2).toUpperCase()); - } - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - ItemStack costItem; - - if (mat == null) { - costItem = pSender.getInventory().getItemInMainHand().clone(); - } else { - costItem = new ItemStack(mat, 1); - } - - if (costItem.getType() == Material.AIR) { - Message.HELD_EMPTY.sendMessage(pSender); - return; - } - - if (isIllegal(IllegalItemList.TradeItemType.COST, costItem.getType())) { - Message.ILLEGAL_ITEM.sendMessage(pSender); - return; - } - - if (!(shop.getShopType().isITrade() && shop.getInventoryLocation() == null) && costItem.getType().toString().endsWith("SHULKER_BOX") && shop.getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")) { - Message.NO_SHULKER_COST.sendMessage(pSender); - return; - } - - if (amount > 0) { - costItem.setAmount(amount); - } - - if (Math.ceil((double) costItem.getAmount() / (double) costItem.getMaxStackSize()) > Setting.MAX_ITEMS_PER_TRADE_SIDE.getInt()) { - Message.TOO_MANY_ITEMS.sendMessage(pSender, new Tuple<>(Variable.SIDE.toString(), "cost")); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.SET_COST, new ObjectHolder(costItem)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - shop.setCost(costItem); - - Message.ITEM_ADDED.sendMessage(pSender); - } - - /** - * Adds a cost to a Shop - *

- * With no variables sent will use the amount and data of the held item for cost - *

- *

- * If the player uses a int in the first variable they can change the amount for the item they are holding - *

- *

- * With 2 variables used the player can use an amount and material to set the sign instead of a held item - *

- */ - public void addCost() { - Shop shop = findShop(); - - if (shop == null) - return; - - int amount = 0; - Material mat = null; - - if (command.hasArgAt(1) && isInt(command.getArgAt(1))) { - amount = Integer.parseInt(command.getArgAt(1)); - } - - if (command.hasArgAt(2) && Material.getMaterial(command.getArgAt(2).toUpperCase()) != null) { - mat = Material.getMaterial(command.getArgAt(2).toUpperCase()); - } - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - ItemStack itemInHand; - - if (mat == null) { - itemInHand = pSender.getInventory().getItemInMainHand().clone(); - } else { - itemInHand = new ItemStack(mat, 1); - } - - if (itemInHand.getType() == Material.AIR) { - Message.HELD_EMPTY.sendMessage(pSender); - return; - } - - if (isIllegal(IllegalItemList.TradeItemType.COST, itemInHand.getType())) { - Message.ILLEGAL_ITEM.sendMessage(pSender); - return; - } - - if (!(shop.getShopType().isITrade() && shop.getInventoryLocation() == null) && itemInHand.getType().toString().endsWith("SHULKER_BOX") && shop.getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")) { - Message.NO_SHULKER_COST.sendMessage(pSender); - return; - } - - if (amount > 0) { - itemInHand.setAmount(amount); - } - - if (shop.getCost().size() + Math.ceil((double) itemInHand.getAmount() / (double) itemInHand.getMaxStackSize()) > Setting.MAX_ITEMS_PER_TRADE_SIDE.getInt()) { - Message.TOO_MANY_ITEMS.sendMessage(pSender, new Tuple<>(Variable.SIDE.toString(), "cost")); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.ADD_COST, new ObjectHolder(itemInHand)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - shop.addCost(itemInHand); - - Message.ITEM_ADDED.sendMessage(pSender); - } - - /** - * Sets the shop to the open status allowing trades to happen - */ - public void open() { - Shop shop = findShop(); - - if (shop == null) - return; - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) || - shop.getManagersUUID().contains(pSender.getUniqueId()) || - Permissions.isAdminEnabled(pSender))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - PlayerShopOpenEvent event = new PlayerShopOpenEvent(pSender, shop); - if (event.isCancelled()) return; - - ShopStatus status = shop.setOpen(); - - switch (status) { - case OPEN: - Message.CHANGE_OPEN.sendMessage(pSender); - break; - case INCOMPLETE: - if (shop.isMissingItems()) - Message.MISSING_ITEM.sendMessage(pSender); - else if (shop.getChestAsSC() == null) - Message.MISSING_CHEST.sendMessage(pSender); - break; - case OUT_OF_STOCK: - Message.SHOP_EMPTY.sendMessage(pSender); - break; - } - } - - /** - * Sets the shop to the close status preventing trades from happen - */ - public void close() { - Shop shop = findShop(); - - if (shop == null) - return; - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) || - shop.getManagersUUID().contains(pSender.getUniqueId()) || - Permissions.isAdminEnabled(pSender))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - PlayerShopCloseEvent event = new PlayerShopCloseEvent(pSender, shop); - if (event.isCancelled()) return; - - shop.setStatus(ShopStatus.CLOSED); - shop.updateSign(); - shop.saveShop(); - - Message.CHANGE_CLOSED.sendMessage(pSender); - } - - /** - * Switches the shop type between BiTrade and Trade - */ - public void switchShop() { - Shop shop = findShop(); - - if (shop == null) - return; - - if (!Permissions.hasPermission(pSender, Permissions.EDIT)) { - Message.NO_COMMAND_PERMISSION.sendMessage(pSender); - return; - } - - switch (shop.getShopType()) { - case TRADE: - if (!Permissions.hasPermission(pSender, Permissions.CREATEBI)) { - Message.NO_COMMAND_PERMISSION.sendMessage(pSender); - return; - } - case BITRADE: - if (!Permissions.hasPermission(pSender, Permissions.CREATE)) { - Message.NO_COMMAND_PERMISSION.sendMessage(pSender); - return; - } - } - - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - shop.switchType(); - - Message.SHOP_TYPE_SWITCHED.sendMessage(pSender, new Tuple<>(Variable.NEW_TYPE.toString(), shop.getShopType().toHeader())); - } - - /** - * Tells the player who the Owner/Managers/Members that are on the shop are - */ - public void who() { - String owner = ""; - StringBuilder managers = new StringBuilder(); - StringBuilder members = new StringBuilder(); - Shop shop = findShop(); - - if (shop == null) - return; - - if (shop.getShopType().isITrade()) { - Message.WHO_MESSAGE.sendMessage(pSender, - new Tuple<>(Variable.OWNER.toString(), Setting.ITRADESHOP_OWNER.getString()), - new Tuple<>(Variable.MANAGERS.toString(), "None"), - new Tuple<>(Variable.MEMBERS.toString(), "None")); - return; - } - - if (shop.getOwner() != null) - owner = shop.getOwner().getName(); - - if (shop.getManagers().size() > 0) { - for (ShopUser usr : shop.getManagers()) { - if (managers.toString().equals("")) - managers = new StringBuilder(usr.getName()); - else - managers.append(", ").append(usr.getName()); - } - } - - if (shop.getMembers().size() > 0) { - for (ShopUser usr : shop.getMembers()) { - if (members.toString().equals("")) - members = new StringBuilder(usr.getName()); - else - members.append(", ").append(usr.getName()); - } - } - - if (managers.toString().equals("")) { - managers = new StringBuilder("None"); - } - if (members.toString().equals("")) { - members = new StringBuilder("None"); - } - Message.WHO_MESSAGE.sendMessage(pSender, - new Tuple<>(Variable.OWNER.toString(), owner), - new Tuple<>(Variable.MANAGERS.toString(), managers.toString()), - new Tuple<>(Variable.MEMBERS.toString(), members.toString())); - } - - /** - * Adds the specified player to the shop as a manager - */ - public void addManager() { - Shop shop = findShop(); - - if (shop == null) - return; - - if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); - if (!target.hasPlayedBefore()) { - Message.PLAYER_NOT_FOUND.sendMessage(pSender); - return; - } - - if (shop.getUsersUUID().contains(target.getUniqueId())) { - Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.ADD_MANAGER, new ObjectHolder(target)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - shop.addManager(target.getUniqueId()); - - Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); - } - - /** - * Removes the specified player from the shop if they currently are a manager - */ - public void removeUser() { - Shop shop = findShop(); - - if (shop == null) - return; - - if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); - if (!target.hasPlayedBefore()) { - Message.PLAYER_NOT_FOUND.sendMessage(pSender); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.REMOVE_USER, new ObjectHolder(target)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - if (!shop.removeUser(target.getUniqueId())) { - Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); - return; - } - - Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); - } - - /** - * Adds the specified player to the shop as a member - */ - public void addMember() { - Shop shop = findShop(); - - if (shop == null) - return; - - if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); - if (!target.hasPlayedBefore()) { - Message.PLAYER_NOT_FOUND.sendMessage(pSender); - return; - } - - - if (shop.getUsersUUID().contains(target.getUniqueId())) { - Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); - return; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.ADD_MEMBER, new ObjectHolder(target)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - shop.addMember(target.getUniqueId()); - - Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); - } - - /** - * Changes the players trade multiplier for current login - */ - public void multi() { - if (!Setting.ALLOW_MULTI_TRADE.getBoolean()) { - Message.FEATURE_DISABLED.sendMessage(pSender); - return; - } - - PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); - - if (command.argsSize() == 1) { - Message.MULTI_AMOUNT.sendMessage(pSender, new Tuple<>(Variable.AMOUNT.toString(), String.valueOf(playerSetting.getMulti()))); - } else { - int amount = Setting.MULTI_TRADE_DEFAULT.getInt(); - - if (isInt(command.getArgAt(1))) - amount = Integer.parseInt(command.getArgAt(1)); - - if (amount < 2) - amount = 2; - else if (amount > Setting.MULTI_TRADE_MAX.getInt()) - amount = Setting.MULTI_TRADE_MAX.getInt(); - - playerSetting.setMulti(amount); - plugin.getDataStorage().savePlayer(playerSetting); - - Message.MULTI_UPDATE.sendMessage(pSender, new Tuple<>(Variable.AMOUNT.toString(), String.valueOf(amount))); - } - } - - /** - * Changes the players with the ADMIN permission to toggle whether it is enabled for them - */ - public void toggleAdmin() { - PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); - - playerSetting.setAdminEnabled(!playerSetting.isAdminEnabled()); - plugin.getDataStorage().savePlayer(playerSetting); - - Message.ADMIN_TOGGLED.sendMessage(pSender, new Tuple<>(Variable.STATE.toString(), playerSetting.isAdminEnabled() ? "enabled" : "disabled")); - } - - /** - * Shows players their current admin mode or changes with optional variable - */ - public void admin() { - PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); - boolean initialValue = playerSetting.isAdminEnabled(); - - if (command.hasArgAt(1)) { - - switch (command.getArgAt(1).toLowerCase()) { - case "true": - case "t": - playerSetting.setAdminEnabled(true); - break; - case "false": - case "f": - playerSetting.setAdminEnabled(false); - break; - } - - if (initialValue != playerSetting.isAdminEnabled()) - plugin.getDataStorage().savePlayer(playerSetting); - } - - Message.ADMIN_TOGGLED.sendMessage(pSender, new Tuple<>(Variable.STATE.toString(), playerSetting.isAdminEnabled() ? "enabled" : "disabled")); - } - - /** - * Toggles the join status message for the player - */ - public void toggleStatus() { - if (!Setting.ALLOW_TOGGLE_STATUS.getBoolean()) { - Message.FEATURE_DISABLED.sendMessage(pSender); - return; - } - - PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); - playerSetting.setShowInvolvedStatus(!playerSetting.showInvolvedStatus()); - plugin.getDataStorage().savePlayer(playerSetting); - Message.TOGGLED_STATUS.sendMessage(pSender, new Tuple<>(Variable.STATUS.toString(), playerSetting.showInvolvedStatus() ? "on" : "off")); - } - - /** - * Create a regular shop from a sign in front of the player - */ - public void createTrade() { - Sign sign = findSign(); - - if (sign == null) - return; - - createShop(sign, ShopType.TRADE); - } - - /** - * Create a BiTrade shop from a sign in front of the player - */ - public void createBiTrade() { - Sign sign = findSign(); - - if (sign == null) - return; - - createShop(sign, ShopType.BITRADE); - } - - /** - * Create a iTrade shop from a sign in front of the player - */ - public void createITrade() { - Sign sign = findSign(); - - if (sign == null) - return; - - createShop(sign, ShopType.ITRADE); - } - - - /** - * Create a shop from a non-shop sign in front of the player - * - * @param shopSign sign to make into a shop - * @param shopType type of shop to make - */ - private void createShop(Sign shopSign, ShopType shopType) { - if (ShopType.isShop(shopSign)) { - Message.EXISTING_SHOP.sendMessage(pSender); - return; - } - - ShopUser owner = new ShopUser(pSender, ShopRole.OWNER); - - if (!checkShopChest(shopSign.getBlock()) && !shopType.isITrade()) { - Message.NO_CHEST.sendMessage(pSender); - return; - } - - if (Setting.MAX_SHOPS_PER_CHUNK.getInt() <= plugin.getDataStorage().getShopCountInChunk(shopSign.getChunk())) { - Message.TOO_MANY_CHESTS.sendMessage(pSender); - return; - } - - ShopChest shopChest; - Shop shop; - Block chest = findShopChest(shopSign.getBlock()); - - if (!shopType.isITrade()) { - if (ShopChest.isShopChest(chest)) { - shopChest = new ShopChest(chest.getLocation()); - } else { - shopChest = new ShopChest(chest, pSender.getUniqueId(), shopSign.getLocation()); - } - - if (shopChest.hasOwner() && !shopChest.getOwner().equals(owner.getUUID())) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - if (shopChest.hasShopSign() && !shopChest.getShopSign().getLocation().equals(shopSign.getLocation())) { - Message.EXISTING_SHOP.sendMessage(pSender); - return; - } - - shop = new Shop(new Tuple<>(shopSign.getLocation(), shopChest.getChest().getLocation()), shopType, owner); - shopChest.setName(); - - - if (shopChest.isEmpty() && shop.hasProduct()) { - Message.EMPTY_TS_ON_SETUP.sendMessage(pSender); - } - } else { - shop = new Shop(shopSign.getLocation(), shopType, owner); - } - - PlayerShopCreateEvent shopCreateEvent = new PlayerShopCreateEvent(pSender, shop); - Bukkit.getPluginManager().callEvent(shopCreateEvent); - if (shopCreateEvent.isCancelled()) { - return; - } - - shopSign.setLine(0, shopType.toHeader()); - shopSign.update(); - - shop.saveShop(); - - Message.SUCCESSFUL_SETUP.sendMessage(pSender); - } - - /** - * Changes/Sets the players permission level if internal permissions is enabled - */ - public void playerLevel() { - if (Bukkit.getOfflinePlayer(command.getArgAt(1)).hasPlayedBefore()) { - PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(Bukkit.getOfflinePlayer(command.getArgAt(1)).getUniqueId()); - if (command.argsSize() == 2) { - Message.VIEW_PLAYER_LEVEL.sendMessage(pSender, - new Tuple<>(Variable.PLAYER.toString(), Bukkit.getOfflinePlayer(command.getArgAt(1)).getName()), - new Tuple<>(Variable.LEVEL.toString(), playerSetting.getType() + "")); - } else { - if (isInt(command.getArgAt(2))) { - int newLevel = Integer.parseInt(command.getArgAt(2)); - - playerSetting.setType(newLevel); - plugin.getDataStorage().savePlayer(playerSetting); - - Message.SET_PLAYER_LEVEL.sendMessage(pSender, - new Tuple<>(Variable.PLAYER.toString(), Bukkit.getOfflinePlayer(command.getArgAt(1)).getName()), - new Tuple<>(Variable.LEVEL.toString(), playerSetting.getType() + "")); - } else { - Message.INVALID_ARGUMENTS.sendMessage(pSender); - } - } - } else { - Message.PLAYER_NOT_FOUND.sendMessage(pSender); - } - } - - /** - * Shows the player the status of all shops they are involved with or the specified player is involved with - */ - public void status() { - if (command.hasArgAt(1)) { - if (!Permissions.isAdminEnabled(pSender)) { - Message.NO_COMMAND_PERMISSION.sendMessage(pSender); - return; - } - if (Bukkit.getOfflinePlayer(command.getArgAt(1)).hasPlayedBefore()) { - plugin.getDataStorage().loadPlayer(Bukkit.getOfflinePlayer(command.getArgAt(1)).getUniqueId()) - .getInvolvedStatusesInventory().show(pSender.getPlayer()); - } else { - Message.PLAYER_NOT_FOUND.sendMessage(pSender); - } - } else { - plugin.getDataStorage().loadPlayer(pSender.getUniqueId()).getInvolvedStatusesInventory().show(pSender.getPlayer()); - } - } - - /** - * Returns the Shop the player is looking at - * - * @return null if Shop is not found, Shop object if it is - */ - protected Shop findShop() { - if (pSender == null) { - Message.PLAYER_ONLY_COMMAND.sendMessage(pSender); - return null; - } - - Block b = pSender.getTargetBlockExact(Setting.MAX_EDIT_DISTANCE.getInt()); - try { - if (b == null) - throw new NoSuchFieldException(); - - if (ShopType.isShop(b)) { - return Shop.loadShop((Sign) b.getState()); - - } else if (ShopChest.isShopChest(b)) { - if (plugin.getDataStorage().getChestLinkage(new ShopLocation(b.getLocation())) != null) - return plugin.getDataStorage().loadShopFromStorage(new ShopLocation(b.getLocation())); - - return Shop.loadShop(new ShopChest(b.getLocation()).getShopSign()); - - } else - throw new NoSuchFieldException(); - - } catch (NoSuchFieldException ex) { - Message.NO_SIGHTED_SHOP.sendMessage(pSender); - return null; - } - } - - /** - * Returns the Sign the player is looking at - * - * @return null if Sign is not found, Sign object if it is - */ - protected Sign findSign() { - if (pSender == null) { - Message.PLAYER_ONLY_COMMAND.sendMessage(pSender); - return null; - } - - Block b = pSender.getTargetBlockExact(Setting.MAX_EDIT_DISTANCE.getInt()); - try { - if (b == null) - throw new NoSuchFieldException(); - - if (plugin.getSigns().getSignTypes().contains(b.getType())) { - return (Sign) b.getState(); - - } else - throw new NoSuchFieldException(); - - } catch (NoSuchFieldException ex) { - Message.NO_SIGN_FOUND.sendMessage(pSender); - return null; - } - } -} \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java new file mode 100644 index 00000000..106b396a --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java @@ -0,0 +1,140 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import org.bukkit.Bukkit; +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.config.Variable; +import org.shanerx.tradeshop.data.storage.DataType; +import org.shanerx.tradeshop.framework.events.TradeShopReloadEvent; +import org.shanerx.tradeshop.player.PlayerSetting; +import org.shanerx.tradeshop.utils.debug.DebugLevels; +import org.shanerx.tradeshop.utils.objects.Tuple; + +/** + * Implementation of CommandRunner for commands that are used for administration purposes + * + * @since 2.6.0 + */ +public class AdminCommand extends CommandRunner { + + public AdminCommand(TradeShop instance, CommandPass command) { + super(instance, command); + } + + /** + * Reloads the plugin and sends success message + */ + public void reload() { + plugin.getLanguage().reload(); + plugin.getSettingManager().reload(); + plugin.getMessageManager().reload(); + plugin.getListManager().reload(); + plugin.getDebugger().reload(); + try { + plugin.getDataStorage().reload(DataType.valueOf(Setting.DATA_STORAGE_TYPE.getString().toUpperCase())); + } catch (IllegalArgumentException iae) { + debugger.log("Config value for data storage set to an invalid value: " + Setting.DATA_STORAGE_TYPE.getString(), DebugLevels.DATA_ERROR); + debugger.log("TradeShop will now disable...", DebugLevels.DATA_ERROR); + plugin.getServer().getPluginManager().disablePlugin(plugin); + return; + } + + command.sendMessage(Setting.MESSAGE_PREFIX.getString() + "&6The configuration files have been reloaded!"); + Bukkit.getPluginManager().callEvent(new TradeShopReloadEvent(plugin, command.getSender())); + } + + /** + * Changes the players with the ADMIN permission to toggle whether it is enabled for them + */ + public void toggleAdmin() { + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); + + playerSetting.setAdminEnabled(!playerSetting.isAdminEnabled()); + plugin.getDataStorage().savePlayer(playerSetting); + + Message.ADMIN_TOGGLED.sendMessage(pSender, new Tuple<>(Variable.STATE.toString(), playerSetting.isAdminEnabled() ? "enabled" : "disabled")); + } + + /** + * Shows players their current admin mode or changes with optional variable + */ + public void admin() { + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); + boolean initialValue = playerSetting.isAdminEnabled(); + + if (command.hasArgAt(1)) { + + switch (command.getArgAt(1).toLowerCase()) { + case "true": + case "t": + playerSetting.setAdminEnabled(true); + break; + case "false": + case "f": + playerSetting.setAdminEnabled(false); + break; + } + + if (initialValue != playerSetting.isAdminEnabled()) + plugin.getDataStorage().savePlayer(playerSetting); + } + + Message.ADMIN_TOGGLED.sendMessage(pSender, new Tuple<>(Variable.STATE.toString(), playerSetting.isAdminEnabled() ? "enabled" : "disabled")); + } + + /** + * Changes/Sets the players permission level if internal permissions is enabled + */ + public void playerLevel() { + if (Bukkit.getOfflinePlayer(command.getArgAt(1)).hasPlayedBefore()) { + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(Bukkit.getOfflinePlayer(command.getArgAt(1)).getUniqueId()); + if (command.argsSize() == 2) { + Message.VIEW_PLAYER_LEVEL.sendMessage(pSender, + new Tuple<>(Variable.PLAYER.toString(), Bukkit.getOfflinePlayer(command.getArgAt(1)).getName()), + new Tuple<>(Variable.LEVEL.toString(), playerSetting.getType() + "")); + } else { + if (isInt(command.getArgAt(2))) { + int newLevel = Integer.parseInt(command.getArgAt(2)); + + playerSetting.setType(newLevel); + plugin.getDataStorage().savePlayer(playerSetting); + + Message.SET_PLAYER_LEVEL.sendMessage(pSender, + new Tuple<>(Variable.PLAYER.toString(), Bukkit.getOfflinePlayer(command.getArgAt(1)).getName()), + new Tuple<>(Variable.LEVEL.toString(), playerSetting.getType() + "")); + } else { + Message.INVALID_ARGUMENTS.sendMessage(pSender); + } + } + } else { + Message.PLAYER_NOT_FOUND.sendMessage(pSender); + } + } +} diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/BasicTextCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/BasicTextCommand.java new file mode 100644 index 00000000..4f4379be --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/BasicTextCommand.java @@ -0,0 +1,103 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.commands.Commands; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.config.Variable; +import org.shanerx.tradeshop.player.PermStatus; +import org.shanerx.tradeshop.utils.objects.Tuple; + +/** + * Implementation of CommandRunner for plugin commands that return basic text/info to the user + * + * @since 2.6.0 + */ +public class BasicTextCommand extends CommandRunner { + + public BasicTextCommand(TradeShop instance, CommandPass command) { + super(instance, command); + } + + /** + * Builds and sends the sender the help message + */ + public void help() { + if (command.argsSize() == 2) { + usage(command.getArgAt(1)); + return; + } + + StringBuilder sb = new StringBuilder(); + + sb.append("\n&2") + .append(getPluginName()) + .append(" ") + .append(getVersion()) + .append(" by ").append(pdf.getAuthors().get(0)).append(" & ").append(pdf.getAuthors().get(1)) + .append("\n\n&b/tradeshop &f &f Display help message\n"); + + for (Commands c : Commands.values()) { + if (c.checkPerm(command.getSender()) == PermStatus.GOOD) { + sb.append(plugin.getMessageManager().colour(String.format("&b/ts %s &f %s\n", c.getFirstName(), c.getDescription()))); + } + } + + sb.append("\n "); + command.sendMessage(colorize(sb.toString())); + } + + /** + * Retrieves and sends usage string to player for requested sub-command or error message if command cannot be found + * + * @param subcmd string we should search for a sub-command + */ + public void usage(String subcmd) { + Commands cmd = Commands.getType(subcmd); + if (cmd == null) { + command.sendMessage(plugin.getMessageManager().colour(String.format("&4Cannot find usages for &c%s&r", subcmd))); + return; + } + command.sendMessage(plugin.getMessageManager().colour(String.format("&6Showing help for &c%s&r\n&bUsage:&e %s \n&bAliases: %s\n&bDescription:&e %s", subcmd, cmd.getUsage(), cmd.getAliases(), cmd.getDescription()))); + } + + /** + * Sends the sender the bug message + */ + public void bugs() { + command.sendMessage("\n&a[&eTradeShop&a] \n&2To report any bugs to the author, either send a PM on &cSpigot &2- &egoo.gl/s6Jk23 &2or open an issue on &cGitHub &2-&e goo.gl/X4qqyg\n"); + } + + /** + * Sends the sender the setup message + */ + public void setup() { + Message.SETUP_HELP.sendMessage(pSender, new Tuple<>(Variable.HEADER.toString(), Setting.TRADESHOP_HEADER.getString())); + } +} diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CommandRunner.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CommandRunner.java new file mode 100644 index 00000000..dc4d2926 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CommandRunner.java @@ -0,0 +1,96 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.entity.Player; +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopChest; +import org.shanerx.tradeshop.shop.ShopType; +import org.shanerx.tradeshop.shoplocation.ShopLocation; +import org.shanerx.tradeshop.utils.Utils; + +public class CommandRunner extends Utils { + + protected final TradeShop plugin; + protected final CommandPass command; + protected Player pSender; + + public CommandRunner(TradeShop instance, CommandPass command) { + this.plugin = instance; + this.command = command; + + if (command.getSender() instanceof Player) { + pSender = (Player) command.getSender(); + } + } + + + //region Util Methods + //------------------------------------------------------------------------------------------------------------------ + + /** + * Returns the Shop the player is looking at + * + * @return null if Shop is not found, Shop object if it is + */ + protected Shop findShop() { + if (pSender == null) { + Message.PLAYER_ONLY_COMMAND.sendMessage(pSender); + return null; + } + + Block b = pSender.getTargetBlockExact(Setting.MAX_EDIT_DISTANCE.getInt()); + try { + if (b == null) + throw new NoSuchFieldException(); + + if (ShopType.isShop(b)) { + return Shop.loadShop((Sign) b.getState()); + + } else if (ShopChest.isShopChest(b)) { + if (plugin.getDataStorage().getChestLinkage(new ShopLocation(b.getLocation())) != null) + return plugin.getDataStorage().loadShopFromStorage(new ShopLocation(b.getLocation())); + + return Shop.loadShop(new ShopChest(b.getLocation()).getShopSign()); + + } else + throw new NoSuchFieldException(); + + } catch (NoSuchFieldException ex) { + Message.NO_SIGHTED_SHOP.sendMessage(pSender); + return null; + } + } + + //------------------------------------------------------------------------------------------------------------------ + //endregion +} \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CreateCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CreateCommand.java new file mode 100644 index 00000000..3572750c --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CreateCommand.java @@ -0,0 +1,196 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import org.bukkit.Bukkit; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.framework.events.PlayerShopCreateEvent; +import org.shanerx.tradeshop.item.ShopItemSide; +import org.shanerx.tradeshop.player.ShopRole; +import org.shanerx.tradeshop.player.ShopUser; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopChest; +import org.shanerx.tradeshop.shop.ShopType; +import org.shanerx.tradeshop.utils.objects.Tuple; + +/** + * Implementation of CommandRunner for plugin commands that create new shops + * + * @since 2.6.0 + */ +public class CreateCommand extends CommandRunner { + + public CreateCommand(TradeShop instance, CommandPass command) { + super(instance, command); + } + + /** + * Create a regular shop from a sign in front of the player + */ + public void createTrade() { + Sign sign = findSign(); + + if (sign == null) + return; + + createShop(sign, ShopType.TRADE); + } + + /** + * Create a BiTrade shop from a sign in front of the player + */ + public void createBiTrade() { + Sign sign = findSign(); + + if (sign == null) + return; + + createShop(sign, ShopType.BITRADE); + } + + /** + * Create a iTrade shop from a sign in front of the player + */ + public void createITrade() { + Sign sign = findSign(); + + if (sign == null) + return; + + createShop(sign, ShopType.ITRADE); + } + + + /** + * Create a shop from a non-shop sign in front of the player + * + * @param shopSign sign to make into a shop + * @param shopType type of shop to make + */ + private void createShop(Sign shopSign, ShopType shopType) { + if (ShopType.isShop(shopSign)) { + Message.EXISTING_SHOP.sendMessage(pSender); + return; + } + + ShopUser owner = new ShopUser(pSender, ShopRole.OWNER); + + if (!checkShopChest(shopSign.getBlock()) && !shopType.isITrade()) { + Message.NO_CHEST.sendMessage(pSender); + return; + } + + if (Setting.MAX_SHOPS_PER_CHUNK.getInt() <= plugin.getDataStorage().getShopCountInChunk(shopSign.getChunk())) { + Message.TOO_MANY_CHESTS.sendMessage(pSender); + return; + } + + ShopChest shopChest; + Shop shop; + Block chest = findShopChest(shopSign.getBlock()); + + if (!shopType.isITrade()) { + if (ShopChest.isShopChest(chest)) { + shopChest = new ShopChest(chest.getLocation()); + } else { + shopChest = new ShopChest(chest, pSender.getUniqueId(), shopSign.getLocation()); + } + + if (shopChest.hasOwner() && !shopChest.getOwner().equals(owner.getUUID())) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + if (shopChest.hasShopSign() && !shopChest.getShopSign().getLocation().equals(shopSign.getLocation())) { + Message.EXISTING_SHOP.sendMessage(pSender); + return; + } + + shop = new Shop(new Tuple<>(shopSign.getLocation(), shopChest.getChest().getLocation()), shopType, owner); + shopChest.setName(); + + + if (shopChest.isEmpty() && shop.hasSide(ShopItemSide.PRODUCT)) { + Message.EMPTY_TS_ON_SETUP.sendMessage(pSender); + } + } else { + shop = new Shop(shopSign.getLocation(), shopType, owner); + } + + PlayerShopCreateEvent shopCreateEvent = new PlayerShopCreateEvent(pSender, shop); + Bukkit.getPluginManager().callEvent(shopCreateEvent); + if (shopCreateEvent.isCancelled()) { + return; + } + + shopSign.setLine(0, shopType.toHeader()); + shopSign.update(); + + shop.saveShop(); + + Message.SUCCESSFUL_SETUP.sendMessage(pSender); + } + + + //region Util Methods + //------------------------------------------------------------------------------------------------------------------ + + /** + * Returns the Sign the player is looking at + * + * @return null if Sign is not found, Sign object if it is + */ + protected Sign findSign() { + if (pSender == null) { + Message.PLAYER_ONLY_COMMAND.sendMessage(pSender); + return null; + } + + Block b = pSender.getTargetBlockExact(Setting.MAX_EDIT_DISTANCE.getInt()); + try { + if (b == null) + throw new NoSuchFieldException(); + + if (plugin.getSigns().getSignTypes().contains(b.getType())) { + return (Sign) b.getState(); + + } else + throw new NoSuchFieldException(); + + } catch (NoSuchFieldException ex) { + Message.NO_SIGN_FOUND.sendMessage(pSender); + return null; + } + } + + //------------------------------------------------------------------------------------------------------------------ + //endregion +} diff --git a/src/main/java/org/shanerx/tradeshop/commands/EditCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java similarity index 95% rename from src/main/java/org/shanerx/tradeshop/commands/EditCommand.java rename to src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java index cb6d32f9..e3b771e2 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/EditCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.commands; +package org.shanerx.tradeshop.commands.commandrunners; import com.google.common.collect.Iterables; import de.themoep.inventorygui.GuiElementGroup; @@ -37,7 +37,9 @@ import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.inventory.meta.ItemMeta; import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; import org.shanerx.tradeshop.player.Permissions; @@ -51,7 +53,12 @@ import java.util.List; import java.util.Set; -public class EditCommand extends CommandRunner { +/** + * Implementation of GUICommand for the `edit` command + * + * @since 2.3.0 + */ +public class EditCommand extends GUICommand { private Shop shop; private InventoryGui mainMenu, @@ -170,7 +177,7 @@ public void edit() { costEdit = new InventoryGui(plugin, "Edit Costs", EDIT_LAYOUT); costItems = new ArrayList<>(); costItemsRemoval = new ArrayList<>(); - for (ShopItemStack item : shop.getCost()) { + for (ShopItemStack item : shop.getSideList(ShopItemSide.COST)) { costItems.add(item.clone()); costItemsRemoval.add(false); } @@ -191,7 +198,7 @@ public void edit() { if (costItemsRemoval.get(i)) costItems.remove(i); } - shop.updateCost(costItems); + shop.updateSide(ShopItemSide.COST, costItems); InventoryGui.goBack(pSender); return true; }, "Save Changes")); @@ -211,7 +218,7 @@ public void edit() { productEdit = new InventoryGui(plugin, "Edit Products", EDIT_LAYOUT); productItems = new ArrayList<>(); productItemsRemoval = new ArrayList<>(); - for (ShopItemStack item : shop.getProduct()) { + for (ShopItemStack item : shop.getSideList(ShopItemSide.PRODUCT)) { productItems.add(item.clone()); productItemsRemoval.add(false); } @@ -232,7 +239,7 @@ public void edit() { if (productItemsRemoval.get(i)) productItems.remove(i); } - shop.updateProduct(productItems); + shop.updateSide(ShopItemSide.PRODUCT, productItems); InventoryGui.goBack(pSender); return true; }, "Save Changes")); @@ -251,6 +258,10 @@ public void edit() { mainMenu.show(pSender); } + + //region Util Methods + //------------------------------------------------------------------------------------------------------------------ + private StaticGuiElement shopItemEditMenu(int index, boolean isCost) { ShopItemStack item = (isCost ? costItems : productItems).get(index).clone(); ItemStack tempStack = item.getItemStack(); @@ -392,4 +403,7 @@ private GuiStateElement booleanOption(ShopItemStackSettingKeys setting, ShopItem "State: False" )); } + + //------------------------------------------------------------------------------------------------------------------ + //endregion } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java new file mode 100644 index 00000000..ac9d044b --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java @@ -0,0 +1,70 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import de.themoep.inventorygui.GuiPageElement; +import de.themoep.inventorygui.InventoryGui; +import de.themoep.inventorygui.StaticGuiElement; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; + +/** + * Implementation of CommandRunner for plugin commands that generate GUI screens + * + * @since 2.6.0 + */ +public class GUICommand extends CommandRunner { + + //region Util Variables + //------------------------------------------------------------------------------------------------------------------ + + protected final GuiPageElement PREV_BUTTON = new GuiPageElement('p', new ItemStack(Material.POTION), GuiPageElement.PageAction.PREVIOUS, "Go to previous page (%prevpage%)"), + NEXT_BUTTON = new GuiPageElement('n', new ItemStack(Material.SPLASH_POTION), GuiPageElement.PageAction.NEXT, "Go to next page (%nextpage%)"); + protected final StaticGuiElement CANCEL_BUTTON = new StaticGuiElement('c', new ItemStack(Material.END_CRYSTAL), click3 -> { + InventoryGui.goBack(pSender); + return true; + }, "Cancel Changes"), + BACK_BUTTON = new StaticGuiElement('b', new ItemStack(Material.END_CRYSTAL), click3 -> { + InventoryGui.goBack(pSender); + return true; + }, "Back"); + protected final String[] MENU_LAYOUT = {"a b c"}, + EDIT_LAYOUT = {"aggggggga", "ap c s na"}, + ITEM_LAYOUT = {"aggggggga", "aggggggga", "a cbs a"}, + WHAT_MENU = {"141125333", "1aaa2bbb3", "11p123n33"}; + + + //------------------------------------------------------------------------------------------------------------------ + //endregion + + public GUICommand(TradeShop instance, CommandPass command) { + super(instance, command); + } + + +} diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GeneralPlayerCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GeneralPlayerCommand.java new file mode 100644 index 00000000..16856700 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GeneralPlayerCommand.java @@ -0,0 +1,109 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import org.bukkit.Bukkit; +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.config.Variable; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.PlayerSetting; +import org.shanerx.tradeshop.utils.objects.Tuple; + +public class GeneralPlayerCommand extends CommandRunner { + + public GeneralPlayerCommand(TradeShop instance, CommandPass command) { + super(instance, command); + } + + /** + * Changes the players trade multiplier for current login + */ + public void multi() { + if (!Setting.ALLOW_MULTI_TRADE.getBoolean()) { + Message.FEATURE_DISABLED.sendMessage(pSender); + return; + } + + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); + + if (command.argsSize() == 1) { + Message.MULTI_AMOUNT.sendMessage(pSender, new Tuple<>(Variable.AMOUNT.toString(), String.valueOf(playerSetting.getMulti()))); + } else { + int amount = Setting.MULTI_TRADE_DEFAULT.getInt(); + + if (isInt(command.getArgAt(1))) + amount = Integer.parseInt(command.getArgAt(1)); + + if (amount < 2) + amount = 2; + else if (amount > Setting.MULTI_TRADE_MAX.getInt()) + amount = Setting.MULTI_TRADE_MAX.getInt(); + + playerSetting.setMulti(amount); + plugin.getDataStorage().savePlayer(playerSetting); + + Message.MULTI_UPDATE.sendMessage(pSender, new Tuple<>(Variable.AMOUNT.toString(), String.valueOf(amount))); + } + } + + /** + * Toggles the join status message for the player + */ + public void toggleStatus() { + if (!Setting.ALLOW_TOGGLE_STATUS.getBoolean()) { + Message.FEATURE_DISABLED.sendMessage(pSender); + return; + } + + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); + playerSetting.setShowInvolvedStatus(!playerSetting.showInvolvedStatus()); + plugin.getDataStorage().savePlayer(playerSetting); + Message.TOGGLED_STATUS.sendMessage(pSender, new Tuple<>(Variable.STATUS.toString(), playerSetting.showInvolvedStatus() ? "on" : "off")); + } + + /** + * Shows the player the status of all shops they are involved with or the specified player is involved with + */ + public void status() { + if (command.hasArgAt(1)) { + if (!Permissions.isAdminEnabled(pSender)) { + Message.NO_COMMAND_PERMISSION.sendMessage(pSender); + return; + } + if (Bukkit.getOfflinePlayer(command.getArgAt(1)).hasPlayedBefore()) { + plugin.getDataStorage().loadPlayer(Bukkit.getOfflinePlayer(command.getArgAt(1)).getUniqueId()) + .getInvolvedStatusesInventory().show(pSender.getPlayer()); + } else { + Message.PLAYER_NOT_FOUND.sendMessage(pSender); + } + } else { + plugin.getDataStorage().loadPlayer(pSender.getUniqueId()).getInvolvedStatusesInventory().show(pSender.getPlayer()); + } + } +} diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopCommand.java new file mode 100644 index 00000000..24031973 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopCommand.java @@ -0,0 +1,147 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.config.Variable; +import org.shanerx.tradeshop.framework.events.PlayerShopCloseEvent; +import org.shanerx.tradeshop.framework.events.PlayerShopOpenEvent; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopStatus; +import org.shanerx.tradeshop.utils.objects.Tuple; + +public class ShopCommand extends CommandRunner { + + public ShopCommand(TradeShop instance, CommandPass command) { + super(instance, command); + } + + /** + * Sets the shop to the open status allowing trades to happen + */ + public void open() { + Shop shop = findShop(); + + if (shop == null) + return; + + if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) || + shop.getManagersUUID().contains(pSender.getUniqueId()) || + Permissions.isAdminEnabled(pSender))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + PlayerShopOpenEvent event = new PlayerShopOpenEvent(pSender, shop); + if (event.isCancelled()) return; + + ShopStatus status = shop.setOpen(); + + switch (status) { + case OPEN: + Message.CHANGE_OPEN.sendMessage(pSender); + break; + case INCOMPLETE: + if (shop.isMissingItems()) + Message.MISSING_ITEM.sendMessage(pSender); + else if (shop.getChestAsSC() == null) + Message.MISSING_CHEST.sendMessage(pSender); + break; + case OUT_OF_STOCK: + Message.SHOP_EMPTY.sendMessage(pSender); + break; + } + } + + /** + * Sets the shop to the close status preventing trades from happen + */ + public void close() { + Shop shop = findShop(); + + if (shop == null) + return; + + if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) || + shop.getManagersUUID().contains(pSender.getUniqueId()) || + Permissions.isAdminEnabled(pSender))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + PlayerShopCloseEvent event = new PlayerShopCloseEvent(pSender, shop); + if (event.isCancelled()) return; + + shop.setStatus(ShopStatus.CLOSED); + shop.updateSign(); + shop.saveShop(); + + Message.CHANGE_CLOSED.sendMessage(pSender); + } + + /** + * Switches the shop type between BiTrade and Trade + */ + public void switchShop() { + Shop shop = findShop(); + + if (shop == null) + return; + + if (!Permissions.hasPermission(pSender, Permissions.EDIT)) { + Message.NO_COMMAND_PERMISSION.sendMessage(pSender); + return; + } + + switch (shop.getShopType()) { + case TRADE: + if (!Permissions.hasPermission(pSender, Permissions.CREATEBI)) { + Message.NO_COMMAND_PERMISSION.sendMessage(pSender); + return; + } + case BITRADE: + if (!Permissions.hasPermission(pSender, Permissions.CREATE)) { + Message.NO_COMMAND_PERMISSION.sendMessage(pSender); + return; + } + } + + if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) + || shop.getManagersUUID().contains(pSender.getUniqueId()) + || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + shop.switchType(); + + Message.SHOP_TYPE_SWITCHED.sendMessage(pSender, new Tuple<>(Variable.NEW_TYPE.toString(), shop.getShopType().toHeader())); + } +} diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java new file mode 100644 index 00000000..6a8cc0fc --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java @@ -0,0 +1,262 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.config.Variable; +import org.shanerx.tradeshop.framework.ShopChange; +import org.shanerx.tradeshop.framework.events.PlayerShopChangeEvent; +import org.shanerx.tradeshop.item.ShopItemSide; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; +import org.shanerx.tradeshop.utils.objects.Tuple; + +public class ShopItemCommand extends CommandRunner { + + ShopItemSide side; + + public ShopItemCommand(TradeShop instance, CommandPass command, ShopItemSide side) { + super(instance, command); + this.side = side; + } + + /** + * Lists items on a shops specified side with their index + */ + public void listSide() { + Shop shop = findShop(); + + if (shop == null) + return; + + StringBuilder sb = new StringBuilder(); + int counter = 1; + + for (ShopItemStack itm : shop.getSideList(side)) { + sb.append(String.format("&b[&f%d&b] &2- &f%s\n", counter, itm.getCleanItemName())); + counter++; + } + + Message.SHOP_ITEM_LIST.sendMessage(pSender, new Tuple<>(Variable.TYPE.toString(), side.toString().toLowerCase() + "s"), new Tuple<>(Variable.LIST.toString(), sb.toString())); + } + + /** + * Removes the item at index from the shops specified side + */ + public void removeSide() { + Shop shop = findShop(); + + if (shop == null) + return; + + int index = 0; + + if (isInt(command.getArgAt(1))) { + index = Integer.parseInt(command.getArgAt(1)) - 1; + } else { + Message.INVALID_ARGUMENTS.sendMessage(pSender); + return; + } + + if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) + || shop.getManagersUUID().contains(pSender.getUniqueId()) + || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.valueOf("REMOVE_" + side.toString()), new ObjectHolder(index)); + Bukkit.getPluginManager().callEvent(changeEvent); + if (changeEvent.isCancelled()) return; + + if (shop.removeSideIndex(side, index)) + Message.ITEM_REMOVED.sendMessage(pSender); + else + Message.ITEM_NOT_REMOVED.sendMessage(pSender); + } + + /** + * Sets the item for the specified side to a Shop + *

+ * With no variables sent, this will use the amount and data of the held item + *

+ *

+ * If the player uses a int in the first variable they can change the amount for the item they are holding + *

+ *

+ * With 2 variables used the player can use an amount and material to set the sign instead of a held item + *

+ */ + public void setSide() { + Shop shop = findShop(); + + if (shop == null) + return; + + int amount = 0; + Material mat = null; + + if (command.hasArgAt(1) && isInt(command.getArgAt(1))) { + amount = Integer.parseInt(command.getArgAt(1)); + } + + if (command.hasArgAt(2) && Material.getMaterial(command.getArgAt(2).toUpperCase()) != null) { + mat = Material.getMaterial(command.getArgAt(2).toUpperCase()); + } + + if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) + || shop.getManagersUUID().contains(pSender.getUniqueId()) + || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + ItemStack itemInHand; + + if (mat == null) { + itemInHand = pSender.getInventory().getItemInMainHand().clone(); + } else { + itemInHand = new ItemStack(mat, 1); + } + + if (itemInHand.getType() == Material.AIR) { + Message.HELD_EMPTY.sendMessage(pSender); + return; + } + + if (isIllegal(side, itemInHand.getType())) { + Message.ILLEGAL_ITEM.sendMessage(pSender); + return; + } + + if (!(shop.getShopType().isITrade() && shop.getInventoryLocation() == null) && itemInHand.getType().toString().endsWith("SHULKER_BOX") && shop.getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")) { + Message.NO_SHULKER_ITEM.sendMessage(pSender); + return; + } + + if (amount > 0) { + itemInHand.setAmount(amount); + } + + if (Math.ceil((double) itemInHand.getAmount() / (double) itemInHand.getMaxStackSize()) > Setting.MAX_ITEMS_PER_TRADE_SIDE.getInt()) { + Message.TOO_MANY_ITEMS.sendMessage(pSender, new Tuple<>(Variable.SIDE.toString(), side.toString().toLowerCase())); + return; + } + + PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.valueOf("SET_" + side.toString()), new ObjectHolder(itemInHand)); + Bukkit.getPluginManager().callEvent(changeEvent); + if (changeEvent.isCancelled()) return; + + shop.setSideItems(side, itemInHand); + + Message.ITEM_ADDED.sendMessage(pSender); + } + + /** + * Adds a item to the specified side of a Shop + *

+ * With no variables sent will use the amount and data of the held item + *

+ *

+ * If the player uses a int in the first variable they can change the amount for the item they are holding + *

+ *

+ * With 2 variables used the player can use an amount and material to set the sign instead of a held item + *

+ */ + public void addSide() { + Shop shop = findShop(); + + if (shop == null) + return; + + int amount = 0; + Material mat = null; + + if (command.hasArgAt(1) && isInt(command.getArgAt(1))) { + amount = Integer.parseInt(command.getArgAt(1)); + } + + if (command.hasArgAt(2) && Material.getMaterial(command.getArgAt(2).toUpperCase()) != null) { + mat = Material.getMaterial(command.getArgAt(2).toUpperCase()); + } + + if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) + || shop.getManagersUUID().contains(pSender.getUniqueId()) + || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + ItemStack itemInHand; + + if (mat == null) { + itemInHand = pSender.getInventory().getItemInMainHand().clone(); + } else { + itemInHand = new ItemStack(mat, 1); + } + + if (itemInHand.getType() == Material.AIR) { + Message.HELD_EMPTY.sendMessage(pSender); + return; + } + + if (isIllegal(side, itemInHand.getType())) { + Message.ILLEGAL_ITEM.sendMessage(pSender); + return; + } + + if (!(shop.getShopType().isITrade() && shop.getInventoryLocation() == null) && itemInHand.getType().toString().endsWith("SHULKER_BOX") && shop.getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")) { + Message.NO_SHULKER_ITEM.sendMessage(pSender); + return; + } + + if (amount > 0) { + itemInHand.setAmount(amount); + } + + if (shop.getSideList(side).size() + Math.ceil((double) itemInHand.getAmount() / (double) itemInHand.getMaxStackSize()) > Setting.MAX_ITEMS_PER_TRADE_SIDE.getInt()) { + Message.TOO_MANY_ITEMS.sendMessage(pSender, new Tuple<>(Variable.SIDE.toString(), side.toString().toLowerCase())); + return; + } + + PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.valueOf("ADD_" + side.toString()), new ObjectHolder(itemInHand)); + Bukkit.getPluginManager().callEvent(changeEvent); + if (changeEvent.isCancelled()) return; + + shop.addSideItem(side, itemInHand); + + Message.ITEM_ADDED.sendMessage(pSender); + } +} diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java new file mode 100644 index 00000000..764d34f6 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java @@ -0,0 +1,210 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.commands.commandrunners; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.data.config.Variable; +import org.shanerx.tradeshop.framework.ShopChange; +import org.shanerx.tradeshop.framework.events.PlayerShopChangeEvent; +import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.ShopUser; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; +import org.shanerx.tradeshop.utils.objects.Tuple; + +/** + * Implementation of CommandRunner for commands that view/change shop users + * + * @since 2.6.0 + */ +public class ShopUserCommand extends CommandRunner { + + public ShopUserCommand(TradeShop instance, CommandPass command) { + super(instance, command); + } + + /** + * Tells the player who the Owner/Managers/Members that are on the shop are + */ + public void who() { + String owner = ""; + StringBuilder managers = new StringBuilder(); + StringBuilder members = new StringBuilder(); + Shop shop = findShop(); + + if (shop == null) + return; + + if (shop.getShopType().isITrade()) { + Message.WHO_MESSAGE.sendMessage(pSender, + new Tuple<>(Variable.OWNER.toString(), Setting.ITRADESHOP_OWNER.getString()), + new Tuple<>(Variable.MANAGERS.toString(), "None"), + new Tuple<>(Variable.MEMBERS.toString(), "None")); + return; + } + + if (shop.getOwner() != null) + owner = shop.getOwner().getName(); + + if (shop.getManagers().size() > 0) { + for (ShopUser usr : shop.getManagers()) { + if (managers.toString().equals("")) + managers = new StringBuilder(usr.getName()); + else + managers.append(", ").append(usr.getName()); + } + } + + if (shop.getMembers().size() > 0) { + for (ShopUser usr : shop.getMembers()) { + if (members.toString().equals("")) + members = new StringBuilder(usr.getName()); + else + members.append(", ").append(usr.getName()); + } + } + + if (managers.toString().equals("")) { + managers = new StringBuilder("None"); + } + if (members.toString().equals("")) { + members = new StringBuilder("None"); + } + Message.WHO_MESSAGE.sendMessage(pSender, + new Tuple<>(Variable.OWNER.toString(), owner), + new Tuple<>(Variable.MANAGERS.toString(), managers.toString()), + new Tuple<>(Variable.MEMBERS.toString(), members.toString())); + } + + /** + * Adds the specified player to the shop as a manager + */ + public void addManager() { + Shop shop = findShop(); + + if (shop == null) + return; + + if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) + || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); + if (!target.hasPlayedBefore()) { + Message.PLAYER_NOT_FOUND.sendMessage(pSender); + return; + } + + if (shop.getUsersUUID().contains(target.getUniqueId())) { + Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); + return; + } + + PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.ADD_MANAGER, new ObjectHolder(target)); + Bukkit.getPluginManager().callEvent(changeEvent); + if (changeEvent.isCancelled()) return; + + shop.addManager(target.getUniqueId()); + + Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); + } + + /** + * Removes the specified player from the shop if they currently are a manager + */ + public void removeUser() { + Shop shop = findShop(); + + if (shop == null) + return; + + if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) + || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); + if (!target.hasPlayedBefore()) { + Message.PLAYER_NOT_FOUND.sendMessage(pSender); + return; + } + + PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.REMOVE_USER, new ObjectHolder(target)); + Bukkit.getPluginManager().callEvent(changeEvent); + if (changeEvent.isCancelled()) return; + + if (!shop.removeUser(target.getUniqueId())) { + Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); + return; + } + + Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); + } + + /** + * Adds the specified player to the shop as a member + */ + public void addMember() { + Shop shop = findShop(); + + if (shop == null) + return; + + if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) + || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + return; + } + + OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); + if (!target.hasPlayedBefore()) { + Message.PLAYER_NOT_FOUND.sendMessage(pSender); + return; + } + + + if (shop.getUsersUUID().contains(target.getUniqueId())) { + Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); + return; + } + + PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.ADD_MEMBER, new ObjectHolder(target)); + Bukkit.getPluginManager().callEvent(changeEvent); + if (changeEvent.isCancelled()) return; + + shop.addMember(target.getUniqueId()); + + Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); + } +} diff --git a/src/main/java/org/shanerx/tradeshop/commands/WhatCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java similarity index 92% rename from src/main/java/org/shanerx/tradeshop/commands/WhatCommand.java rename to src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java index 6cc2ec99..574a6913 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/WhatCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.commands; +package org.shanerx.tradeshop.commands.commandrunners; import de.themoep.inventorygui.GuiElementGroup; import de.themoep.inventorygui.InventoryGui; @@ -35,8 +35,10 @@ import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.commands.CommandPass; import org.shanerx.tradeshop.data.config.Message; import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; import org.shanerx.tradeshop.player.Permissions; @@ -46,7 +48,12 @@ import java.util.ArrayList; import java.util.List; -public class WhatCommand extends CommandRunner { +/** + * Implementation of GUICommand for the `what` command + * + * @since 2.3.0 + */ +public class WhatCommand extends GUICommand { public WhatCommand(TradeShop instance, CommandPass command) { super(instance, command); @@ -75,11 +82,11 @@ public void what() { gui.setFiller(new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1)); - for (ShopItemStack item : shop.getCost()) { + for (ShopItemStack item : shop.getSideList(ShopItemSide.COST)) { costGroup.addElement(shopitemViewMenu(item)); } - for (ShopItemStack item : shop.getProduct()) { + for (ShopItemStack item : shop.getSideList(ShopItemSide.PRODUCT)) { productGroup.addElement(shopitemViewMenu(item)); } @@ -101,6 +108,10 @@ public void what() { gui.show(pSender); } + + //region Util Methods + //------------------------------------------------------------------------------------------------------------------ + private ItemStack settingItem(boolean state) { return state ? new ItemStack(Material.EMERALD_BLOCK) : new ItemStack(Material.REDSTONE_BLOCK); } @@ -187,4 +198,7 @@ private StaticGuiElement shopitemViewMenu(ShopItemStack item) { return true; }); } + + //------------------------------------------------------------------------------------------------------------------ + //endregion } diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java index 2a6caedb..f22fbb06 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -55,7 +55,7 @@ public enum Message { FEATURE_DISABLED(MessageSection.NONE, "feature-disabled"), HELD_EMPTY(MessageSection.NONE, "held-empty"), ILLEGAL_ITEM(MessageSection.NONE, "illegal-item"), - NO_SHULKER_COST(MessageSection.NONE, "no-shulker-cost"), + NO_SHULKER_ITEM(MessageSection.NONE, "no-shulker-item"), INSUFFICIENT_ITEMS(MessageSection.NONE, "insufficient-items"), SHOP_INSUFFICIENT_ITEMS(MessageSection.NONE, "shop-insufficient-items"), INVALID_ARGUMENTS(MessageSection.NONE, "invalid-arguments"), diff --git a/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java b/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java index 55bc1a37..cb36fb4c 100644 --- a/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java +++ b/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java @@ -157,11 +157,4 @@ public enum ListType { DISABLED } - - public enum TradeItemType { - - COST, - PRODUCT - - } } diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemSide.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemSide.java new file mode 100644 index 00000000..1733d46b --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemSide.java @@ -0,0 +1,43 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.item; + +public enum ShopItemSide { + COST, + PRODUCT; + + private final ShopItemSide reverse; + + ShopItemSide() { + this.reverse = this; + } + + public ShopItemSide getReverse() { + return reverse.equals(COST) ? PRODUCT : COST; + } + + +} diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index fe151efe..b1555e83 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -38,7 +38,7 @@ import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.data.config.Setting; -import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.player.PlayerSetting; import org.shanerx.tradeshop.player.ShopRole; @@ -435,95 +435,6 @@ public void setShopType(ShopType newType) { shopType = newType; } - /** - * Sets the cost item - * - * @param newItem ItemStack to be set - */ - public void setCost(ItemStack newItem) { - if (utils.isIllegal(IllegalItemList.TradeItemType.COST, newItem.getType())) - return; - - cost.clear(); - - addCost(newItem); - } - - /** - * Adds more cost items - * - * @param newItem ItemStack to be added - */ - public void addCost(ItemStack newItem) { - if (utils.isIllegal(IllegalItemList.TradeItemType.COST, newItem.getType())) - return; - - ///* Added stacks are not separated and are added ontop of existing similar stacks - ShopItemStack toAddShopItemStack = new ShopItemStack(newItem); - int toRemoveShopItemStack = -1; - - - for (int i = 0; i < getCost().size(); i++) { - if (getCost().get(i).getItemStack().getType().equals(newItem.getType()) && getCost().get(i).isSimilar(newItem)) { - toRemoveShopItemStack = i; - toAddShopItemStack = getCost().get(i).clone(); - toAddShopItemStack.setAmount(getCost().get(i).getAmount() + newItem.getAmount()); - break; - } - } - - if (toRemoveShopItemStack > -1) - cost.remove(toRemoveShopItemStack); - - cost.add(toAddShopItemStack); - //*/ - - - if (!getShopType().isITrade() && chestLoc != null) - cost.removeIf(item -> item.getItemStack().getType().toString().endsWith("SHULKER_BOX") && getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")); - - saveShop(); - updateSign(); - } - - /** - * Removes the cost item at the index - * - * @param index index of item to remove - * - * @return true if Cost is removed - */ - public boolean removeCost(int index) { - try { - cost.remove(index); - - saveShop(); - updateSign(); - return true; - } catch (IndexOutOfBoundsException ex) { - return false; - } - } - - /** - * Checks if shop has product - * - * @return True if product != null - */ - public boolean hasProduct() { - return product.size() > 0; - } - - /** - * Checks if shop has cost - * - * @return True if cost != null - */ - public boolean hasCost() { - return cost.size() > 0; - } - - /** * Returns the amount of trades the shop could do when last accessed * @@ -533,120 +444,6 @@ public int getAvailableTrades() { return availableTrades; } - /** - * Adds more product items - * - * @param newItem ItemStack to be added - */ - public void addProduct(ItemStack newItem) { - if (utils.isIllegal(IllegalItemList.TradeItemType.PRODUCT, newItem.getType())) - return; - - ///* Added stacks are not separated and are added ontop of existing similar stacks - ShopItemStack toAddShopItemStack = new ShopItemStack(newItem); - int toRemoveShopItemStack = -1; - - - for (int i = 0; i < getProduct().size(); i++) { - if (getProduct().get(i).getItemStack().getType().equals(newItem.getType()) && getProduct().get(i).isSimilar(newItem)) { - toRemoveShopItemStack = i; - toAddShopItemStack = getProduct().get(i).clone(); - toAddShopItemStack.setAmount(getProduct().get(i).getAmount() + newItem.getAmount()); - break; - } - } - - if (toRemoveShopItemStack > -1) - product.remove(toRemoveShopItemStack); - - product.add(toAddShopItemStack); - //*/ - - saveShop(); - updateSign(); - } - - /** - * Returns the product items - * - * @return Product ShopItemStack List - */ - public List getProduct() { - List ret = new ArrayList<>(); - for (ShopItemStack itm : product) - ret.add(itm.clone()); - return ret; - } - - /** - * Returns the product items - * - * @return Product ItemStack List - */ - public List getProductItemStacks() { - List ret = new ArrayList<>(); - for (ShopItemStack itm : product) - ret.add(itm.getItemStack().clone()); - return ret; - } - - /** - * returns the cost item - * - * @return Cost ItemStack List - */ - public List getCost() { - List ret = new ArrayList<>(); - for (ShopItemStack itm : cost) - ret.add(itm.clone()); - return ret; - } - - /** - * Returns the cost items - * - * @return Cost ItemStack List - */ - public List getCostItemStacks() { - List ret = new ArrayList<>(); - for (ShopItemStack itm : cost) - ret.add(itm.getItemStack().clone()); - return ret; - } - - /** - * Sets the product item - * - * @param newItem item to be set to product - */ - public void setProduct(ItemStack newItem) { - if (utils.isIllegal(IllegalItemList.TradeItemType.PRODUCT, newItem.getType())) - return; - - product.clear(); - - addProduct(newItem); - } - - /** - * Removes the product item at the index - * - * @param index index of item to remove - * - * @return true if Product is removed - */ - public boolean removeProduct(int index) { - if (product.size() > index) { - product.remove(index); - - saveShop(); - updateSign(); - return true; - } - - return false; - } - /** * Serializes the object to Json using Gson * @@ -879,27 +676,13 @@ public ShopStatus setOpen() { return status; } - /** - * Checks if the shop has sufficient product stock to make a trade - */ - public boolean hasProductStock() { - return !shopType.isITrade() && hasProduct() && getChestAsSC() != null && getChestAsSC().hasStock(getProduct()); - } - - /** - * Checks if the shop has sufficient cost stock to make a trade(Use for BiTrade) - */ - public boolean hasCostStock() { - return !shopType.isITrade() && hasCost() && getChestAsSC() != null && getChestAsSC().hasStock(getCost()); - } - /** * Automatically updates a shops status if it is not CLOSED */ public void updateStatus() { if (!status.equals(ShopStatus.CLOSED)) { if (!isMissingItems() && (chestLoc != null || shopType.isITrade())) { - if (shopType.isITrade() || hasProductStock() || (shopType.isBiTrade() && hasCostStock())) + if (shopType.isITrade() || hasSideStock(ShopItemSide.PRODUCT) || (shopType.isBiTrade() && hasSideStock(ShopItemSide.COST))) setStatus(ShopStatus.OPEN); else setStatus(ShopStatus.OUT_OF_STOCK); @@ -998,62 +781,22 @@ public List getUserNames() { return users; } - /** - * Checks if all Costs in the list are valid for trade - * - * @return true if all costs are valid - */ - public boolean areCostsValid() { - return areItemsValid(IllegalItemList.TradeItemType.COST, cost); - } - - /** - * Checks if all Products in the list are valid for trade - * - * @return true if all products are valid - */ - public boolean areProductsValid() { - return areItemsValid(IllegalItemList.TradeItemType.PRODUCT, product); - } - /** * Checks if all Items in the list are valid for trade * - * @param tradeItemType Should Illegal Items be checked as Costs or Products - * @param items List to check + * @param side Which side of the trade should be checked for illegal items + * @param items List to check * @return true if all products are valid */ - private boolean areItemsValid(IllegalItemList.TradeItemType tradeItemType, List items) { + private boolean areItemsValid(ShopItemSide side, List items) { for (ShopItemStack iS : items) { - if (utils.isIllegal(tradeItemType, iS.getItemStack().getType())) + if (utils.isIllegal(side, iS.getItemStack().getType())) return false; } return true; } - /** - * Returns true if shop has enough product to make trade - * - * @param multiplier multiplier to use for check - * @return true if shop has enough product to make trade - */ - public Boolean checkProduct(int multiplier) { - setStorageInventory(); - return utils.checkInventory(storageInv, product, multiplier); - } - - /** - * Returns true if shop has enough cost to make trade - * - * @param multiplier multiplier to use for check - * @return true if shop has enough cost to make trade - */ - public Boolean checkCost(int multiplier) { - setStorageInventory(); - return utils.checkInventory(storageInv, cost, multiplier); - } - /** * Returns the ShopRole of the supplied UUID * @@ -1076,7 +819,7 @@ public ShopRole checkRole(UUID uuidToCheck) { * Updates the number of trades the shop can make */ public void updateFullTradeCount() { - if (!hasStorage() || !hasProduct()) { + if (!hasStorage() || !hasSide(ShopItemSide.PRODUCT)) { availableTrades = 0; return; } @@ -1087,7 +830,7 @@ public void updateFullTradeCount() { clone.setContents(shopInventory.getStorageContents()); int totalCount = 0, currentCount = 0; - for (ShopItemStack item : getProduct()) { + for (ShopItemStack item : getSideList(ShopItemSide.PRODUCT)) { totalCount += item.getItemStack().getAmount(); int traded; for (ItemStack storageItem : clone.getStorageContents()) { @@ -1124,27 +867,172 @@ public void updateShopUsers(Set updatedUserSet) { saveShop(); } + //region Item Management - Methods for adding/deleting/updating/viewing Cost and Product lists + //------------------------------------------------------------------------------------------------------------------ + /** - * Updates shops cost list + * Checks if shop has items on specified side * - * @param updatedCostList list to set as new CostList + * @return True if side != null + */ + public boolean hasSide(ShopItemSide side) { + return getSide(side).size() > 0; + } + + /** + * Returns the ItemStacks on specified side + * + * @param side Side to get ItemStacks form + * @return ItemStack List + */ + public List getSideItemStacks(ShopItemSide side) { + List ret = new ArrayList<>(); + for (ShopItemStack itm : getSide(side)) + ret.add(itm.getItemStack().clone()); + return ret; + } + + /** + * Returns the appropriate list for the side of the trade for object internal use + * + * @return Side ShopItemStack List + */ + private List getSide(ShopItemSide side) { + return side.equals(ShopItemSide.PRODUCT) ? product : cost; + } + + /** + * Returns a list of the items on the shops specified side + * + * @param side Side to get items for + * @return Side ShopItemStack List + */ + public List getSideList(ShopItemSide side) { + return getSideList(side, false); + } + + /** + * Returns a list of the items on the shops specified side, or the opposite side it doBiTradeAlternate is true + * + * @param side Side to get items for + * @param doBiTradeAlternate Should side be flipped(for biTrade + Left Click) + * @return Side ShopItemStack List */ - public void updateCost(List updatedCostList) { + public List getSideList(ShopItemSide side, boolean doBiTradeAlternate) { + List ret = new ArrayList<>(); + for (ShopItemStack itm : getSide(doBiTradeAlternate ? side.getReverse() : side)) + ret.add(itm.clone()); + return ret; + } + + /** + * Removes the item at the index of the specified side + * + * @param side side of the trade to remove item from + * @param index index of item to remove + * @return true if Item is removed from the specified Side + */ + public boolean removeSideIndex(ShopItemSide side, int index) { + if (getSide(side).size() > index) { + getSide(side).remove(index); + + saveShop(); + updateSign(); + return true; + } + + return false; + } + + /** + * Sets the Item for the specified side of the trade + * + * @param side Side of the trade to set + * @param newItem ItemStack to be set + */ + public void setSideItems(ShopItemSide side, ItemStack newItem) { + if (utils.isIllegal(side, newItem.getType())) + return; + + getSide(side).clear(); + + addSideItem(side, newItem); + } + + /** + * Adds more items to the specified side + * + * @param side Side to add items to + * @param newItem ItemStack to be added + */ + public void addSideItem(ShopItemSide side, ItemStack newItem) { + if (utils.isIllegal(side, newItem.getType())) + return; + + ///* Added stacks are not separated and are added ontop of existing similar stacks + ShopItemStack toAddShopItemStack = new ShopItemStack(newItem); + int toRemoveShopItemStack = -1; + + + for (int i = 0; i < getSide(side).size(); i++) { + if (getSideList(side).get(i).getItemStack().getType().equals(newItem.getType()) && getSideList(side).get(i).isSimilar(newItem)) { + toRemoveShopItemStack = i; + toAddShopItemStack = getSideList(side).get(i).clone(); + toAddShopItemStack.setAmount(getSideList(side).get(i).getAmount() + newItem.getAmount()); + break; + } + } + + if (toRemoveShopItemStack > -1) + getSide(side).remove(toRemoveShopItemStack); + + getSide(side).add(toAddShopItemStack); + //*/ + + if (!getShopType().isITrade() && chestLoc != null) - updatedCostList.removeIf(item -> item.getItemStack().getType().toString().endsWith("SHULKER_BOX") && getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")); - cost = updatedCostList; + getSide(side).removeIf(item -> item.getItemStack().getType().toString().endsWith("SHULKER_BOX") && getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")); + saveShop(); updateSign(); } /** - * Updates shops product list + * Checks if the shop has sufficient stock to make a trade on specified side + */ + public boolean hasSideStock(ShopItemSide side) { + return !shopType.isITrade() && hasSide(side) && getChestAsSC() != null && getChestAsSC().hasStock(getSideList(side)); + } + + /** + * Checks if all Items on the specified side are valid for trade + * + * @param side Side to check + * @return true if all Items are valid + */ + public boolean isSideValid(ShopItemSide side) { + return areItemsValid(side, getSideList(side)); + } + + /** + * Updates list on specified side * - * @param updatedProductList list to set as new ProductList + * @param side Side to be updated + * @param updatedCostList list to set as new CostList */ - public void updateProduct(List updatedProductList) { - product = updatedProductList; + public void updateSide(ShopItemSide side, List updatedCostList) { + if (!getShopType().isITrade() && chestLoc != null) + updatedCostList.removeIf(item -> item.getItemStack().getType().toString().endsWith("SHULKER_BOX") && getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")); + if (side.equals(ShopItemSide.PRODUCT)) { + product = updatedCostList; + } else { + cost = updatedCostList; + } + saveShop(); updateSign(); } + + //------------------------------------------------------------------------------------------------------------------ + //endregion } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java index 1af79caa..63623367 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java @@ -38,7 +38,7 @@ import org.shanerx.tradeshop.data.config.Message; import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.framework.events.PlayerShopCreateEvent; -import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.player.ShopUser; import org.shanerx.tradeshop.shop.Shop; @@ -110,7 +110,7 @@ public void onSignChange(SignChangeEvent event) { shopChest.setName(); - if (shopChest.isEmpty() && shop.hasProduct()) { + if (shopChest.isEmpty() && shop.hasSide(ShopItemSide.PRODUCT)) { p.sendMessage(Message.EMPTY_TS_ON_SETUP.getPrefixed()); } } else { @@ -119,14 +119,14 @@ public void onSignChange(SignChangeEvent event) { shop.setEvent(event); - ItemStack product = lineCheck(IllegalItemList.TradeItemType.PRODUCT, event.getLine(1)), - cost = lineCheck(IllegalItemList.TradeItemType.COST, event.getLine(2)); + ItemStack product = lineCheck(ShopItemSide.PRODUCT, event.getLine(1)), + cost = lineCheck(ShopItemSide.COST, event.getLine(2)); - if (product != null && shop.getProduct().isEmpty()) - shop.setProduct(product); + if (product != null && !shop.hasSide(ShopItemSide.PRODUCT)) + shop.setSideItems(ShopItemSide.PRODUCT, product); - if (cost != null && shop.getCost().isEmpty()) - shop.setCost(cost); + if (cost != null && !shop.hasSide(ShopItemSide.COST)) + shop.setSideItems(ShopItemSide.COST, cost); PlayerShopCreateEvent shopCreateEvent = new PlayerShopCreateEvent(p, shop); Bukkit.getPluginManager().callEvent(shopCreateEvent); @@ -142,7 +142,7 @@ public void onSignChange(SignChangeEvent event) { p.sendMessage(Message.SUCCESSFUL_SETUP.getPrefixed()); } - private ItemStack lineCheck(IllegalItemList.TradeItemType type, String line) { + private ItemStack lineCheck(ShopItemSide side, String line) { if (line == null || line.equalsIgnoreCase("") || !line.contains(" ") || line.split(" ").length != 2) return null; @@ -158,7 +158,7 @@ private ItemStack lineCheck(IllegalItemList.TradeItemType type, String line) { ItemStack item = new ItemStack(Material.matchMaterial(info[1]), Integer.parseInt(info[0])); - if (PLUGIN.getListManager().isIllegal(type, item.getType())) + if (PLUGIN.getListManager().isIllegal(side, item.getType())) return null; return item; diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java index 20e6dd34..d22acbf2 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java @@ -45,6 +45,7 @@ import org.shanerx.tradeshop.framework.events.PlayerPreTradeEvent; import org.shanerx.tradeshop.framework.events.PlayerPrepareTradeEvent; import org.shanerx.tradeshop.framework.events.PlayerSuccessfulTradeEvent; +import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.player.Permissions; import org.shanerx.tradeshop.shop.ExchangeStatus; import org.shanerx.tradeshop.shop.Shop; @@ -103,7 +104,7 @@ public void onBlockInteract(PlayerInteractEvent e) { return; } - PlayerPreTradeEvent preEvent = new PlayerPreTradeEvent(e.getPlayer(), shop.getCost(), shop.getProduct(), shop, e.getClickedBlock(), e.getBlockFace()); + PlayerPreTradeEvent preEvent = new PlayerPreTradeEvent(e.getPlayer(), shop.getSideList(ShopItemSide.COST), shop.getSideList(ShopItemSide.PRODUCT), shop, e.getClickedBlock(), e.getBlockFace()); Bukkit.getPluginManager().callEvent(preEvent); if (preEvent.isCancelled()) return; @@ -116,7 +117,7 @@ public void onBlockInteract(PlayerInteractEvent e) { return; } - if (!(shop.areProductsValid() && shop.areCostsValid())) { + if (!(shop.isSideValid(ShopItemSide.PRODUCT) && shop.isSideValid(ShopItemSide.COST))) { Message.ILLEGAL_ITEM.sendMessage(buyer); return; } @@ -138,14 +139,14 @@ public void onBlockInteract(PlayerInteractEvent e) { break; } - List searchResult = getItems(shop.getChestAsSC().getInventory().getStorageContents(), doBiTradeAlternate ? shop.getCost() : shop.getProduct(), multiplier); + List searchResult = getItems(shop.getChestAsSC().getInventory().getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT, doBiTradeAlternate), multiplier); Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, searchResult)); return; case OPEN: break; } - PlayerPrepareTradeEvent event = new PlayerPrepareTradeEvent(e.getPlayer(), shop.getCost(), shop.getProduct(), shop, e.getClickedBlock(), e.getBlockFace()); + PlayerPrepareTradeEvent event = new PlayerPrepareTradeEvent(e.getPlayer(), shop.getSideList(ShopItemSide.COST), shop.getSideList(ShopItemSide.PRODUCT), shop, e.getClickedBlock(), e.getBlockFace()); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) return; @@ -202,8 +203,8 @@ private Tuple, List> tradeAllItems(Shop shop, int mul if (shop.getShopType() == ShopType.ITRADE && action.equals(Action.RIGHT_CLICK_BLOCK)) { //ITrade trade - if (!shop.getCost().isEmpty()) { - costItems = getItems(playerInventory.getStorageContents(), shop.getCost(), multiplier); + if (shop.hasSide(ShopItemSide.COST)) { + costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); if (costItems.get(0) == null) { ItemStack item = costItems.get(1); Message.INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, costItems)); @@ -225,15 +226,15 @@ private Tuple, List> tradeAllItems(Shop shop, int mul costItems.add(noCostITradeItem); } - Inventory iTradeVirtualInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getProduct().size() / 9.0) * 9) * multiplier, 54)); + Inventory iTradeVirtualInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getSideList(ShopItemSide.PRODUCT).size() / 9.0) * 9) * multiplier, 54)); while (iTradeVirtualInventory.firstEmpty() != -1) { - for (ItemStack item : shop.getProductItemStacks()) { + for (ItemStack item : shop.getSideItemStacks(ShopItemSide.PRODUCT)) { item.setAmount(item.getMaxStackSize()); iTradeVirtualInventory.addItem(item); } } - productItems = getItems(iTradeVirtualInventory.getStorageContents(), shop.getProduct(), multiplier); + productItems = getItems(iTradeVirtualInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); for (ItemStack item : productItems) { playerInventory.addItem(item); @@ -245,7 +246,7 @@ private Tuple, List> tradeAllItems(Shop shop, int mul } else if (shop.getShopType() == ShopType.BITRADE && action == Action.LEFT_CLICK_BLOCK) { //BiTrade Reversed Trade //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getProduct(), multiplier); //Reverse BiTrade, Product is Cost + costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); //Reverse BiTrade, Product is Cost if (costItems.get(0) == null) { ItemStack item = costItems.get(1); Message.INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, costItems)); @@ -253,7 +254,7 @@ private Tuple, List> tradeAllItems(Shop shop, int mul } //Method to find Product items in shop inventory and add to product array - productItems = getItems(shopInventory.getStorageContents(), shop.getCost(), multiplier); //Reverse BiTrade, Cost is Product + productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); //Reverse BiTrade, Cost is Product if (productItems.get(0) == null) { ItemStack item = productItems.get(1); shop.updateStatus(); @@ -263,7 +264,7 @@ private Tuple, List> tradeAllItems(Shop shop, int mul } else if (action.equals(Action.RIGHT_CLICK_BLOCK)) { // Normal Trade //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getCost(), multiplier); + costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); if (costItems.get(0) == null) { ItemStack item = costItems.get(1); Message.INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, costItems)); @@ -271,7 +272,7 @@ private Tuple, List> tradeAllItems(Shop shop, int mul } //Method to find Product items in shop inventory and add to product array - productItems = getItems(shopInventory.getStorageContents(), shop.getProduct(), multiplier); + productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); if (productItems.get(0) == null) { ItemStack item = productItems.get(1); shop.updateStatus(); diff --git a/src/main/java/org/shanerx/tradeshop/utils/ListManager.java b/src/main/java/org/shanerx/tradeshop/utils/ListManager.java index 92c5c62e..30dc1840 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/ListManager.java +++ b/src/main/java/org/shanerx/tradeshop/utils/ListManager.java @@ -34,6 +34,7 @@ import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.item.IllegalItemList; import org.shanerx.tradeshop.item.NonObtainableMaterials; +import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.shop.ShopStorage; import org.shanerx.tradeshop.utils.debug.DebugLevels; @@ -104,14 +105,11 @@ public ArrayList getGameMats() { return gameMats; } - public boolean isIllegal(IllegalItemList.TradeItemType type, Material mat) { + public boolean isIllegal(ShopItemSide side, Material mat) { if (globalList.isIllegal(mat)) return true; - if (type.equals(IllegalItemList.TradeItemType.COST)) - return costList.isIllegal(mat); - else - return productList.isIllegal(mat); + return side.equals(ShopItemSide.COST) ? costList.isIllegal(mat) : productList.isIllegal(mat); } public boolean isDirection(BlockFace face) { diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 9496bcca..96f8f673 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -42,7 +42,7 @@ import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.data.config.Message; import org.shanerx.tradeshop.data.config.Setting; -import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.shop.ExchangeStatus; import org.shanerx.tradeshop.shop.Shop; @@ -240,12 +240,12 @@ public void failedTrade(PlayerInteractEvent e, Message msg) { /** * Checks whether or not it is an illegal material. * - * @param type What side of the trade the item is on + * @param side What side of the trade the item is on * @param mat String to check * @return returns true if valid material */ - public boolean isIllegal(IllegalItemList.TradeItemType type, Material mat) { - return PLUGIN.getListManager().isIllegal(type, mat); + public boolean isIllegal(ShopItemSide side, Material mat) { + return PLUGIN.getListManager().isIllegal(side, mat); } /** @@ -401,7 +401,7 @@ public Tuple> canExchangeAll(Shop shop, Inventor if (shop.getShopType() == ShopType.ITRADE) { //ITrade trade //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getCost(), multiplier); + costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); if (!costItems.isEmpty()) { if (costItems.get(0) == null) { @@ -413,15 +413,15 @@ public Tuple> canExchangeAll(Shop shop, Inventor } } - Inventory iTradeVirtualInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getProduct().size() / 9.0) * 9) * multiplier, 54)); + Inventory iTradeVirtualInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getSideList(ShopItemSide.PRODUCT).size() / 9.0) * 9) * multiplier, 54)); while (iTradeVirtualInventory.firstEmpty() != -1) { - for (ItemStack item : shop.getProductItemStacks()) { + for (ItemStack item : shop.getSideItemStacks(ShopItemSide.PRODUCT)) { item.setAmount(item.getMaxStackSize()); iTradeVirtualInventory.addItem(item); } } - productItems = getItems(iTradeVirtualInventory.getStorageContents(), shop.getProduct(), multiplier); + productItems = getItems(iTradeVirtualInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); for (ItemStack item : productItems) { if (!playerInventory.addItem(item).isEmpty()) { @@ -433,13 +433,13 @@ public Tuple> canExchangeAll(Shop shop, Inventor } else if (shop.getShopType() == ShopType.BITRADE && action == Action.LEFT_CLICK_BLOCK) { //BiTrade Reversed Trade //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getProduct(), multiplier); //Reverse BiTrade, Product is Cost + costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); //Reverse BiTrade, Product is Cost if (costItems.get(0) == null) { return new Tuple<>(ExchangeStatus.PLAYER_NO_COST, costItems); } //Method to find Product items in shop inventory and add to product array - productItems = getItems(shopInventory.getStorageContents(), shop.getCost(), multiplier); //Reverse BiTrade, Cost is Product + productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); //Reverse BiTrade, Cost is Product if (productItems.get(0) == null) { shop.updateStatus(); return new Tuple<>(ExchangeStatus.SHOP_NO_PRODUCT, productItems); @@ -447,13 +447,13 @@ public Tuple> canExchangeAll(Shop shop, Inventor } else { // Normal Trade //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getCost(), multiplier); + costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); if (costItems.get(0) == null) { return new Tuple<>(ExchangeStatus.PLAYER_NO_COST, costItems); } //Method to find Product items in shop inventory and add to product array - productItems = getItems(shopInventory.getStorageContents(), shop.getProduct(), multiplier); + productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); if (productItems.get(0) == null) { shop.updateStatus(); return new Tuple<>(ExchangeStatus.SHOP_NO_PRODUCT, productItems); diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index f2ba39d0..b92ad378 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -183,9 +183,9 @@ message: illegal-item: default: "&cYou cannot use one or more of those items in shops." pre-comment: "Text to display when a shop failed creation due to an illegal item" - no-shulker-cost: - default: "&cYou cannot add a Shulker Box as a cost when the shop uses it for storage." - pre-comment: "Text to display when a shop failed creation due to using a shulker box as cost when the shop uses it for storage: " + no-shulker-item: + default: "&cYou cannot add a Shulker Box when the shop uses it for storage." + pre-comment: "Text to display when a shop failed creation due to using a shulker box when the shop uses it for storage: " insufficient-items: default: "&cYou are missing the below items for the trade! \n{%MISSINGITEMS%= &e%AMOUNT% %ITEM%}" pre-comment: "Text to display when the player does not have enough items:" From 365f18a364436de011df7476f5247d58dee61c12 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 25 May 2022 17:30:28 -0700 Subject: [PATCH 04/53] DRY'd Shop User methods --- .../commands/commandrunners/EditCommand.java | 10 +- .../commands/commandrunners/ShopCommand.java | 14 +- .../commandrunners/ShopItemCommand.java | 10 +- .../commandrunners/ShopUserCommand.java | 13 +- .../java/org/shanerx/tradeshop/shop/Shop.java | 473 ++++++++---------- 5 files changed, 238 insertions(+), 282 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java index e3b771e2..93df8d5a 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java @@ -25,7 +25,6 @@ package org.shanerx.tradeshop.commands.commandrunners; -import com.google.common.collect.Iterables; import de.themoep.inventorygui.GuiElementGroup; import de.themoep.inventorygui.GuiStateElement; import de.themoep.inventorygui.InventoryGui; @@ -86,9 +85,8 @@ public void edit() { if (shop == null) return; - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) || - shop.getManagersUUID().contains(pSender.getUniqueId()) || - Permissions.isAdminEnabled(pSender))) { + if (!(shop.getUsersUUID(ShopRole.MANAGER, ShopRole.OWNER).contains(pSender.getUniqueId()) + || Permissions.isAdminEnabled(pSender))) { command.sendMessage(Message.NO_SHOP_PERMISSION.getPrefixed()); return; } @@ -126,7 +124,7 @@ public void edit() { return true; }, "Save Changes")); - for (ShopUser user : Iterables.concat(shop.getManagers(), shop.getMembers())) { + for (ShopUser user : shop.getUsers(ShopRole.MANAGER, ShopRole.MEMBER)) { shopUsers.add(user); userGroup.addElement(new GuiStateElement('e', user.getRole().toString(), @@ -164,7 +162,7 @@ public void edit() { } } else { - for (ShopUser user : Iterables.concat(shop.getManagers(), shop.getMembers())) { + for (ShopUser user : shop.getUsers(ShopRole.MANAGER, ShopRole.MEMBER)) { userGroup.addElement(new StaticGuiElement('e', user.getHead(), user.getName(), "Position: " + user.getRole().toString())); } } diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopCommand.java index 24031973..02824d29 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopCommand.java @@ -33,6 +33,7 @@ import org.shanerx.tradeshop.framework.events.PlayerShopCloseEvent; import org.shanerx.tradeshop.framework.events.PlayerShopOpenEvent; import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shop.ShopStatus; import org.shanerx.tradeshop.utils.objects.Tuple; @@ -52,9 +53,8 @@ public void open() { if (shop == null) return; - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) || - shop.getManagersUUID().contains(pSender.getUniqueId()) || - Permissions.isAdminEnabled(pSender))) { + if (!(shop.getUsersUUID(ShopRole.MANAGER, ShopRole.OWNER).contains(pSender.getUniqueId()) + || Permissions.isAdminEnabled(pSender))) { Message.NO_SHOP_PERMISSION.sendMessage(pSender); return; } @@ -89,9 +89,8 @@ public void close() { if (shop == null) return; - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) || - shop.getManagersUUID().contains(pSender.getUniqueId()) || - Permissions.isAdminEnabled(pSender))) { + if (!(shop.getUsersUUID(ShopRole.MANAGER, ShopRole.OWNER).contains(pSender.getUniqueId()) + || Permissions.isAdminEnabled(pSender))) { Message.NO_SHOP_PERMISSION.sendMessage(pSender); return; } @@ -133,8 +132,7 @@ public void switchShop() { } } - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) + if (!(shop.getUsersUUID(ShopRole.MANAGER, ShopRole.OWNER).contains(pSender.getUniqueId()) || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { Message.NO_SHOP_PERMISSION.sendMessage(pSender); return; diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java index 6a8cc0fc..7281bfd7 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java @@ -38,6 +38,7 @@ import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.utils.objects.ObjectHolder; import org.shanerx.tradeshop.utils.objects.Tuple; @@ -89,8 +90,7 @@ public void removeSide() { return; } - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) + if (!(shop.getUsersUUID(ShopRole.MANAGER, ShopRole.OWNER).contains(pSender.getUniqueId()) || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { Message.NO_SHOP_PERMISSION.sendMessage(pSender); return; @@ -135,8 +135,7 @@ public void setSide() { mat = Material.getMaterial(command.getArgAt(2).toUpperCase()); } - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) + if (!(shop.getUsersUUID(ShopRole.MANAGER, ShopRole.OWNER).contains(pSender.getUniqueId()) || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { Message.NO_SHOP_PERMISSION.sendMessage(pSender); return; @@ -212,8 +211,7 @@ public void addSide() { mat = Material.getMaterial(command.getArgAt(2).toUpperCase()); } - if (!(shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || shop.getManagersUUID().contains(pSender.getUniqueId()) + if (!(shop.getUsersUUID(ShopRole.MANAGER, ShopRole.OWNER).contains(pSender.getUniqueId()) || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender)))) { Message.NO_SHOP_PERMISSION.sendMessage(pSender); return; diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java index 764d34f6..2fff308f 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java @@ -35,6 +35,7 @@ import org.shanerx.tradeshop.framework.ShopChange; import org.shanerx.tradeshop.framework.events.PlayerShopChangeEvent; import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.player.ShopUser; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.utils.objects.ObjectHolder; @@ -74,8 +75,8 @@ public void who() { if (shop.getOwner() != null) owner = shop.getOwner().getName(); - if (shop.getManagers().size() > 0) { - for (ShopUser usr : shop.getManagers()) { + if (shop.hasUsers(ShopRole.MANAGER)) { + for (ShopUser usr : shop.getUsers(ShopRole.MANAGER)) { if (managers.toString().equals("")) managers = new StringBuilder(usr.getName()); else @@ -83,8 +84,8 @@ public void who() { } } - if (shop.getMembers().size() > 0) { - for (ShopUser usr : shop.getMembers()) { + if (shop.hasUsers(ShopRole.MEMBER)) { + for (ShopUser usr : shop.getUsers(ShopRole.MEMBER)) { if (members.toString().equals("")) members = new StringBuilder(usr.getName()); else @@ -134,7 +135,7 @@ public void addManager() { Bukkit.getPluginManager().callEvent(changeEvent); if (changeEvent.isCancelled()) return; - shop.addManager(target.getUniqueId()); + shop.addUser(target.getUniqueId(), ShopRole.MANAGER); Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); } @@ -203,7 +204,7 @@ public void addMember() { Bukkit.getPluginManager().callEvent(changeEvent); if (changeEvent.isCancelled()) return; - shop.addMember(target.getUniqueId()); + shop.addUser(target.getUniqueId(), ShopRole.MEMBER); Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); } diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index b1555e83..674ed7c1 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -49,7 +49,6 @@ import java.io.Serializable; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; @@ -174,24 +173,6 @@ public static Shop loadShop(Sign s) { return loadShop(new ShopLocation(s.getLocation())); } - /** - * Returns the shops owner - * - * @return ShopUser object of owner - */ - public ShopUser getOwner() { - return owner; - } - - /** - * Sets the owner (don't know if this will ever be used) - * - * @param owner The new owner of the shop - */ - public void setOwner(ShopUser owner) { - this.owner = owner; - } - /** * Sets the storageInventory */ @@ -218,44 +199,6 @@ public void removeEvent() { this.signChangeEvent = null; } - /** - * Returns the managers - * - * @return List of managers as ShopUser - */ - public List getManagers() { - List tempManagers = new ArrayList<>(); - - for (UUID user : managers) { - tempManagers.add(new ShopUser(user, ShopRole.MANAGER)); - } - - return tempManagers; - } - - /** - * Sets the managers - * - * @param managers the managers to be set to the shop - */ - public void setManagers(List managers) { - this.managers = managers; - } - - /** - * Returns a list of all users for the shop, including; owners, managers, and members. - * - * @return the sign. - */ - public List getUsers() { - List users = new ArrayList<>(); - users.add(owner); - users.addAll(getManagers()); - users.addAll(getMembers()); - - return users; - } - /** * Returns the storage block as a ShopChest * @@ -269,126 +212,6 @@ public ShopChest getChestAsSC() { } } - /** - * Gets the members of the shop as ShopUser - * - * @return List of members as ShopUser - */ - public List getMembers() { - List tempMembers = new ArrayList<>(); - - for (UUID user : members) { - tempMembers.add(new ShopUser(user, ShopRole.MEMBER)); - } - - return tempMembers; - } - - /** - * Sets the members - * - * @param members the members to be set to the shop - */ - public void setMembers(List members) { - this.members = members; - } - - /** - * Adds a manager to the shop - * - * @param newManager the player to be added as a shopUser object - * @return true if player has been added - */ - public boolean addManager(UUID newManager) { - if (!getUsersUUID().contains(newManager)) { - managers.add(newManager); - saveShop(); - return true; - } - return false; - } - - /** - * Updates the saved player data for all users - */ - private void updateUserFiles() { - TradeShop plugin = new Utils().PLUGIN; - for (UUID user : getUsersUUID()) { - PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(user); - playerSetting.updateShops(this); - plugin.getDataStorage().savePlayer(playerSetting); - } - } - - /** - * Removes this shop from all users - */ - private void purgeFromUserFiles() { - TradeShop plugin = new Utils().PLUGIN; - for (UUID user : getUsersUUID()) { - PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(user); - playerSetting.removeShop(this); - plugin.getDataStorage().savePlayer(playerSetting); - } - } - - /** - * Removes a user from the shop - * - * @param oldUser the UUID of the player to be removed - * @return true if user was removed - */ - public boolean removeUser(UUID oldUser) { - boolean ret = false; - if (getManagersUUID().contains(oldUser)) { - managers.remove(oldUser); - ret = true; - } - - if (getMembersUUID().contains(oldUser)) { - members.remove(oldUser); - ret = true; - } - - saveShop(); - - return ret; - } - - /** - * Adds a member to the shop - * - * @param newMember the player to be added as a shopUser object - * @return true if player has been added - */ - public boolean addMember(UUID newMember) { - if (!getUsersUUID().contains(newMember)) { - members.add(newMember); - saveShop(); - return true; - } - - return false; - } - - /** - * Returns a list of managers uuid - * - * @return List of all managers uuid - */ - public List getManagersUUID() { - return managers; - } - - /** - * Returns a list of all members uuid - * - * @return list of member uuid - */ - public List getMembersUUID() { - return members; - } - /** * Returns location of shops inventory * @@ -493,15 +316,6 @@ public void fixAfterLoad() { updateSign(); } - /** - * Gets all users of shop as UUID List - * - * @return List of all users as UUIDs - */ - public List getUsersUUID() { - return getUsers().stream().map(ShopUser::getUUID).collect(Collectors.toList()); - } - /** * Saves the shop to file */ @@ -692,15 +506,6 @@ public void updateStatus() { } } - /** - * Checks if shop has necessary items to make a trade - * - * @return true if items are missing - */ - public boolean isMissingItems() { - return shopType.equals(ShopType.ITRADE) ? product.isEmpty() : product.isEmpty() || cost.isEmpty(); - } - /** * Sets the shops status to closed */ @@ -738,49 +543,6 @@ else if (shopType == ShopType.BITRADE) updateSign(); } - /** - * Returns a list of Managers' names - * - * @return List of Managers' names - */ - public List getManagersNames() { - List names = Arrays.asList(new String[getManagers().size()]); - - for (int i = 0; i < getManagers().size(); i++) { - names.set(i, getManagers().get(i).getName()); - } - - return names; - } - - /** - * Returns a list of Members' names - * - * @return List of Members' names - */ - public List getMembersNames() { - List names = Arrays.asList(new String[getMembers().size()]); - - for (int i = 0; i < getMembers().size(); i++) { - names.set(i, getMembers().get(i).getName()); - } - - return names; - } - - /** - * Returns a list of Members' and Managers' names - * - * @return List of Members' and Managers' names - */ - public List getUserNames() { - List users = new ArrayList<>(); - users.addAll(getManagersNames()); - users.addAll(getMembersNames()); - - return users; - } - /** * Checks if all Items in the list are valid for trade * @@ -797,24 +559,6 @@ private boolean areItemsValid(ShopItemSide side, List items) { return true; } - /** - * Returns the ShopRole of the supplied UUID - * - * @param uuidToCheck uuid to check for role of - * @return the ShopRole of the supplied UUID - */ - public ShopRole checkRole(UUID uuidToCheck) { - if (owner.getUUID().equals(uuidToCheck)) { - return ShopRole.OWNER; - } else if (managers.contains(uuidToCheck)) { - return ShopRole.MANAGER; - } else if (members.contains(uuidToCheck)) { - return ShopRole.MEMBER; - } else { - return ShopRole.SHOPPER; - } - } - /** * Updates the number of trades the shop can make */ @@ -847,6 +591,122 @@ public void updateFullTradeCount() { availableTrades = currentCount == 0 || totalCount == 0 ? 0 : currentCount / totalCount; } + //region User Management - Methods for adding/deleting/updating/viewing a shops users + //------------------------------------------------------------------------------------------------------------------ + + /** + * Returns a list of all users for the shop based on specified roles. + * + * @param roles role to get users with + * @return list of ShopUsers. + */ + public List getUsers(ShopRole... roles) { + List users = new ArrayList<>(); + for (ShopRole role : roles) { + switch (role) { + case MEMBER: + members.forEach(uuid -> users.add(new ShopUser(uuid, ShopRole.MEMBER))); + break; + case MANAGER: + members.forEach(uuid -> users.add(new ShopUser(uuid, ShopRole.MANAGER))); + break; + case OWNER: + users.add(owner); + break; + } + } + + return users; + } + + /** + * Returns a list of all user names for the shop based on specified roles. + * + * @param roles role to get users with + * @return List of specified users names + */ + public List getUserNames(ShopRole... roles) { + return getUsers(roles).stream().map(ShopUser::getName).collect(Collectors.toList()); + } + + /** + * Returns a list of all user UUIDs for the shop based on specified roles. + * + * @param roles role to get users with + * @return List of specified users names + */ + public List getUsersUUID(ShopRole... roles) { + List users = new ArrayList<>(); + for (ShopRole role : roles) { + switch (role) { + case MEMBER: + users.addAll(members); + break; + case MANAGER: + users.addAll(managers); + break; + case OWNER: + users.add(owner.getUUID()); + break; + } + } + + return users; + } + + /** + * Returns true if the shop has users of the specified role + * + * @param role role to check for users + * @return true if users exist + */ + public boolean hasUsers(ShopRole role) { + return !getUsers(role).isEmpty(); + } + + /** + * Returns the shops owner + * + * @return ShopUser object of owner + */ + public ShopUser getOwner() { + return owner; + } + + /** + * Sets the owner (don't know if this will ever be used) + * + * @param owner The new owner of the shop + */ + public void setOwner(ShopUser owner) { + this.owner = owner; + } + + /** + * Adds a user to the shop with the specified role + * + * @param newUser the player to be added as a shopUser object + * @param role role to set thge player to + * @return true if player has been added + */ + public boolean addUser(UUID newUser, ShopRole role) { + boolean ret = false; + if (!getUsersUUID().contains(newUser)) { + switch (role) { + case MANAGER: + managers.add(newUser); + ret = true; + case MEMBER: + members.add(newUser); + ret = true; + } + } + + if (ret) saveShop(); + + return ret; + } + /** * Updates all shop users */ @@ -867,6 +727,98 @@ public void updateShopUsers(Set updatedUserSet) { saveShop(); } + /** + * Returns the ShopRole of the supplied UUID + * + * @param uuidToCheck uuid to check for role of + * @return the ShopRole of the supplied UUID + */ + public ShopRole checkRole(UUID uuidToCheck) { + if (owner.getUUID().equals(uuidToCheck)) { + return ShopRole.OWNER; + } else if (managers.contains(uuidToCheck)) { + return ShopRole.MANAGER; + } else if (members.contains(uuidToCheck)) { + return ShopRole.MEMBER; + } else { + return ShopRole.SHOPPER; + } + } + + /** + * Removes a user from the shop + * + * @param oldUser the UUID of the player to be removed + * @return true if user was removed + */ + public boolean removeUser(UUID oldUser) { + boolean ret = false; + if (getUsersUUID(ShopRole.MANAGER).contains(oldUser)) { + managers.remove(oldUser); + ret = true; + } + + if (getUsersUUID(ShopRole.MEMBER).contains(oldUser)) { + members.remove(oldUser); + ret = true; + } + + saveShop(); + + return ret; + } + + /** + * Sets the a list of users to a role + * + * @param users the managers to be set to the shop + */ + public boolean setUsers(List users, ShopRole role) { + boolean ret = false; + switch (role) { + case MANAGER: + users.forEach(this::removeUser); + managers = users; + ret = true; + case MEMBER: + users.forEach(this::removeUser); + members = users; + ret = true; + } + + if (ret) saveShop(); + + return ret; + } + + /** + * Updates the saved player data for all users + */ + private void updateUserFiles() { + TradeShop plugin = new Utils().PLUGIN; + for (UUID user : getUsersUUID()) { + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(user); + playerSetting.updateShops(this); + plugin.getDataStorage().savePlayer(playerSetting); + } + } + + /** + * Removes this shop from all users + */ + private void purgeFromUserFiles() { + TradeShop plugin = new Utils().PLUGIN; + for (UUID user : getUsersUUID()) { + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(user); + playerSetting.removeShop(this); + plugin.getDataStorage().savePlayer(playerSetting); + } + } + + + //------------------------------------------------------------------------------------------------------------------ + //endregion + //region Item Management - Methods for adding/deleting/updating/viewing Cost and Product lists //------------------------------------------------------------------------------------------------------------------ @@ -879,6 +831,15 @@ public boolean hasSide(ShopItemSide side) { return getSide(side).size() > 0; } + /** + * Checks if shop has necessary items to make a trade + * + * @return true if items are missing + */ + public boolean isMissingItems() { + return shopType.equals(ShopType.ITRADE) ? product.isEmpty() : product.isEmpty() || cost.isEmpty(); + } + /** * Returns the ItemStacks on specified side * From 22ffe94ed2423ebb75f100538c1e5ba3cf054b6a Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 25 May 2022 18:06:59 -0700 Subject: [PATCH 05/53] DRY'd Shop Constructors --- .../java/org/shanerx/tradeshop/shop/Shop.java | 46 ++++++------------- 1 file changed, 13 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 674ed7c1..1183908f 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -82,17 +82,22 @@ public class Shop implements Serializable { public Shop(Tuple locations, ShopType shopType, ShopUser owner, Tuple, List> players, Tuple items) { shopLoc = new ShopLocation(locations.getLeft()); this.owner = owner; - chestLoc = new ShopLocation(locations.getRight()); - utils.PLUGIN.getDataStorage().addChestLinkage(chestLoc, shopLoc); + + if (locations.getRight() != null) { + chestLoc = new ShopLocation(locations.getRight()); + utils.PLUGIN.getDataStorage().addChestLinkage(chestLoc, shopLoc); + } + this.shopType = shopType; - managers = players.getLeft(); - members = players.getRight(); + + managers = players.getLeft() == null ? Collections.emptyList() : players.getLeft(); + members = players.getRight() == null ? Collections.emptyList() : players.getRight(); product = new ArrayList<>(); cost = new ArrayList<>(); - product.add(new ShopItemStack(items.getLeft())); - cost.add(new ShopItemStack(items.getRight())); + if (items.getLeft() != null) product.add(new ShopItemStack(items.getLeft())); + if (items.getRight() != null) cost.add(new ShopItemStack(items.getRight())); fixAfterLoad(); } @@ -105,18 +110,7 @@ public Shop(Tuple locations, ShopType shopType, ShopUser own * @param shopType Type of the shop as ShopType */ public Shop(Tuple locations, ShopType shopType, ShopUser owner) { - shopLoc = new ShopLocation(locations.getLeft()); - this.owner = owner; - chestLoc = new ShopLocation(locations.getRight()); - utils.PLUGIN.getDataStorage().addChestLinkage(chestLoc, shopLoc); - this.shopType = shopType; - managers = Collections.emptyList(); - members = Collections.emptyList(); - - product = new ArrayList<>(); - cost = new ArrayList<>(); - - fixAfterLoad(); + this(locations, shopType, owner, new Tuple<>(null, null), new Tuple<>(null, null)); } /** @@ -127,16 +121,7 @@ public Shop(Tuple locations, ShopType shopType, ShopUser own * @param shopType Type of the shop as ShopType */ public Shop(Location location, ShopType shopType, ShopUser owner) { - shopLoc = new ShopLocation(location); - this.owner = owner; - this.shopType = shopType; - managers = Collections.emptyList(); - members = Collections.emptyList(); - - product = new ArrayList<>(); - cost = new ArrayList<>(); - - fixAfterLoad(); + this(new Tuple<>(location, null), shopType, owner, new Tuple<>(null, null), new Tuple<>(null, null)); } /** @@ -307,11 +292,6 @@ public void fixAfterLoad() { utils.PLUGIN.getDataStorage().addChestLinkage(chestLoc, shopLoc); } - /* TODO Fix this after 2.4 - Removed since this ends up running getItems everytime a hopper trys to access a shop. - Runs up to 3 times per second per hopper under a tradeshop with items inside - Removing this caused errors with shops not being updated properly and causing fail messages during trades - */ if (getShopSign() != null) updateSign(); } From ecdd47410b7d5e2bbdb0685d95b1bc4ac83cc5af Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 25 May 2022 18:28:38 -0700 Subject: [PATCH 06/53] Fix for #128 --- .../java/org/shanerx/tradeshop/utils/Utils.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 96f8f673..d9141a09 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -524,7 +524,7 @@ public List getItems(ItemStack[] storageContents, List for (ItemStack storageItem : storage.keySet()) { boolean isSimilar = item.isSimilar(storageItem); if (isSimilar) { - int taken = Math.min(storage.get(storageItem), count); + int taken = megaMin(storage.get(storageItem), count, storageItem.getMaxStackSize()); if (found.putIfAbsent(item.getItemStack(), taken) != null) found.put(item.getItemStack(), storage.get(storageItem) + taken); @@ -555,4 +555,19 @@ public List getItems(ItemStack[] storageContents, List return currentCount != totalCount ? bad : good; } + + /** + * Returns the smallest integer passed to it + * + * @param values list of integers to compare against each other + * @return smallest integer + */ + public int megaMin(int... values) { + int min = values[0]; + for (int i : values) { + min = Math.min(i, min); + } + + return min; + } } \ No newline at end of file From f56b7279e37000263a5c6062ad91fabcdd483abb Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 25 May 2022 20:43:41 -0700 Subject: [PATCH 07/53] Implementation of #129 --- .../tradeshop/commands/CommandCaller.java | 8 +- .../shanerx/tradeshop/commands/Commands.java | 6 +- .../commandrunners/ShopUserCommand.java | 175 ++++++++++-------- .../tradeshop/data/config/Message.java | 52 +++++- .../tradeshop/data/config/Variable.java | 4 +- .../java/org/shanerx/tradeshop/shop/Shop.java | 14 +- .../org/shanerx/tradeshop/utils/Utils.java | 65 ++++--- src/main/resources/Lang/en-us.yml | 18 +- 8 files changed, 221 insertions(+), 121 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java index c64cafa2..7eec06f0 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java @@ -40,7 +40,9 @@ import org.shanerx.tradeshop.commands.commandrunners.ShopUserCommand; import org.shanerx.tradeshop.commands.commandrunners.WhatCommand; import org.shanerx.tradeshop.data.config.Message; +import org.shanerx.tradeshop.framework.ShopChange; import org.shanerx.tradeshop.item.ShopItemSide; +import org.shanerx.tradeshop.player.ShopRole; /** * This class is used for calling command methods from CommandRunner @@ -117,13 +119,13 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String new ShopUserCommand(plugin, cmdPass).who(); break; case ADD_MANAGER: - new ShopUserCommand(plugin, cmdPass).addManager(); + new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.MANAGER, ShopChange.ADD_MANAGER); break; case REMOVE_USER: - new ShopUserCommand(plugin, cmdPass).removeUser(); + new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.SHOPPER, ShopChange.REMOVE_USER); break; case ADD_MEMBER: - new ShopUserCommand(plugin, cmdPass).addMember(); + new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.MEMBER, ShopChange.ADD_MEMBER); break; case MULTI: new GeneralPlayerCommand(plugin, cmdPass).multi(); diff --git a/src/main/java/org/shanerx/tradeshop/commands/Commands.java b/src/main/java/org/shanerx/tradeshop/commands/Commands.java index 1d8b540b..bf8327b4 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/Commands.java +++ b/src/main/java/org/shanerx/tradeshop/commands/Commands.java @@ -52,9 +52,9 @@ public enum Commands { CREATE_ITRADE(Lists.newArrayList("createitrade", "createi", "cri"), Permissions.CREATEI, 1, 1, true, "Create iTrade shop", "/tradeshop $cmd$"), // Shop user management commands - ADD_MANAGER(Lists.newArrayList("addManager"), Permissions.NONE, 2, 2, true, "Add manager to shop", "/tradeshop $cmd$ "), - REMOVE_USER(Lists.newArrayList("removeUser", "removeManager", "removeMember"), Permissions.NONE, 2, 2, true, "Remove user from shop", "/tradeshop $cmd$ "), - ADD_MEMBER(Lists.newArrayList("addMember"), Permissions.NONE, 2, 2, true, "Add member to shop", "/tradeshop $cmd$ "), + ADD_MANAGER(Lists.newArrayList("addManager"), Permissions.NONE, 2, 3, true, "Add manager to shop", "/tradeshop $cmd$ [all shops]"), + REMOVE_USER(Lists.newArrayList("removeUser", "removeManager", "removeMember"), Permissions.NONE, 2, 3, true, "Remove user from shop", "/tradeshop $cmd$ [all shops]"), + ADD_MEMBER(Lists.newArrayList("addMember"), Permissions.NONE, 2, 3, true, "Add member to shop", "/tradeshop $cmd$ [all shops]"), // Shop item management commands ADD_PRODUCT(Lists.newArrayList("addProduct"), Permissions.NONE, 1, 3, true, "Add product to shop", "/tradeshop $cmd$ [Amount] [Material]"), diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java index 2fff308f..887ebc1e 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java @@ -38,9 +38,34 @@ import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.player.ShopUser; import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.objects.ObjectHolder; import org.shanerx.tradeshop.utils.objects.Tuple; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +enum UserOperationStatus { + SUCCESSFUL(Message.UPDATED_SHOP_USERS_SUCCESSFUL), + FAILED_CAPACITY(Message.UPDATED_SHOP_USERS_FAILED_CAPACITY), + FAILED_EXISTING(Message.UPDATED_SHOP_USERS_FAILED_EXISTING), + FAILED_MISSING(Message.UPDATED_SHOP_USERS_FAILED_MISSING); + + private final Message text; + + UserOperationStatus(Message text) { + this.text = text; + } + + @Override + public String toString() { + return text.toString(); + } +} + /** * Implementation of CommandRunner for commands that view/change shop users * @@ -48,6 +73,8 @@ */ public class ShopUserCommand extends CommandRunner { + private OfflinePlayer target; + public ShopUserCommand(TradeShop instance, CommandPass command) { super(instance, command); } @@ -106,106 +133,100 @@ public void who() { } /** - * Adds the specified player to the shop as a manager + * Adds or Removes the specified player to/from the shop as the specified role */ - public void addManager() { - Shop shop = findShop(); + public void editUser(ShopRole role, ShopChange change) { + boolean applyAllOwned = command.hasArgAt(2) && toBool(command.getArgAt(2)); + Set ownedShops = new HashSet<>(); + Map updateStatuses = new HashMap<>(); - if (shop == null) - return; + Shop tempShop = shopUserCommandStart(applyAllOwned); - if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); + if (tempShop == null && target == null) { return; } - OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); - if (!target.hasPlayedBefore()) { - Message.PLAYER_NOT_FOUND.sendMessage(pSender); - return; - } - - if (shop.getUsersUUID().contains(target.getUniqueId())) { - Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); - return; + if (applyAllOwned) { + for (String location : plugin.getDataStorage().loadPlayer(pSender.getUniqueId()).getOwnedShops()) { + ownedShops.add(plugin.getDataStorage().loadShopFromSign(ShopLocation.deserialize(location))); + } + } else { + ownedShops.add(tempShop); } - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.ADD_MANAGER, new ObjectHolder(target)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - shop.addUser(target.getUniqueId(), ShopRole.MANAGER); - - Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); - } - - /** - * Removes the specified player from the shop if they currently are a manager - */ - public void removeUser() { - Shop shop = findShop(); - - if (shop == null) - return; + for (Shop shop : ownedShops) { + if (shop.getUsersUUID().contains(target.getUniqueId()) && change != ShopChange.REMOVE_USER) { + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_EXISTING.toString()); + break; + } else if (!shop.getUsersUUID().contains(target.getUniqueId()) && change == ShopChange.REMOVE_USER) { + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_MISSING.toString()); + break; + } else if (shop.getUsers(ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt() && change != ShopChange.REMOVE_USER) { + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_CAPACITY.toString()); + break; + } - if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } + PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, change, new ObjectHolder(target)); + Bukkit.getPluginManager().callEvent(changeEvent); + if (changeEvent.isCancelled()) return; + + switch (change) { + case ADD_MEMBER: + case ADD_MANAGER: + shop.addUser(target.getUniqueId(), role); + break; + case REMOVE_USER: + shop.removeUser(target.getUniqueId()); + break; + } - OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); - if (!target.hasPlayedBefore()) { - Message.PLAYER_NOT_FOUND.sendMessage(pSender); - return; + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.SUCCESSFUL.toString()); } - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.REMOVE_USER, new ObjectHolder(target)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; + Message.UPDATED_SHOP_USERS.sendUserEditMultiLineMessage(pSender, Collections.singletonMap(Variable.UPDATED_SHOPS, updateStatuses)); + } - if (!shop.removeUser(target.getUniqueId())) { - Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); - return; - } - Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); - } + //region Util Methods + //------------------------------------------------------------------------------------------------------------------ /** - * Adds the specified player to the shop as a member + * Checks if targeted player exists and if player is looking at a shop while not targetting all owned shops + * + * @param applyAllOwned Is Player targetting all owned shops + * @return shop if found or null if not needed; returning null while setting target to null indicates failure, command should respond with an immediate blank return. */ - public void addMember() { - Shop shop = findShop(); - - if (shop == null) - return; - - if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) - || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - OfflinePlayer target = Bukkit.getOfflinePlayer(command.getArgAt(1)); + private Shop shopUserCommandStart(boolean applyAllOwned) { + target = Bukkit.getOfflinePlayer(command.getArgAt(1)); if (!target.hasPlayedBefore()) { Message.PLAYER_NOT_FOUND.sendMessage(pSender); - return; + target = null; + return null; } + if (!applyAllOwned) { + Shop shop = findShop(); - if (shop.getUsersUUID().contains(target.getUniqueId())) { - Message.UNSUCCESSFUL_SHOP_MEMBERS.sendMessage(pSender); - return; - } + if (shop == null) { + Message.NO_SIGHTED_SHOP.sendMessage(pSender); + target = null; + return null; + } - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, ShopChange.ADD_MEMBER, new ObjectHolder(target)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; + if (!shop.getOwner().getUUID().equals(pSender.getUniqueId()) + || (Setting.UNLIMITED_ADMIN.getBoolean() && Permissions.isAdminEnabled(pSender))) { + Message.NO_SHOP_PERMISSION.sendMessage(pSender); + target = null; + return null; + } - shop.addUser(target.getUniqueId(), ShopRole.MEMBER); + return shop; + } - Message.UPDATED_SHOP_MEMBERS.sendMessage(pSender); + return null; } -} + + + //------------------------------------------------------------------------------------------------------------------ + //endregion +} \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java index f22fbb06..82ab897f 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -91,7 +91,11 @@ public enum Message { TOO_MANY_CHESTS(MessageSection.NONE, "too-many-chests"), TOO_MANY_ITEMS(MessageSection.NONE, "too-many-items"), UNSUCCESSFUL_SHOP_MEMBERS(MessageSection.NONE, "unsuccessful-shop-members"), - UPDATED_SHOP_MEMBERS(MessageSection.NONE, "updated-shop-members"), + UPDATED_SHOP_USERS(MessageSection.NONE, "updated-shop-users"), + UPDATED_SHOP_USERS_SUCCESSFUL(MessageSection.NONE, "pdated-shop-users-successful"), + UPDATED_SHOP_USERS_FAILED_CAPACITY(MessageSection.NONE, "updated-shop-users-failed-capacity"), + UPDATED_SHOP_USERS_FAILED_EXISTING(MessageSection.NONE, "updated-shop-users-failed-existing"), + UPDATED_SHOP_USERS_FAILED_MISSING(MessageSection.NONE, "updated-shop-users-failed-missing"), WHO_MESSAGE(MessageSection.NONE, "who-message"), VIEW_PLAYER_LEVEL(MessageSection.NONE, "view-player-level"), SET_PLAYER_LEVEL(MessageSection.NONE, "set-player-level"), @@ -315,6 +319,52 @@ public final void sendItemMultiLineMessage(Player player, Map> valuesToFill, Tuple... replacements) { + if (valuesToFill.isEmpty()) { + sendMessage(player, replacements); + return; + } + + boolean isJson = getString().startsWith("#json "); + String message = getPrefixed().replaceFirst("#json ", ""); + + Debug debug = new Utils().debugger; + + for (Map.Entry> entry : valuesToFill.entrySet()) { + Pattern pattern = Pattern.compile(MULTILINEREGEX.replace("&V&", entry.getKey().toString())); + Matcher matcher = pattern.matcher(message); + + if (entry.getValue().get(0) == null) { + entry.getValue().remove(0); + } + + while (matcher.find()) { + StringBuilder itemList = new StringBuilder(); + String found = matcher.group(), format = found.replaceAll("[{}]", "").split("=")[1]; + + entry.getValue().forEach((k, v) -> { + itemList.append("\n") + .append(format.replace(Variable.SHOP.toString(), k).replace(Variable.STATUS.toString(), v)); + }); + + message = message.replace(found, itemList.toString()); + } + } + + for (Tuple replace : replacements) { + message = message.replace(replace.getLeft().toUpperCase(), replace.getRight()) + .replace(replace.getLeft().toLowerCase(), replace.getRight()) + .replace(replace.getLeft(), replace.getRight()); + } + + if (isJson) { + sendMessageDirectJson(player, message); + } else { + sendMessageDirect(player, message); + } + } + @SafeVarargs public final void sendMessage(CommandSender sender, Tuple... replacements) { if (sender instanceof Player) { diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Variable.java b/src/main/java/org/shanerx/tradeshop/data/config/Variable.java index 6566f3bd..2d9679c5 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Variable.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Variable.java @@ -44,7 +44,9 @@ public enum Variable { STATE, MISSING_ITEMS, RECEIVED_LINES, - GIVEN_LINES; + GIVEN_LINES, + UPDATED_SHOPS, + SHOP; final String SURROUND = "%"; diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 1183908f..143ffae9 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -670,6 +670,9 @@ public void setOwner(ShopUser owner) { * @return true if player has been added */ public boolean addUser(UUID newUser, ShopRole role) { + if (getUsers(ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt()) + return false; + boolean ret = false; if (!getUsersUUID().contains(newUser)) { switch (role) { @@ -693,16 +696,7 @@ public boolean addUser(UUID newUser, ShopRole role) { public void updateShopUsers(Set updatedUserSet) { for (ShopUser user : updatedUserSet) { removeUser(user.getUUID()); - switch (user.getRole()) { - case MANAGER: - managers.add(user.getUUID()); - break; - case MEMBER: - members.add(user.getUUID()); - break; - default: - break; - } + addUser(user.getUUID(), user.getRole()); } saveShop(); } diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index d9141a09..9031dd16 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -432,48 +432,48 @@ public Tuple> canExchangeAll(Shop shop, Inventor return new Tuple<>(ExchangeStatus.SUCCESS, createBadList()); //Successfully completed trade } else if (shop.getShopType() == ShopType.BITRADE && action == Action.LEFT_CLICK_BLOCK) { //BiTrade Reversed Trade - //Method to find Cost items in player inventory and add to cost array + //Method to find Cost items in player inventory and add to cost array costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); //Reverse BiTrade, Product is Cost if (costItems.get(0) == null) { return new Tuple<>(ExchangeStatus.PLAYER_NO_COST, costItems); - } + } - //Method to find Product items in shop inventory and add to product array + //Method to find Product items in shop inventory and add to product array productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); //Reverse BiTrade, Cost is Product - if (productItems.get(0) == null) { + if (productItems.get(0) == null) { shop.updateStatus(); return new Tuple<>(ExchangeStatus.SHOP_NO_PRODUCT, productItems); - } - } else { // Normal Trade + } + } else { // Normal Trade - //Method to find Cost items in player inventory and add to cost array + //Method to find Cost items in player inventory and add to cost array costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); if (costItems.get(0) == null) { return new Tuple<>(ExchangeStatus.PLAYER_NO_COST, costItems); - } + } - //Method to find Product items in shop inventory and add to product array + //Method to find Product items in shop inventory and add to product array productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); - if (productItems.get(0) == null) { + if (productItems.get(0) == null) { shop.updateStatus(); return new Tuple<>(ExchangeStatus.SHOP_NO_PRODUCT, productItems); - } + } - } + } - //For loop to remove cost items from player inventory - for (ItemStack item : costItems) { - playerInventory.removeItem(item); - } + //For loop to remove cost items from player inventory + for (ItemStack item : costItems) { + playerInventory.removeItem(item); + } - //For loop to remove product items from shop inventory - for (ItemStack item : productItems) { - shopInventory.removeItem(item); - } + //For loop to remove product items from shop inventory + for (ItemStack item : productItems) { + shopInventory.removeItem(item); + } - //For loop to put cost items in shop inventory - for (ItemStack item : costItems) { - if (!shopInventory.addItem(item).isEmpty()) { + //For loop to put cost items in shop inventory + for (ItemStack item : costItems) { + if (!shopInventory.addItem(item).isEmpty()) { return new Tuple<>(ExchangeStatus.SHOP_NO_SPACE, createBadList()); } } @@ -560,6 +560,7 @@ public List getItems(ItemStack[] storageContents, List * Returns the smallest integer passed to it * * @param values list of integers to compare against each other + * * @return smallest integer */ public int megaMin(int... values) { @@ -570,4 +571,22 @@ public int megaMin(int... values) { return min; } + + /** + * Converts string to boolean based on acceptable responses + * + * @param check String to convert to boolean + * @return true if acceptable string was found + */ + public boolean toBool(String check) { + switch (check.toLowerCase()) { + case "true": + case "t": + case "yes": + case "y": + return true; + default: + return false; + } + } } \ No newline at end of file diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index b92ad378..276cd2cd 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -278,9 +278,21 @@ message: unsuccessful-shop-members: default: "&aThat player is either already on the shop, or you have reached the maximum number of users!" pre-comment: "Text to display when shop users could not be updated" - updated-shop-members: - default: "&aShop owners and members have been updated!" - pre-comment: "Text to display when shop users have been updated successfully" + updated-shop-users: + default: "&aShop users have tried to update for the below shops! \n{%UPDATED_SHOPS%= %SHOP% -|- %STATUS%}" + pre-comment: "Text to display when shop users have been updated." + updated-shop-users-successful: + default: "&aSuccessful" + pre-comment: "Text to display when shop users have been updated successfully." + updated-shop-users-failed-capacity: + default: "&cMax Capacity" + pre-comment: "Text to display when shop users have been added but the max amount of users is already on the shop." + updated-shop-users-failed-existing: + default: "&ePlayer Exists" + pre-comment: "Text to display when shop users have been added and the player is already on the shop." + updated-shop-users-failed-missing: + default: "&ePlayer Missing" + pre-comment: "Text to display when shop users have been removed and the player was not on the shop." who-message: default: "&6Shop users are:\n&2Owner: &e%OWNER%\n&2Managers: &e%MANAGERS%\n&2Members: &e%MEMBERS%" pre-comment: "Text to display when players use the who command" From 4da7e2324db3b4b1ca865026753c994b2c067d8f Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 25 May 2022 20:47:30 -0700 Subject: [PATCH 08/53] Removed depreciated UNSUCCESSFUL_SHOP_MEMBERS Message --- src/main/java/org/shanerx/tradeshop/data/config/Message.java | 1 - src/main/resources/Lang/en-us.yml | 3 --- 2 files changed, 4 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java index 82ab897f..cd45bd63 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -90,7 +90,6 @@ public enum Message { SUCCESSFUL_SETUP(MessageSection.NONE, "successful-setup"), TOO_MANY_CHESTS(MessageSection.NONE, "too-many-chests"), TOO_MANY_ITEMS(MessageSection.NONE, "too-many-items"), - UNSUCCESSFUL_SHOP_MEMBERS(MessageSection.NONE, "unsuccessful-shop-members"), UPDATED_SHOP_USERS(MessageSection.NONE, "updated-shop-users"), UPDATED_SHOP_USERS_SUCCESSFUL(MessageSection.NONE, "pdated-shop-users-successful"), UPDATED_SHOP_USERS_FAILED_CAPACITY(MessageSection.NONE, "updated-shop-users-failed-capacity"), diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 276cd2cd..2d0821d3 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -275,9 +275,6 @@ message: default: "&cThere are too many shops in this chunk, you can not add another one." too-many-items: default: "&cThis shop cannot take any more %SIDE% items!" - unsuccessful-shop-members: - default: "&aThat player is either already on the shop, or you have reached the maximum number of users!" - pre-comment: "Text to display when shop users could not be updated" updated-shop-users: default: "&aShop users have tried to update for the below shops! \n{%UPDATED_SHOPS%= %SHOP% -|- %STATUS%}" pre-comment: "Text to display when shop users have been updated." From 98ea92399c245f35f9d024607b7c45cff25c361f Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 26 May 2022 20:45:52 -0700 Subject: [PATCH 09/53] Fix for #130 --- .../shop/listeners/ShopProtectionListener.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java index 68804d90..4f8f9c6d 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java @@ -135,12 +135,20 @@ public void onInventoryMoveItem(InventoryMoveItemEvent event) { debugger.log("ShopProtectionListener: (TSAF) HopperEvent fired! ", DebugLevels.PROTECTION); Bukkit.getPluginManager().callEvent(hopperEvent); debugger.log("ShopProtectionListener: (TSAF) HopperEvent recovered! ", DebugLevels.PROTECTION); + debugger.log("ShopProtectionListener: (TSAF) HopperEvent isForbidden: " + hopperEvent.isForbidden(), DebugLevels.PROTECTION); event.setCancelled(hopperEvent.isForbidden()); plugin.getListManager().addSkippableHopper(event.getInitiator().getLocation(), hopperEvent.isForbidden()); - debugger.log("ShopProtectionListener: (TSAF) HopperEvent isForbidden: " + hopperEvent.isForbidden(), DebugLevels.PROTECTION); - shop.updateStatus(); - shop.updateSign(); - shop.saveShop(); + + if (!hopperEvent.isForbidden()) { + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + @Override + public void run() { + shop.updateSign(); + shop.saveShop(); + } + }, 2L); + + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) From fcc07c444c01a3ff9dea90a762cfc8a1a77a4e2c Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 27 May 2022 14:37:21 -0700 Subject: [PATCH 10/53] Feature add for #131 --- .../tradeshop/commands/CommandCaller.java | 12 ++- .../shanerx/tradeshop/commands/Commands.java | 4 +- .../commandrunners/ShopUserCommand.java | 78 +++++++++++++------ .../tradeshop/data/config/Message.java | 1 + .../tradeshop/framework/ShopChange.java | 29 ++++++- .../java/org/shanerx/tradeshop/shop/Shop.java | 37 ++++++++- src/main/resources/Lang/en-us.yml | 9 ++- 7 files changed, 133 insertions(+), 37 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java index 7eec06f0..ee98c192 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java @@ -118,15 +118,21 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String case WHO: new ShopUserCommand(plugin, cmdPass).who(); break; - case ADD_MANAGER: - new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.MANAGER, ShopChange.ADD_MANAGER); - break; case REMOVE_USER: new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.SHOPPER, ShopChange.REMOVE_USER); break; + case ADD_MANAGER: + new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.MANAGER, ShopChange.ADD_MANAGER); + break; case ADD_MEMBER: new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.MEMBER, ShopChange.ADD_MEMBER); break; + case SET_MANAGER: + new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.MANAGER, ShopChange.SET_MANAGER); + break; + case SET_MEMBER: + new ShopUserCommand(plugin, cmdPass).editUser(ShopRole.MEMBER, ShopChange.SET_MEMBER); + break; case MULTI: new GeneralPlayerCommand(plugin, cmdPass).multi(); break; diff --git a/src/main/java/org/shanerx/tradeshop/commands/Commands.java b/src/main/java/org/shanerx/tradeshop/commands/Commands.java index bf8327b4..e04df6e4 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/Commands.java +++ b/src/main/java/org/shanerx/tradeshop/commands/Commands.java @@ -52,9 +52,11 @@ public enum Commands { CREATE_ITRADE(Lists.newArrayList("createitrade", "createi", "cri"), Permissions.CREATEI, 1, 1, true, "Create iTrade shop", "/tradeshop $cmd$"), // Shop user management commands - ADD_MANAGER(Lists.newArrayList("addManager"), Permissions.NONE, 2, 3, true, "Add manager to shop", "/tradeshop $cmd$ [all shops]"), REMOVE_USER(Lists.newArrayList("removeUser", "removeManager", "removeMember"), Permissions.NONE, 2, 3, true, "Remove user from shop", "/tradeshop $cmd$ [all shops]"), + ADD_MANAGER(Lists.newArrayList("addManager"), Permissions.NONE, 2, 3, true, "Add manager to shop", "/tradeshop $cmd$ [all shops]"), ADD_MEMBER(Lists.newArrayList("addMember"), Permissions.NONE, 2, 3, true, "Add member to shop", "/tradeshop $cmd$ [all shops]"), + SET_MANAGER(Lists.newArrayList("setManager"), Permissions.NONE, 2, 3, true, "Sets a player to Manager on a shop", "/tradeshop $cmd$ [all shops]"), + SET_MEMBER(Lists.newArrayList("setMember"), Permissions.NONE, 2, 3, true, "Sets a player to Member on a shop", "/tradeshop $cmd$ [all shops]"), // Shop item management commands ADD_PRODUCT(Lists.newArrayList("addProduct"), Permissions.NONE, 1, 3, true, "Add product to shop", "/tradeshop $cmd$ [Amount] [Material]"), diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java index 887ebc1e..2a9c0e5a 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java @@ -50,6 +50,7 @@ enum UserOperationStatus { SUCCESSFUL(Message.UPDATED_SHOP_USERS_SUCCESSFUL), + FAILED(Message.UPDATED_SHOP_USERS_FAILED), FAILED_CAPACITY(Message.UPDATED_SHOP_USERS_FAILED_CAPACITY), FAILED_EXISTING(Message.UPDATED_SHOP_USERS_FAILED_EXISTING), FAILED_MISSING(Message.UPDATED_SHOP_USERS_FAILED_MISSING); @@ -155,32 +156,59 @@ public void editUser(ShopRole role, ShopChange change) { } for (Shop shop : ownedShops) { - if (shop.getUsersUUID().contains(target.getUniqueId()) && change != ShopChange.REMOVE_USER) { - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_EXISTING.toString()); - break; - } else if (!shop.getUsersUUID().contains(target.getUniqueId()) && change == ShopChange.REMOVE_USER) { - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_MISSING.toString()); - break; - } else if (shop.getUsers(ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt() && change != ShopChange.REMOVE_USER) { - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_CAPACITY.toString()); - break; - } - - PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, change, new ObjectHolder(target)); - Bukkit.getPluginManager().callEvent(changeEvent); - if (changeEvent.isCancelled()) return; - - switch (change) { - case ADD_MEMBER: - case ADD_MANAGER: - shop.addUser(target.getUniqueId(), role); - break; - case REMOVE_USER: - shop.removeUser(target.getUniqueId()); - break; + eachOwnedShop: + { + switch (change) { + case REMOVE_USER: + if (!shop.getUsersUUID().contains(target.getUniqueId())) { + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_MISSING.toString()); + break eachOwnedShop; + } + break; + case ADD_MANAGER: + case ADD_MEMBER: + if (shop.getUsersUUID().contains(target.getUniqueId())) { + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_EXISTING.toString()); + break eachOwnedShop; + } else if (shop.getUsers(ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt()) { + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_CAPACITY.toString()); + break eachOwnedShop; + } + break; + case SET_MANAGER: + case SET_MEMBER: + if (shop.getUsersExcluding(Collections.singletonList(target.getUniqueId()), ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt()) { + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_CAPACITY.toString()); + break eachOwnedShop; + } + break; + } + + PlayerShopChangeEvent changeEvent = new PlayerShopChangeEvent(pSender, shop, change, new ObjectHolder(target)); + Bukkit.getPluginManager().callEvent(changeEvent); + if (changeEvent.isCancelled()) return; + + boolean success = false; + + switch (change) { + case SET_MANAGER: + case SET_MEMBER: + success = shop.setUser(target.getUniqueId(), role); + break; + case ADD_MEMBER: + case ADD_MANAGER: + success = shop.addUser(target.getUniqueId(), role); + break; + case REMOVE_USER: + success = shop.removeUser(target.getUniqueId()); + break; + } + + if (success) + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.SUCCESSFUL.toString()); + else + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED.toString()); } - - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.SUCCESSFUL.toString()); } Message.UPDATED_SHOP_USERS.sendUserEditMultiLineMessage(pSender, Collections.singletonMap(Variable.UPDATED_SHOPS, updateStatuses)); diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java index cd45bd63..8028966a 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -92,6 +92,7 @@ public enum Message { TOO_MANY_ITEMS(MessageSection.NONE, "too-many-items"), UPDATED_SHOP_USERS(MessageSection.NONE, "updated-shop-users"), UPDATED_SHOP_USERS_SUCCESSFUL(MessageSection.NONE, "pdated-shop-users-successful"), + UPDATED_SHOP_USERS_FAILED(MessageSection.NONE, "updated-shop-users-failed"), UPDATED_SHOP_USERS_FAILED_CAPACITY(MessageSection.NONE, "updated-shop-users-failed-capacity"), UPDATED_SHOP_USERS_FAILED_EXISTING(MessageSection.NONE, "updated-shop-users-failed-existing"), UPDATED_SHOP_USERS_FAILED_MISSING(MessageSection.NONE, "updated-shop-users-failed-missing"), diff --git a/src/main/java/org/shanerx/tradeshop/framework/ShopChange.java b/src/main/java/org/shanerx/tradeshop/framework/ShopChange.java index a63fdf1f..2c42d466 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/ShopChange.java +++ b/src/main/java/org/shanerx/tradeshop/framework/ShopChange.java @@ -1,12 +1,39 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + package org.shanerx.tradeshop.framework; /** * This enum's entries represent the possible changes the {@link org.shanerx.tradeshop.framework.events.PlayerShopChangeEvent} is fired upon. */ public enum ShopChange { - + ADD_MANAGER, ADD_MEMBER, + SET_MANAGER, + SET_MEMBER, ADD_PRODUCT, ADD_COST, REMOVE_USER, diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 143ffae9..f637a0ff 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -581,17 +581,35 @@ public void updateFullTradeCount() { * @return list of ShopUsers. */ public List getUsers(ShopRole... roles) { + return getUsersExcluding(Collections.emptyList(), roles); + } + + /** + * Returns a list of all users for the shop based on specified roles. Will exclude any users in the list. + * + * @param excludedPlayers player UUIDs to exclude from the results + * @param roles role to get users with + * @return list of ShopUsers. + */ + public List getUsersExcluding(List excludedPlayers, ShopRole... roles) { List users = new ArrayList<>(); for (ShopRole role : roles) { switch (role) { case MEMBER: - members.forEach(uuid -> users.add(new ShopUser(uuid, ShopRole.MEMBER))); + members.forEach(uuid -> { + if (!excludedPlayers.contains(uuid)) + users.add(new ShopUser(uuid, ShopRole.MEMBER)); + }); break; case MANAGER: - members.forEach(uuid -> users.add(new ShopUser(uuid, ShopRole.MANAGER))); + members.forEach(uuid -> { + if (!excludedPlayers.contains(uuid)) + users.add(new ShopUser(uuid, ShopRole.MANAGER)); + }); break; case OWNER: - users.add(owner); + if (!excludedPlayers.contains(owner.getUUID())) + users.add(owner); break; } } @@ -662,10 +680,21 @@ public void setOwner(ShopUser owner) { this.owner = owner; } + /** + * Sets a user to the shop with the specified role after removing it if it was already on the shop + * + * @param newUser the player to be set + * @param role role to set thge player to + * @return true if player has been set + */ + public boolean setUser(UUID newUser, ShopRole role) { + return removeUser(newUser) && addUser(newUser, role); + } + /** * Adds a user to the shop with the specified role * - * @param newUser the player to be added as a shopUser object + * @param newUser the player to be added * @param role role to set thge player to * @return true if player has been added */ diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 2d0821d3..84a7d3bf 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -281,15 +281,18 @@ message: updated-shop-users-successful: default: "&aSuccessful" pre-comment: "Text to display when shop users have been updated successfully." + updated-shop-users-failed: + default: "&cFailed" + pre-comment: "Text to display when shop users could not be added for an unknown reason." updated-shop-users-failed-capacity: default: "&cMax Capacity" - pre-comment: "Text to display when shop users have been added but the max amount of users is already on the shop." + pre-comment: "Text to display when shop users could not be added due to the shop having max user capacity." updated-shop-users-failed-existing: default: "&ePlayer Exists" - pre-comment: "Text to display when shop users have been added and the player is already on the shop." + pre-comment: "Text to display when shop users could not be added because they are already a user on the shop." updated-shop-users-failed-missing: default: "&ePlayer Missing" - pre-comment: "Text to display when shop users have been removed and the player was not on the shop." + pre-comment: "Text to display when shop users could not be removed because the user was not on the shop." who-message: default: "&6Shop users are:\n&2Owner: &e%OWNER%\n&2Managers: &e%MANAGERS%\n&2Members: &e%MEMBERS%" pre-comment: "Text to display when players use the who command" From 38f3029b835d3484f34fa4297e74d8acfc54f837 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 27 May 2022 22:48:18 -0700 Subject: [PATCH 11/53] Feature Improvement for #132 - Improvements to Setting Section comparison code(due to errors when ne ones were added) should be a lot beefier and handle any future additions without problems - Added configurable default item settings and ability to disable editing of individual item settings - Added type checking to ObjectHolder - Moved State String generation to ShopItemStack - ShopItemStack Settings are ignored if not set to UserEditable in the config(uses default setting instead) --- .../commands/commandrunners/EditCommand.java | 211 ++------------- .../commands/commandrunners/GUICommand.java | 244 +++++++++++++++++- .../commands/commandrunners/WhatCommand.java | 128 ++------- .../tradeshop/data/config/ConfigManager.java | 14 +- .../tradeshop/data/config/Setting.java | 50 +++- .../tradeshop/data/config/SettingSection.java | 16 ++ .../shanerx/tradeshop/item/ShopItemStack.java | 64 ++++- .../item/ShopItemStackSettingKeys.java | 45 ++-- .../tradeshop/utils/objects/ObjectHolder.java | 38 ++- src/main/resources/Lang/en-us.yml | 115 +++++++++ 10 files changed, 570 insertions(+), 355 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java index 93df8d5a..b9781210 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java @@ -31,25 +31,17 @@ import de.themoep.inventorygui.StaticGuiElement; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BookMeta; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.FireworkMeta; -import org.bukkit.inventory.meta.ItemMeta; import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.commands.CommandPass; import org.shanerx.tradeshop.data.config.Message; import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; -import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; import org.shanerx.tradeshop.player.Permissions; import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.player.ShopUser; import org.shanerx.tradeshop.shop.Shop; -import org.shanerx.tradeshop.utils.objects.ObjectHolder; -import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; /** @@ -64,12 +56,6 @@ public class EditCommand extends GUICommand { userEdit, costEdit, productEdit; - private List costItems, - productItems; - private List costItemsRemoval, - productItemsRemoval; - public final ItemStack TRUE_ITEM = new ItemStack(Material.EMERALD_BLOCK); - public final ItemStack FALSE_ITEM = new ItemStack(Material.REDSTONE_BLOCK); public EditCommand(TradeShop instance, CommandPass command) { @@ -102,13 +88,13 @@ public void edit() { GuiElementGroup userGroup = new GuiElementGroup('g'); // Previous page - userEdit.addElement(PREV_BUTTON); + userEdit.addElement(getPrevButton()); // Next page - userEdit.addElement(NEXT_BUTTON); + userEdit.addElement(getNextButton()); // Cancel and Back - userEdit.addElement(CANCEL_BUTTON); + userEdit.addElement(getBackButton(true)); userEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.BLUE_STAINED_GLASS_PANE), " ")); @@ -137,7 +123,7 @@ public void edit() { user.getHead(), user.getName(), "Position: MANAGER", - "Click here to change to Member."), + "Click to cycle the player to Member."), new GuiStateElement.State(change -> { shopUsers.remove(user); user.setRole(ShopRole.MEMBER); @@ -147,7 +133,7 @@ public void edit() { user.getHead(), user.getName(), "Position: MEMBER", - "Click here to remove this player."), + "Click to cycle the player to Removed."), new GuiStateElement.State(change -> { shopUsers.remove(user); user.setRole(ShopRole.SHOPPER); @@ -157,7 +143,7 @@ public void edit() { new ItemStack(Material.BARRIER), user.getName(), "Position: NONE", - "Click here to add the player as a Manager.") + "Click to cycle the player to Manager.") )); } @@ -173,22 +159,22 @@ public void edit() { mainMenu.addElement(new StaticGuiElement('b', new ItemStack(Material.GOLD_NUGGET), click -> { costEdit = new InventoryGui(plugin, "Edit Costs", EDIT_LAYOUT); - costItems = new ArrayList<>(); - costItemsRemoval = new ArrayList<>(); - for (ShopItemStack item : shop.getSideList(ShopItemSide.COST)) { - costItems.add(item.clone()); - costItemsRemoval.add(false); + if (costItems.isEmpty()) { + for (ShopItemStack item : shop.getSideList(ShopItemSide.COST)) { + costItems.add(item.clone()); + costItemsRemoval.add(false); + } } GuiElementGroup costGroup = new GuiElementGroup('g'); // Previous page - costEdit.addElement(PREV_BUTTON); + costEdit.addElement(getPrevButton()); // Next page - costEdit.addElement(NEXT_BUTTON); + costEdit.addElement(getNextButton()); // Cancel and Back - costEdit.addElement(CANCEL_BUTTON); + costEdit.addElement(getBackButton(true)); // Save and Back costEdit.addElement(new StaticGuiElement('s', new ItemStack(Material.ANVIL), click3 -> { @@ -204,7 +190,7 @@ public void edit() { costEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.YELLOW_STAINED_GLASS_PANE), " ")); for (int i = 0; i < costItems.size(); i++) { - costGroup.addElement(shopItemEditMenu(i, true)); + costGroup.addElement(itemSettingMenu(i, ShopItemSide.COST, true)); } costEdit.addElement(costGroup); @@ -214,22 +200,22 @@ public void edit() { mainMenu.addElement(new StaticGuiElement('c', new ItemStack(Material.GRASS_BLOCK), click -> { productEdit = new InventoryGui(plugin, "Edit Products", EDIT_LAYOUT); - productItems = new ArrayList<>(); - productItemsRemoval = new ArrayList<>(); - for (ShopItemStack item : shop.getSideList(ShopItemSide.PRODUCT)) { - productItems.add(item.clone()); - productItemsRemoval.add(false); + if (productItems.isEmpty()) { + for (ShopItemStack item : shop.getSideList(ShopItemSide.PRODUCT)) { + productItems.add(item.clone()); + productItemsRemoval.add(false); + } } GuiElementGroup productGroup = new GuiElementGroup('g'); // Previous page - productEdit.addElement(PREV_BUTTON); + productEdit.addElement(getPrevButton()); // Next page - productEdit.addElement(NEXT_BUTTON); + productEdit.addElement(getNextButton()); // Cancel and Back - productEdit.addElement(CANCEL_BUTTON); + productEdit.addElement(getBackButton(true)); // Save and Back productEdit.addElement(new StaticGuiElement('s', new ItemStack(Material.ANVIL), click3 -> { @@ -245,7 +231,7 @@ public void edit() { productEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.YELLOW_STAINED_GLASS_PANE), " ")); for (int i = 0; i < productItems.size(); i++) { - productGroup.addElement(shopItemEditMenu(i, false)); + productGroup.addElement(itemSettingMenu(i, ShopItemSide.PRODUCT, true)); } productEdit.addElement(productGroup); @@ -255,153 +241,4 @@ public void edit() { mainMenu.show(pSender); } - - - //region Util Methods - //------------------------------------------------------------------------------------------------------------------ - - private StaticGuiElement shopItemEditMenu(int index, boolean isCost) { - ShopItemStack item = (isCost ? costItems : productItems).get(index).clone(); - ItemStack tempStack = item.getItemStack(); - ItemMeta tempMeta = tempStack.getItemMeta(); - List newLore = new ArrayList<>(); - newLore.add(colorize("&8Amount &7» &f" + item.getAmount())); - - if (tempMeta != null && tempMeta.hasLore()) { - newLore.add(""); - newLore.addAll(tempMeta.getLore()); - } - - tempMeta.setLore(newLore); - tempStack.setItemMeta(tempMeta); - - return new StaticGuiElement('e', tempStack, click2 -> { - InventoryGui itemEdit = new InventoryGui(plugin, "Edit Cost Item", ITEM_LAYOUT); - GuiElementGroup itemGroup = new GuiElementGroup('g'); - - // Cancel and Back - itemEdit.addElement(CANCEL_BUTTON); - - // Save and Back - itemEdit.addElement(new StaticGuiElement('s', new ItemStack(Material.ANVIL), click3 -> { - (isCost ? costItems : productItems).set(index, item); - InventoryGui.goBack(pSender); - return true; - }, "Save Changes")); - - itemEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.YELLOW_STAINED_GLASS_PANE), " ")); - - itemGroup.addElement(new GuiStateElement('e', - (isCost ? costItemsRemoval : productItemsRemoval).get(index) + "", - new GuiStateElement.State(change -> (isCost ? costItemsRemoval : productItemsRemoval).set(index, true), - "true", - new ItemStack(Material.BARRIER), - item.getItemName()), - new GuiStateElement.State(change -> (isCost ? costItemsRemoval : productItemsRemoval).set(index, false), - "false", - item.getItemStack()) - - )); - - //Add new item settings below - if (item.getItemStack().getItemMeta() instanceof Damageable) { - itemGroup.addElement(numericalOption(ShopItemStackSettingKeys.COMPARE_DURABILITY, item, new ItemStack[]{ - FALSE_ITEM, new ItemStack(Material.IRON_BLOCK), TRUE_ITEM, new ItemStack(Material.GOLD_BLOCK) - })); - } - - if (tempMeta instanceof BookMeta) { - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR, item, TRUE_ITEM, FALSE_ITEM)); - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES, item, TRUE_ITEM, FALSE_ITEM)); - } - - if (tempMeta instanceof FireworkMeta) { - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_FIREWORK_DURATION, item, TRUE_ITEM, FALSE_ITEM)); - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_FIREWORK_EFFECTS, item, TRUE_ITEM, FALSE_ITEM)); - } - - if (tempStack.getType().toString().endsWith("SHULKER_BOX")) { - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY, item, TRUE_ITEM, FALSE_ITEM)); - } - - if (plugin.getVersion().isAtLeast(1, 17) && tempStack.getType().equals(Material.BUNDLE)) { - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_BUNDLE_INVENTORY, item, TRUE_ITEM, FALSE_ITEM)); - } - - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_NAME, item, TRUE_ITEM, FALSE_ITEM)); - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_LORE, item, TRUE_ITEM, FALSE_ITEM)); - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE, item, TRUE_ITEM, FALSE_ITEM)); - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS, item, TRUE_ITEM, FALSE_ITEM)); - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS, item, TRUE_ITEM, FALSE_ITEM)); - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA, item, TRUE_ITEM, FALSE_ITEM)); - itemGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER, item, TRUE_ITEM, FALSE_ITEM)); - - - itemEdit.addElement(itemGroup); - itemEdit.show(pSender); - return true; - }); - } - - private GuiStateElement numericalOption(ShopItemStackSettingKeys setting, ShopItemStack tempItem, ItemStack[] indexedTempItem) { - - return new GuiStateElement('e', - String.valueOf(tempItem.getShopSettingAsInteger(setting)), - new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(2)); - }, - "2", - indexedTempItem[3], - setting.makeReadable(), - "State: >="), - - new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(-1)); - }, - "-1", - indexedTempItem[0], - setting.makeReadable(), - "State: False"), - - new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(0)); - }, - "0", - indexedTempItem[1], - setting.makeReadable(), - "State: <="), - - new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(1)); - }, - "1", - indexedTempItem[2], - setting.makeReadable(), - "State: ==" - - )); - } - - private GuiStateElement booleanOption(ShopItemStackSettingKeys setting, ShopItemStack tempItem, ItemStack trueTempItem, ItemStack falseTempItem) { - return new GuiStateElement('e', - String.valueOf(tempItem.getShopSettingAsBoolean(setting)), - new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(true)); - }, - "true", - trueTempItem, - setting.makeReadable(), - "State: True"), - new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(false)); - }, - "false", - falseTempItem, - setting.makeReadable(), - "State: False" - )); - } - - //------------------------------------------------------------------------------------------------------------------ - //endregion } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java index ac9d044b..c4a42030 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java @@ -25,13 +25,27 @@ package org.shanerx.tradeshop.commands.commandrunners; +import de.themoep.inventorygui.GuiElement; +import de.themoep.inventorygui.GuiElementGroup; import de.themoep.inventorygui.GuiPageElement; +import de.themoep.inventorygui.GuiStateElement; import de.themoep.inventorygui.InventoryGui; import de.themoep.inventorygui.StaticGuiElement; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.inventory.meta.ItemMeta; import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.commands.CommandPass; +import org.shanerx.tradeshop.item.ShopItemSide; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; + +import java.util.ArrayList; +import java.util.List; /** * Implementation of CommandRunner for plugin commands that generate GUI screens @@ -43,20 +57,15 @@ public class GUICommand extends CommandRunner { //region Util Variables //------------------------------------------------------------------------------------------------------------------ - protected final GuiPageElement PREV_BUTTON = new GuiPageElement('p', new ItemStack(Material.POTION), GuiPageElement.PageAction.PREVIOUS, "Go to previous page (%prevpage%)"), - NEXT_BUTTON = new GuiPageElement('n', new ItemStack(Material.SPLASH_POTION), GuiPageElement.PageAction.NEXT, "Go to next page (%nextpage%)"); - protected final StaticGuiElement CANCEL_BUTTON = new StaticGuiElement('c', new ItemStack(Material.END_CRYSTAL), click3 -> { - InventoryGui.goBack(pSender); - return true; - }, "Cancel Changes"), - BACK_BUTTON = new StaticGuiElement('b', new ItemStack(Material.END_CRYSTAL), click3 -> { - InventoryGui.goBack(pSender); - return true; - }, "Back"); + protected final String[] MENU_LAYOUT = {"a b c"}, EDIT_LAYOUT = {"aggggggga", "ap c s na"}, - ITEM_LAYOUT = {"aggggggga", "aggggggga", "a cbs a"}, - WHAT_MENU = {"141125333", "1aaa2bbb3", "11p123n33"}; + ITEM_LAYOUT = {"u ggggggg", "j hhhhhhh", "ap cbs na"}, + WHAT_MENU = {"141125333", "1qqq2eee3", "11p123n33"}; + protected List costItems = new ArrayList<>(), + productItems = new ArrayList<>(); + protected List costItemsRemoval = new ArrayList<>(), + productItemsRemoval = new ArrayList<>(); //------------------------------------------------------------------------------------------------------------------ @@ -67,4 +76,215 @@ public GUICommand(TradeShop instance, CommandPass command) { } + //region Util Methods + //------------------------------------------------------------------------------------------------------------------ + + protected StaticGuiElement itemSettingMenu(int index, ShopItemSide side, boolean editable) { + ShopItemStack item = (side.equals(ShopItemSide.COST) ? costItems : productItems).get(index).clone(); + ItemStack tempStack = item.getItemStack(); + ItemMeta tempMeta = tempStack.getItemMeta(); + List newLore = new ArrayList<>(); + newLore.add(colorize("&8Amount &7» &f" + item.getAmount())); + + if (tempMeta != null && tempMeta.hasLore()) { + newLore.add(""); + newLore.addAll(tempMeta.getLore()); + } + + tempMeta.setLore(newLore); + tempStack.setItemMeta(tempMeta); + + return new StaticGuiElement('e', tempStack, click2 -> { + InventoryGui itemEdit = new InventoryGui(plugin, (editable ? "Edit " : "View ") + ((side.equals(ShopItemSide.COST) ? "Cost Item" : "Product Item")), ITEM_LAYOUT); + GuiElementGroup itemGroup = new GuiElementGroup('g'), + settingGroup = new GuiElementGroup('h'); + + // Cancel and Back + itemEdit.addElement(getBackButton(true)); + + // Save and Back + itemEdit.addElement(new StaticGuiElement('s', new ItemStack(Material.ANVIL), click3 -> { + (side.equals(ShopItemSide.COST) ? costItems : productItems).set(index, item); + InventoryGui.goBack(pSender); + return true; + }, "Save Changes")); + + itemEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.YELLOW_STAINED_GLASS_PANE), " ")); + itemEdit.addElement(getNextButton()); + itemEdit.addElement(getPrevButton()); + + itemEdit.addElement(new StaticGuiElement('u', item.getItemStack())); + if (editable) { + itemEdit.addElement(new GuiStateElement('j', + (side.equals(ShopItemSide.COST) ? costItemsRemoval : productItemsRemoval).get(index) + "", + new GuiStateElement.State(change -> (side.equals(ShopItemSide.COST) ? costItemsRemoval : productItemsRemoval).set(index, true), + "true", + getBooleanItem(false), + "Item Removed", + "Click to RE-ADD!"), + new GuiStateElement.State(change -> (side.equals(ShopItemSide.COST) ? costItemsRemoval : productItemsRemoval).set(index, false), + "false", + getBooleanItem(true), + "Item Valid", + "Click to REMOVE!") + + )); + } else { + itemEdit.addElement(new StaticGuiElement('j', getBooleanItem(true), "Item Valid", " ")); + } + + + //Add new item settings below + if (item.getItemStack().getItemMeta() instanceof Damageable) { + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_DURABILITY, item)); + settingGroup.addElement(numericalOption(ShopItemStackSettingKeys.COMPARE_DURABILITY, item, editable)); + } + + if (tempMeta instanceof BookMeta) { + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR, item, editable)); + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES, item, editable)); + } + + if (tempMeta instanceof FireworkMeta) { + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_FIREWORK_DURATION, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_FIREWORK_DURATION, item, editable)); + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_FIREWORK_EFFECTS, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_FIREWORK_EFFECTS, item, editable)); + } + + if (tempStack.getType().toString().endsWith("SHULKER_BOX")) { + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY, item, editable)); + } + + if (plugin.getVersion().isAtLeast(1, 17) && tempStack.getType().equals(Material.BUNDLE)) { + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_BUNDLE_INVENTORY, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_BUNDLE_INVENTORY, item, editable)); + } + + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_NAME, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_NAME, item, editable)); + + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_LORE, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_LORE, item, editable)); + + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE, item, editable)); + + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS, item, editable)); + + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS, item, editable)); + + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA, item, editable)); + + itemGroup.addElement(settingDisplayItem(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER, item)); + settingGroup.addElement(booleanOption(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER, item, editable)); + + + itemEdit.addElement(itemGroup); + itemEdit.addElement(settingGroup); + itemEdit.show(pSender); + return true; + }); + } + + private GuiElement numericalOption(ShopItemStackSettingKeys setting, ShopItemStack tempItem, boolean editable) { + ItemStack[] indexedTempItem = new ItemStack[]{getBooleanItem(false), new ItemStack(Material.IRON_BLOCK), getBooleanItem(true), new ItemStack(Material.GOLD_BLOCK)}; + + if (setting.isUserEditable() && editable) { + return new GuiStateElement('e', + String.valueOf(tempItem.getShopSettingAsInteger(setting)), + new GuiStateElement.State(change -> { + tempItem.setShopSettings(setting, new ObjectHolder<>(2)); + }, + "2", + indexedTempItem[3], + setting.makeReadable(), + tempItem.getStateString(new ObjectHolder<>(2))), + + new GuiStateElement.State(change -> { + tempItem.setShopSettings(setting, new ObjectHolder<>(-1)); + }, + "-1", + indexedTempItem[0], + setting.makeReadable(), + tempItem.getStateString(new ObjectHolder<>(-1))), + + new GuiStateElement.State(change -> { + tempItem.setShopSettings(setting, new ObjectHolder<>(0)); + }, + "0", + indexedTempItem[1], + setting.makeReadable(), + tempItem.getStateString(new ObjectHolder<>(0))), + + new GuiStateElement.State(change -> { + tempItem.setShopSettings(setting, new ObjectHolder<>(1)); + }, + "1", + indexedTempItem[2], + setting.makeReadable(), + tempItem.getStateString(new ObjectHolder<>(1)) + + )); + } + + return new StaticGuiElement('e', indexedTempItem[tempItem.getShopSettingAsInteger(setting) + 1], setting.makeReadable(), tempItem.getStateString(setting)); + } + + private GuiElement booleanOption(ShopItemStackSettingKeys setting, ShopItemStack tempItem, boolean editable) { + if (setting.isUserEditable() && editable) { + return new GuiStateElement('e', + String.valueOf(tempItem.getShopSettingAsBoolean(setting)), + new GuiStateElement.State(change -> { + tempItem.setShopSettings(setting, new ObjectHolder<>(true)); + }, + "true", + getBooleanItem(true), + setting.makeReadable(), + tempItem.getStateString(new ObjectHolder<>(true)) + ), + new GuiStateElement.State(change -> { + tempItem.setShopSettings(setting, new ObjectHolder<>(false)); + }, + "false", + getBooleanItem(false), + setting.makeReadable(), + tempItem.getStateString(new ObjectHolder<>(false)) + )); + } + + return new StaticGuiElement('e', tempItem.getShopSettingAsBoolean(setting) ? getBooleanItem(true) : getBooleanItem(false), setting.makeReadable(), tempItem.getStateString(setting)); + } + + private StaticGuiElement settingDisplayItem(ShopItemStackSettingKeys setting, ShopItemStack tempItem) { + return new StaticGuiElement('e', setting.getDisplayItem(), setting.makeReadable(), tempItem.getStateString(setting)); + } + + protected GuiElement getPrevButton() { + return new GuiPageElement('p', new ItemStack(Material.POTION), GuiPageElement.PageAction.PREVIOUS, "Go to previous page (%prevpage%)", " "); + } + + protected GuiElement getNextButton() { + return new GuiPageElement('n', new ItemStack(Material.SPLASH_POTION), GuiPageElement.PageAction.NEXT, "Go to next page (%nextpage%)", " "); + } + + protected GuiElement getBackButton(boolean asCancel) { + return new StaticGuiElement(asCancel ? 'c' : 'b', new ItemStack(Material.END_CRYSTAL), click3 -> { + InventoryGui.goBack(pSender); + return true; + }, asCancel ? "Cancel Changes" : "Back"); + } + + protected ItemStack getBooleanItem(boolean item) { + return item ? new ItemStack(Material.EMERALD_BLOCK) : new ItemStack(Material.REDSTONE_BLOCK); + } + + //------------------------------------------------------------------------------------------------------------------ + //endregion } diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java index 574a6913..f2f38752 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java @@ -31,23 +31,16 @@ import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BookMeta; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.commands.CommandPass; import org.shanerx.tradeshop.data.config.Message; import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; -import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; import org.shanerx.tradeshop.player.Permissions; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shop.ShopType; -import java.util.ArrayList; -import java.util.List; - /** * Implementation of GUICommand for the `what` command * @@ -78,16 +71,29 @@ public void what() { Bukkit.getOfflinePlayer(shop.getOwner().getUUID()).getName() + "'s Shop"), WHAT_MENU); - GuiElementGroup costGroup = new GuiElementGroup('a'), productGroup = new GuiElementGroup('b'); + GuiElementGroup costGroup = new GuiElementGroup('q'), productGroup = new GuiElementGroup('e'); gui.setFiller(new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1)); - for (ShopItemStack item : shop.getSideList(ShopItemSide.COST)) { - costGroup.addElement(shopitemViewMenu(item)); + if (costItems.isEmpty()) { + for (ShopItemStack item : shop.getSideList(ShopItemSide.COST)) { + costItems.add(item.clone()); + } + } + + if (productItems.isEmpty()) { + for (ShopItemStack item : shop.getSideList(ShopItemSide.PRODUCT)) { + productItems.add(item.clone()); + } + } + + + for (int i = 0; i < costItems.size(); i++) { + costGroup.addElement(itemSettingMenu(i, ShopItemSide.COST, false)); } - for (ShopItemStack item : shop.getSideList(ShopItemSide.PRODUCT)) { - productGroup.addElement(shopitemViewMenu(item)); + for (int i = 0; i < productItems.size(); i++) { + productGroup.addElement(itemSettingMenu(i, ShopItemSide.PRODUCT, false)); } gui.addElement(new StaticGuiElement('1', new ItemStack(Material.LIME_STAINED_GLASS_PANE), @@ -100,105 +106,11 @@ public void what() { "Cost", "This is the item", "that you give to", "make the trade.")); gui.addElement(new StaticGuiElement('5', new ItemStack(Material.GRASS_BLOCK), "Product", "This is the item", "that you receive", "from the trade.")); - gui.addElement(PREV_BUTTON); - gui.addElement(NEXT_BUTTON); + gui.addElement(getPrevButton()); + gui.addElement(getNextButton()); gui.addElement(costGroup); gui.addElement(productGroup); gui.show(pSender); } - - - //region Util Methods - //------------------------------------------------------------------------------------------------------------------ - - private ItemStack settingItem(boolean state) { - return state ? new ItemStack(Material.EMERALD_BLOCK) : new ItemStack(Material.REDSTONE_BLOCK); - } - - private ItemStack settingItem(int state) { - switch (state) { - case -1: - return new ItemStack(Material.REDSTONE_BLOCK); - case 0: - return new ItemStack(Material.IRON_BLOCK); - case 1: - default: - return new ItemStack(Material.EMERALD_BLOCK); - case 2: - return new ItemStack(Material.GOLD_BLOCK); - } - } - - private String stateText(int state) { - switch (state) { - case -1: - return "False"; - case 0: - return "<="; - case 1: - default: - return "=="; - case 2: - return ">="; - } - } - - private StaticGuiElement shopitemViewMenu(ShopItemStack item) { - ItemStack tempStack = item.getItemStack().clone(); - ItemMeta tempMeta = tempStack.getItemMeta(); - List newLore = new ArrayList<>(); - newLore.add("Amount: " + item.getAmount()); - - if (tempMeta != null && tempMeta.hasLore()) { - newLore.add(""); - newLore.addAll(tempMeta.getLore()); - } - - tempMeta.setLore(newLore); - tempStack.setItemMeta(tempMeta); - return new StaticGuiElement('e', tempStack, click2 -> { - InventoryGui itemView = new InventoryGui(plugin, "Edit Cost Item", ITEM_LAYOUT); - GuiElementGroup itemGroup = new GuiElementGroup('g'); - - itemView.addElement(BACK_BUTTON); - - itemView.addElement(new StaticGuiElement('a', new ItemStack(Material.BLACK_STAINED_GLASS_PANE), " ")); - - itemGroup.addElement(new StaticGuiElement('e', tempStack)); - - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_NAME)), "Compare Name", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_NAME))); - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_LORE)), "Compare Lore", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_LORE))); - - if (item.getItemStack().getType().toString().endsWith("SHULKER_BOX")) { - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY)), "Compare Shulker Inventory", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY))); - } - - if (item.getItemStack().getItemMeta() instanceof Damageable) { - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsInteger(ShopItemStackSettingKeys.COMPARE_DURABILITY)), "Compare Durability", "State: " + stateText(item.getShopSettingAsInteger(ShopItemStackSettingKeys.COMPARE_DURABILITY)))); - } - - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS)), "Compare Enchantments", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS))); - - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE)), "Compare Unbreakable", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE))); - - if (item.getItemStack().getItemMeta() instanceof BookMeta) { - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR)), "Compare Book Author", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR))); - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES)), "Compare Book Pages", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES))); - } - - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS)), "Compare Item Flags", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS))); - - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA)), "Compare Custom Model Data", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA))); - - itemGroup.addElement(new StaticGuiElement('e', settingItem(item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER)), "Compare Attribute Modifier", "State: " + item.getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER))); - - itemView.addElement(itemGroup); - itemView.show(pSender); - return true; - }); - } - - //------------------------------------------------------------------------------------------------------------------ - //endregion } diff --git a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java index 0c7e7294..6f110e4b 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java @@ -212,7 +212,12 @@ public int compare(SettingSection o1, SettingSection o2) { // if o1's parent is o2 then o2 goes first } else if (o1.getParent() == o2) { return 1; - // if neither of the above are true and one Section has a parent and the other doesn't, then the one without the parent goes first + // if neither is the parent of the other but one Section has a parent and the other doesn't + } else if (o1.hasParent() != o2.hasParent()) { + return o1.hasParent() ? compare(o1.getParent(), o2) : compare(o1, o2.getParent()); // compare existing parent to other section + // if both have parents but they aren't the same parent + } else if (o1.getParent() != null && !o1.getParent().equals(o2.getParent())) { + return compare(o1.getParent(), o2.getParent()); // compare the parents of both } // Otherwise, compare weight @@ -229,9 +234,12 @@ public int compare(MessageSection o1, MessageSection o2) { // if o1's parent is o2 then o2 goes first } else if (o1.getParent() == o2) { return 1; - // if neither of the above are true and one Section has a parent and the other doesn't, then the one without the parent goes first + // if neither is the parent of the other but one Section has a parent and the other doesn't } else if (o1.hasParent() != o2.hasParent()) { - return o1.hasParent() ? 1 : -1; + return o1.hasParent() ? compare(o1.getParent(), o2) : compare(o1, o2.getParent()); // compare existing parent to other section + // if both have parents but they aren't the same parent + } else if (o1.getParent() != null && !o1.getParent().equals(o2.getParent())) { + return compare(o1.getParent(), o2.getParent()); // compare the parents of both } // Otherwise, compare weight diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 2557e63a..efc2ed42 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -74,14 +74,6 @@ public enum Setting { MULTI_TRADE_DEFAULT(SettingSection.GLOBAL_MULTI_TRADE, "default-multi", 2), MULTI_TRADE_MAX(SettingSection.GLOBAL_MULTI_TRADE, "max-multi", 6), - // Illegal Item Options - GLOBAL_ILLEGAL_ITEMS_TYPE(SettingSection.GLOBAL_ILLEGAL_ITEMS, "type", IllegalItemList.ListType.BLACKLIST.toString()), - GLOBAL_ILLEGAL_ITEMS_LIST(SettingSection.GLOBAL_ILLEGAL_ITEMS, "list", new String[]{"Bedrock", "Command_Block", "Barrier"}), - COST_ILLEGAL_ITEMS_TYPE(SettingSection.COST_ILLEGAL_ITEMS, "type", IllegalItemList.ListType.DISABLED.toString()), - COST_ILLEGAL_ITEMS_LIST(SettingSection.COST_ILLEGAL_ITEMS, "list", new String[]{}), - PRODUCT_ILLEGAL_ITEMS_TYPE(SettingSection.PRODUCT_ILLEGAL_ITEMS, "type", IllegalItemList.ListType.DISABLED.toString()), - PRODUCT_ILLEGAL_ITEMS_LIST(SettingSection.PRODUCT_ILLEGAL_ITEMS, "list", new String[]{}), - // Shop Options MAX_SHOP_USERS(SettingSection.SHOP_OPTIONS, "max-shop-users", 5), MAX_SHOPS_PER_CHUNK(SettingSection.SHOP_OPTIONS, "max-shops-per-chunk", 128), @@ -89,6 +81,38 @@ public enum Setting { ALLOW_USER_PURCHASING(SettingSection.SHOP_OPTIONS, "allow-user-purchasing", false), MULTIPLE_ITEMS_ON_SIGN(SettingSection.SHOP_OPTIONS, "multiple-items-on-sign", "Use '/ts what'"), + //Shop Item Default Setting Options + COMPARE_DURABILITY_DEFAULT(SettingSection.COMPARE_DURABILITY, "default", 1), + COMPARE_ENCHANTMENTS_DEFAULT(SettingSection.COMPARE_ENCHANTMENTS, "default", true), + COMPARE_NAME_DEFAULT(SettingSection.COMPARE_NAME, "default", true), + COMPARE_LORE_DEFAULT(SettingSection.COMPARE_LORE, "default", true), + COMPARE_CUSTOM_MODEL_DATA_DEFAULT(SettingSection.COMPARE_CUSTOM_MODEL_DATA, "default", true), + COMPARE_ITEM_FLAGS_DEFAULT(SettingSection.COMPARE_ITEM_FLAGS, "default", true), + COMPARE_UNBREAKABLE_DEFAULT(SettingSection.COMPARE_UNBREAKABLE, "default", true), + COMPARE_ATTRIBUTE_MODIFIER_DEFAULT(SettingSection.COMPARE_ATTRIBUTE_MODIFIER, "default", true), + COMPARE_BOOK_AUTHOR_DEFAULT(SettingSection.COMPARE_BOOK_AUTHOR, "default", true), + COMPARE_BOOK_PAGES_DEFAULT(SettingSection.COMPARE_BOOK_PAGES, "default", true), + COMPARE_SHULKER_INVENTORY_DEFAULT(SettingSection.COMPARE_SHULKER_INVENTORY, "default", true), + COMPARE_BUNDLE_INVENTORY_DEFAULT(SettingSection.COMPARE_BUNDLE_INVENTORY, "default", true), + COMPARE_FIREWORK_DURATION_DEFAULT(SettingSection.COMPARE_FIREWORK_DURATION, "default", true), + COMPARE_FIREWORK_EFFECTS_DEFAULT(SettingSection.COMPARE_FIREWORK_EFFECTS, "default", true), + + //Shop Item Setting User Editable Options + COMPARE_DURABILITY_USER_EDITABLE(SettingSection.COMPARE_DURABILITY, "user-editable", true), + COMPARE_ENCHANTMENTS_USER_EDITABLE(SettingSection.COMPARE_ENCHANTMENTS, "user-editable", true), + COMPARE_NAME_USER_EDITABLE(SettingSection.COMPARE_NAME, "user-editable", true), + COMPARE_LORE_USER_EDITABLE(SettingSection.COMPARE_LORE, "user-editable", true), + COMPARE_CUSTOM_MODEL_DATA_USER_EDITABLE(SettingSection.COMPARE_CUSTOM_MODEL_DATA, "user-editable", true), + COMPARE_ITEM_FLAGS_USER_EDITABLE(SettingSection.COMPARE_ITEM_FLAGS, "user-editable", true), + COMPARE_UNBREAKABLE_USER_EDITABLE(SettingSection.COMPARE_UNBREAKABLE, "user-editable", true), + COMPARE_ATTRIBUTE_MODIFIER_USER_EDITABLE(SettingSection.COMPARE_ATTRIBUTE_MODIFIER, "user-editable", true), + COMPARE_BOOK_AUTHOR_USER_EDITABLE(SettingSection.COMPARE_BOOK_AUTHOR, "user-editable", true), + COMPARE_BOOK_PAGES_USER_EDITABLE(SettingSection.COMPARE_BOOK_PAGES, "user-editable", true), + COMPARE_SHULKER_INVENTORY_USER_EDITABLE(SettingSection.COMPARE_SHULKER_INVENTORY, "user-editable", true), + COMPARE_BUNDLE_INVENTORY_USER_EDITABLE(SettingSection.COMPARE_BUNDLE_INVENTORY, "user-editable", true), + COMPARE_FIREWORK_DURATION_USER_EDITABLE(SettingSection.COMPARE_FIREWORK_DURATION, "user-editable", true), + COMPARE_FIREWORK_EFFECTS_USER_EDITABLE(SettingSection.COMPARE_FIREWORK_EFFECTS, "user-editable", true), + // Trade Shop Options TRADESHOP_HEADER(SettingSection.TRADE_SHOP_OPTIONS, "header", "Trade"), TRADESHOP_EXPLODE(SettingSection.TRADE_SHOP_OPTIONS, "allow-explode", false), @@ -106,7 +130,15 @@ public enum Setting { BITRADESHOP_HEADER(SettingSection.BITRADE_SHOP_OPTIONS, "header", "BiTrade"), BITRADESHOP_EXPLODE(SettingSection.BITRADE_SHOP_OPTIONS, "allow-explode", false), BITRADESHOP_HOPPER_EXPORT(SettingSection.BITRADE_SHOP_OPTIONS, "allow-hopper-export", false), - BITRADESHOP_HOPPER_IMPORT(SettingSection.BITRADE_SHOP_OPTIONS, "allow-hopper-import", false); + BITRADESHOP_HOPPER_IMPORT(SettingSection.BITRADE_SHOP_OPTIONS, "allow-hopper-import", false), + + // Illegal Item Options + GLOBAL_ILLEGAL_ITEMS_TYPE(SettingSection.GLOBAL_ILLEGAL_ITEMS, "type", IllegalItemList.ListType.BLACKLIST.toString()), + GLOBAL_ILLEGAL_ITEMS_LIST(SettingSection.GLOBAL_ILLEGAL_ITEMS, "list", new String[]{"Bedrock", "Command_Block", "Barrier"}), + COST_ILLEGAL_ITEMS_TYPE(SettingSection.COST_ILLEGAL_ITEMS, "type", IllegalItemList.ListType.DISABLED.toString()), + COST_ILLEGAL_ITEMS_LIST(SettingSection.COST_ILLEGAL_ITEMS, "list", new String[]{}), + PRODUCT_ILLEGAL_ITEMS_TYPE(SettingSection.PRODUCT_ILLEGAL_ITEMS, "type", IllegalItemList.ListType.DISABLED.toString()), + PRODUCT_ILLEGAL_ITEMS_LIST(SettingSection.PRODUCT_ILLEGAL_ITEMS, "list", new String[]{}); public static final TradeShop PLUGIN = Objects.requireNonNull((TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop")); diff --git a/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java index 84c0a62f..6bedaf7d 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java @@ -38,6 +38,22 @@ public enum SettingSection { GLOBAL_OPTIONS(3, "global-options"), GLOBAL_MULTI_TRADE(0, GLOBAL_OPTIONS, "multi-trade"), SHOP_OPTIONS(4, "shop-options"), + SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS(0, SHOP_OPTIONS, "shop-item-default-settings-options"), + COMPARE_DURABILITY(0, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-durability"), + COMPARE_ENCHANTMENTS(1, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-enchantments"), + COMPARE_NAME(2, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-name"), + COMPARE_LORE(3, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-lore"), + COMPARE_CUSTOM_MODEL_DATA(4, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-custom-data-model"), + COMPARE_ITEM_FLAGS(5, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-item-flags"), + COMPARE_UNBREAKABLE(6, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-unbreakable"), + COMPARE_ATTRIBUTE_MODIFIER(7, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-attribute-modifier"), + COMPARE_BOOK_AUTHOR(8, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-book-author"), + COMPARE_BOOK_PAGES(9, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-book-pages"), + COMPARE_SHULKER_INVENTORY(10, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-shulker-inventory"), + COMPARE_BUNDLE_INVENTORY(11, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-bundle-inventory"), + COMPARE_FIREWORK_DURATION(12, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-firework-duration"), + COMPARE_FIREWORK_EFFECTS(13, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-firework-effects"), + TRADE_SHOP_OPTIONS(6, "trade-shop-options"), ITRADE_SHOP_OPTIONS(7, "itrade-shop-options"), BITRADE_SHOP_OPTIONS(8, "bitrade-shop-options"), diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index 7db0e2a1..cf6cf229 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -132,21 +132,26 @@ public static ShopItemStack deserialize(String serialized) { } public boolean getShopSettingAsBoolean(ShopItemStackSettingKeys key) { - try { - ObjectHolder tempObj = shopSettings.get(key); - return shopSettings.containsKey(key) ? (Boolean) tempObj.getObject() : (Boolean) key.getDefaultValue().getObject(); - } catch (ClassCastException | NullPointerException e) { - return (Boolean) key.getDefaultValue().getObject(); + if (key.isUserEditable()) { + try { + ObjectHolder tempObj = shopSettings.get(key); + return shopSettings.containsKey(key) ? (Boolean) tempObj.getObject() : (Boolean) key.getDefaultValue().getObject(); + } catch (ClassCastException | NullPointerException ignored) { + } } + return (Boolean) key.getDefaultValue().getObject(); } public int getShopSettingAsInteger(ShopItemStackSettingKeys key) { - try { - ObjectHolder tempObj = shopSettings.get(key); - return shopSettings.containsKey(key) ? (Integer) tempObj.getObject() : (Integer) key.getDefaultValue().getObject(); - } catch (ClassCastException | NullPointerException e) { - return (Integer) key.getDefaultValue().getObject(); + if (key.isUserEditable()) { + try { + ObjectHolder tempObj = shopSettings.get(key); + return shopSettings.containsKey(key) ? (Integer) tempObj.getObject() : (Integer) key.getDefaultValue().getObject(); + } catch (ClassCastException | NullPointerException ignored) { + } } + + return (Integer) key.getDefaultValue().getObject(); } private void buildMap() { @@ -510,6 +515,45 @@ public String getCleanItemName() { return ShopItemStack.getCleanItemName(itemStack); } + public String getStateString(ShopItemStackSettingKeys key) { + return getStateString(shopSettings.get(key)); + } + + public String getStateString(ObjectHolder stateSetting) { + try { + String ret = ""; + if (stateSetting.isBoolean()) { + if ((Boolean) stateSetting.getObject()) { + ret = "True"; + } else { + ret = "False"; + } + } else if (stateSetting.isInteger() || stateSetting.isDouble()) { + switch (stateSetting.isDouble() ? ((Double) stateSetting.getObject()).intValue() : (Integer) stateSetting.getObject()) { + case 2: + ret = ">="; + break; + case 1: + ret = "=="; + break; + case 0: + ret = "<="; + break; + case -1: + default: + ret = "False"; + } + } + + if (ret.length() < 2) + ret = "Unknown"; + + return "State: " + ret; + } catch (ClassCastException ex) { + return "State: ERROR"; + } + } + public String serialize() { return new Gson().toJson(this); } diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java index 09d0c312..08148492 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java @@ -25,31 +25,38 @@ package org.shanerx.tradeshop.item; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.utils.objects.ObjectHolder; public enum ShopItemStackSettingKeys { //New per shop settings and their default value should be added below and will be added to the shops - COMPARE_DURABILITY(new ObjectHolder<>(1)), // -1 == 'off', 0 == '<=', 1 == '==', 2 == '>=' - COMPARE_ENCHANTMENTS(new ObjectHolder<>(true)), - COMPARE_NAME(new ObjectHolder<>(true)), - COMPARE_LORE(new ObjectHolder<>(true)), - COMPARE_CUSTOM_MODEL_DATA(new ObjectHolder<>(true)), - COMPARE_ITEM_FLAGS(new ObjectHolder<>(true)), - COMPARE_UNBREAKABLE(new ObjectHolder<>(true)), - COMPARE_ATTRIBUTE_MODIFIER(new ObjectHolder<>(true)), - COMPARE_BOOK_AUTHOR(new ObjectHolder<>(true)), - COMPARE_BOOK_PAGES(new ObjectHolder<>(true)), - COMPARE_SHULKER_INVENTORY(new ObjectHolder<>(true)), - COMPARE_BUNDLE_INVENTORY(new ObjectHolder<>(true)), - COMPARE_FIREWORK_DURATION(new ObjectHolder<>(true)), - COMPARE_FIREWORK_EFFECTS(new ObjectHolder<>(true)); + COMPARE_DURABILITY(new ObjectHolder<>(Setting.COMPARE_DURABILITY_DEFAULT.getInt()), new ItemStack(Material.DAMAGED_ANVIL)), // -1 == 'off', 0 == '<=', 1 == '==', 2 == '>=' + COMPARE_ENCHANTMENTS(new ObjectHolder<>(Setting.COMPARE_ENCHANTMENTS_DEFAULT.getBoolean()), new ItemStack(Material.ENCHANTED_BOOK)), + COMPARE_NAME(new ObjectHolder<>(Setting.COMPARE_NAME_DEFAULT.getBoolean()), new ItemStack(Material.NAME_TAG)), + COMPARE_LORE(new ObjectHolder<>(Setting.COMPARE_LORE_DEFAULT.getBoolean()), new ItemStack(Material.BOOK)), + COMPARE_CUSTOM_MODEL_DATA(new ObjectHolder<>(Setting.COMPARE_CUSTOM_MODEL_DATA_DEFAULT.getBoolean()), new ItemStack(Material.STICK)), + COMPARE_ITEM_FLAGS(new ObjectHolder<>(Setting.COMPARE_ITEM_FLAGS_DEFAULT.getBoolean()), new ItemStack(Material.WHITE_BANNER)), + COMPARE_UNBREAKABLE(new ObjectHolder<>(Setting.COMPARE_UNBREAKABLE_DEFAULT.getBoolean()), new ItemStack(Material.BEDROCK)), + COMPARE_ATTRIBUTE_MODIFIER(new ObjectHolder<>(Setting.COMPARE_ATTRIBUTE_MODIFIER_DEFAULT.getBoolean()), new ItemStack(Material.BARRIER)), + COMPARE_BOOK_AUTHOR(new ObjectHolder<>(Setting.COMPARE_BOOK_AUTHOR_DEFAULT.getBoolean()), new ItemStack(Material.PLAYER_HEAD)), + COMPARE_BOOK_PAGES(new ObjectHolder<>(Setting.COMPARE_BOOK_PAGES_DEFAULT.getBoolean()), new ItemStack(Material.PAPER)), + COMPARE_SHULKER_INVENTORY(new ObjectHolder<>(Setting.COMPARE_SHULKER_INVENTORY_DEFAULT.getBoolean()), new ItemStack(Material.CHEST_MINECART)), + COMPARE_BUNDLE_INVENTORY(new ObjectHolder<>(Setting.COMPARE_BUNDLE_INVENTORY_DEFAULT.getBoolean()), new ItemStack(Material.CHEST_MINECART)), + COMPARE_FIREWORK_DURATION(new ObjectHolder<>(Setting.COMPARE_FIREWORK_DURATION_DEFAULT.getBoolean()), new ItemStack(Material.GUNPOWDER)), + COMPARE_FIREWORK_EFFECTS(new ObjectHolder<>(Setting.COMPARE_FIREWORK_EFFECTS_DEFAULT.getBoolean()), new ItemStack(Material.FIREWORK_STAR)); private final ObjectHolder defaultValue; + private final boolean userEditable; + private final ItemStack displayItem; - ShopItemStackSettingKeys(ObjectHolder defaultValue) { + ShopItemStackSettingKeys(ObjectHolder defaultValue, ItemStack displayItem) { this.defaultValue = defaultValue; + this.userEditable = Setting.findSetting(this.name() + "_USER_EDITABLE").getBoolean(); + this.displayItem = displayItem; } public ObjectHolder getDefaultValue() { @@ -77,4 +84,12 @@ else if (ch == '_') return ret.toString().trim(); } + + public boolean isUserEditable() { + return userEditable; + } + + public ItemStack getDisplayItem() { + return displayItem; + } } diff --git a/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java index 084e7b2d..037481e5 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java @@ -27,18 +27,34 @@ public class ObjectHolder { - private final Type obj; + private final Type obj; - public ObjectHolder(Type obj) { - this.obj = obj; - } + public ObjectHolder(Type obj) { + this.obj = obj; + } - public Type getObject() { - return obj; - } + public Type getObject() { + return obj; + } - @Override - public String toString() { - return obj.toString(); - } + public boolean isBoolean() { + return obj instanceof Boolean; + } + + public boolean isInteger() { + return obj instanceof Integer; + } + + public boolean isDouble() { + return obj instanceof Double; + } + + public boolean isString() { + return obj instanceof String; + } + + @Override + public String toString() { + return obj.toString(); + } } diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 84a7d3bf..69ed1666 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -16,6 +16,50 @@ setting-section: header: "" shop-options: header: "Shop Options" + shop-item-default-settings-options: + header: "Shop Item Default Settings Options" + compare-durability: + header: "" + pre-comment: "Compare Durability" + compare-enchantments: + header: "" + pre-comment: "Compare Enchantments" + compare-name: + header: "" + pre-comment: "Compare Name" + compare-lore: + header: "" + pre-comment: "Compare Lore" + compare-custom-data-model: + header: "" + pre-comment: "Compare Custom Data Model" + compare-item-flags: + header: "" + pre-comment: "Compare Item Flags" + compare-unbreakable: + header: "" + pre-comment: "Compare Unbreakable" + compare-attribute-modifier: + header: "" + pre-comment: "Compare Attribute Modifier" + compare-book-author: + header: "" + pre-comment: "Compare Book Author" + compare-book-pages: + header: "" + pre-comment: "Compare Book Pages" + compare-shulker-inventory: + header: "" + pre-comment: "Compare Shulker Inventory" + compare-bundle-inventory: + header: "" + pre-comment: "Compare Bundle Inventory" + compare-firework-duration: + header: "" + pre-comment: "Compare Firework Duration" + compare-firework-effects: + header: "" + pre-comment: "Compare Firework Effects" trade-shop-options: header: "Trade Shop Options" itrade-shop-options: @@ -126,6 +170,77 @@ setting: multiple-items-on-sign: pre-comment: "Text that shows on trade signs that contain more than 1 item\n Available variables are: %AMOUNT%" post-comment: "\n" + shop-item-default-settings-options: + compare-durability: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-enchantments: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-name: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-lore: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-custom-data-model: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-item-flags: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-unbreakable: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-attribute-modifier: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-book-author: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-book-pages: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-shulker-inventory: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-bundle-inventory: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-firework-duration: + default: + pre-comment: "" + user-editable: + pre-comment: "" + compare-firework-effects: + default: + pre-comment: "" + user-editable: + pre-comment: "" trade-shop-options: header: pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" From 7e721920859aea17e7691edbfc78d6b4ae7171c4 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Sat, 28 May 2022 16:53:21 -0700 Subject: [PATCH 12/53] Bug Fix for #134 - Moved #createShop to Utils - Made #createShop more generic so sign creation and commands could both use it - Added SHOP_CREATION Debug Level at bit 11(1024) - Added toDebug method to Shop to allow a easily readable output of the shop - Re-wrote updateSign methods to make them simpler to understand and allow sign/event passing from #createShop - Removed event storing and related methods from Shop as it was unnecessary - Deprecated #b64OverstackFixer since it is only used in legacy code - Fixed some spelling in comments(the green underlines were bothering me) - Removed unused `failed` methods from Utils --- .../commandrunners/CreateCommand.java | 86 +---------- .../data/storage/Json/ShopConfiguration.java | 8 + .../java/org/shanerx/tradeshop/shop/Shop.java | 112 +++++++++----- .../shop/listeners/ShopCreateListener.java | 83 +--------- .../tradeshop/shoplocation/ShopLocation.java | 2 +- .../org/shanerx/tradeshop/utils/Utils.java | 146 +++++++++++++++--- .../tradeshop/utils/debug/DebugLevels.java | 3 +- 7 files changed, 213 insertions(+), 227 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CreateCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CreateCommand.java index 3572750c..c0b0b793 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CreateCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CreateCommand.java @@ -25,21 +25,13 @@ package org.shanerx.tradeshop.commands.commandrunners; -import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.commands.CommandPass; import org.shanerx.tradeshop.data.config.Message; import org.shanerx.tradeshop.data.config.Setting; -import org.shanerx.tradeshop.framework.events.PlayerShopCreateEvent; -import org.shanerx.tradeshop.item.ShopItemSide; -import org.shanerx.tradeshop.player.ShopRole; -import org.shanerx.tradeshop.player.ShopUser; -import org.shanerx.tradeshop.shop.Shop; -import org.shanerx.tradeshop.shop.ShopChest; import org.shanerx.tradeshop.shop.ShopType; -import org.shanerx.tradeshop.utils.objects.Tuple; /** * Implementation of CommandRunner for plugin commands that create new shops @@ -61,7 +53,7 @@ public void createTrade() { if (sign == null) return; - createShop(sign, ShopType.TRADE); + createShop(sign, pSender, ShopType.TRADE); } /** @@ -73,7 +65,7 @@ public void createBiTrade() { if (sign == null) return; - createShop(sign, ShopType.BITRADE); + createShop(sign, pSender, ShopType.BITRADE); } /** @@ -85,81 +77,9 @@ public void createITrade() { if (sign == null) return; - createShop(sign, ShopType.ITRADE); + createShop(sign, pSender, ShopType.ITRADE); } - - /** - * Create a shop from a non-shop sign in front of the player - * - * @param shopSign sign to make into a shop - * @param shopType type of shop to make - */ - private void createShop(Sign shopSign, ShopType shopType) { - if (ShopType.isShop(shopSign)) { - Message.EXISTING_SHOP.sendMessage(pSender); - return; - } - - ShopUser owner = new ShopUser(pSender, ShopRole.OWNER); - - if (!checkShopChest(shopSign.getBlock()) && !shopType.isITrade()) { - Message.NO_CHEST.sendMessage(pSender); - return; - } - - if (Setting.MAX_SHOPS_PER_CHUNK.getInt() <= plugin.getDataStorage().getShopCountInChunk(shopSign.getChunk())) { - Message.TOO_MANY_CHESTS.sendMessage(pSender); - return; - } - - ShopChest shopChest; - Shop shop; - Block chest = findShopChest(shopSign.getBlock()); - - if (!shopType.isITrade()) { - if (ShopChest.isShopChest(chest)) { - shopChest = new ShopChest(chest.getLocation()); - } else { - shopChest = new ShopChest(chest, pSender.getUniqueId(), shopSign.getLocation()); - } - - if (shopChest.hasOwner() && !shopChest.getOwner().equals(owner.getUUID())) { - Message.NO_SHOP_PERMISSION.sendMessage(pSender); - return; - } - - if (shopChest.hasShopSign() && !shopChest.getShopSign().getLocation().equals(shopSign.getLocation())) { - Message.EXISTING_SHOP.sendMessage(pSender); - return; - } - - shop = new Shop(new Tuple<>(shopSign.getLocation(), shopChest.getChest().getLocation()), shopType, owner); - shopChest.setName(); - - - if (shopChest.isEmpty() && shop.hasSide(ShopItemSide.PRODUCT)) { - Message.EMPTY_TS_ON_SETUP.sendMessage(pSender); - } - } else { - shop = new Shop(shopSign.getLocation(), shopType, owner); - } - - PlayerShopCreateEvent shopCreateEvent = new PlayerShopCreateEvent(pSender, shop); - Bukkit.getPluginManager().callEvent(shopCreateEvent); - if (shopCreateEvent.isCancelled()) { - return; - } - - shopSign.setLine(0, shopType.toHeader()); - shopSign.update(); - - shop.saveShop(); - - Message.SUCCESSFUL_SETUP.sendMessage(pSender); - } - - //region Util Methods //------------------------------------------------------------------------------------------------------------------ diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java index 57160746..26232c78 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java @@ -126,6 +126,14 @@ public int size() { return jsonObj.size(); } + + /** + * Turns old overstacked itemstacks into individual stacks in a list + * + * @param oldB64 old B64 string to check/fix + * @return new list of ItemStacks + * @deprecated + */ private List b64OverstackFixer(String oldB64) { ShopItemStack oldStack = new ShopItemStack(oldB64); diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index f637a0ff..1d21b25b 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -43,6 +43,7 @@ import org.shanerx.tradeshop.player.PlayerSetting; import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.player.ShopUser; +import org.shanerx.tradeshop.shoplocation.ShopChunk; import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; import org.shanerx.tradeshop.utils.objects.Tuple; @@ -63,7 +64,6 @@ public class Shop implements Serializable { private final ShopLocation shopLoc; private List product, cost; private ShopLocation chestLoc; - private transient SignChangeEvent signChangeEvent; private transient Inventory storageInv; private transient Utils utils = new Utils(); private ShopStatus status = ShopStatus.INCOMPLETE; @@ -168,22 +168,6 @@ public void setStorageInventory() { storageInv = null; } - /** - * Adds the sign change event to the shop to be used during sign update - * - * @param event The SignChangeEvent to hold - */ - public void setEvent(SignChangeEvent event) { - this.signChangeEvent = event; - } - - /** - * Removes the SignChangeEvent from the shop(Should be done before leaving the event) - */ - public void removeEvent() { - this.signChangeEvent = null; - } - /** * Returns the storage block as a ShopChest * @@ -296,6 +280,37 @@ public void fixAfterLoad() { updateSign(); } + /** + * Generates a semi readable output of the shop object for debug output + * + * @return Return String for debug output + */ + public String toDebug() { + StringBuilder sb = new StringBuilder(); + sb.append("Shop Debug: \n"); + sb.append("Shop Chunk: ").append(new ShopChunk(shopLoc.getChunk()).serialize()).append("\n"); + sb.append("Sign Location: ").append(shopLoc.serialize()).append("\n"); + sb.append("Shop Type: ").append((isMissingItems() ? Setting.SHOP_INCOMPLETE_COLOUR : Setting.SHOP_GOOD_COLOUR).getString() + shopType.toHeader()).append("\n"); + sb.append("Shop Status: ").append(status.getLine()).append("\n"); + sb.append("Storage Location: ").append(hasStorage() ? getInventoryLocationAsSL().serialize() : "N/A").append("\n"); + sb.append("Storage Type: ").append(hasStorage() ? getStorage().getType().toString() : "N/A").append("\n"); + sb.append("Owner: ").append(owner.getName()).append(" | ").append(owner.getUUID()).append("\n"); + sb.append("Managers: ").append(managers.isEmpty() ? "N/A" : managers.size()).append("\n"); + if (!managers.isEmpty()) + getUsers(ShopRole.MANAGER).forEach(manager -> sb.append(" ").append(manager.getName()).append(" | ").append(manager.getUUID()).append("\n")); + sb.append("Members: ").append(members.isEmpty() ? "N/A" : members.size()).append("\n"); + if (!members.isEmpty()) + getUsers(ShopRole.MEMBER).forEach(member -> sb.append(" ").append(member.getName()).append(" | ").append(member.getUUID()).append("\n")); + sb.append("Products: ").append(product.isEmpty() ? "N/A" : product.size()).append("\n"); + if (!product.isEmpty()) + product.forEach(productItem -> sb.append(" ").append(productItem.toConsoleText()).append("\n")); + sb.append("Costs: ").append(cost.isEmpty() ? "N/A" : cost.size()).append("\n"); + if (!cost.isEmpty()) + cost.forEach(costItem -> sb.append(" ").append(costItem.toConsoleText()).append("\n")); + + return utils.colorize(sb.toString()); + } + /** * Saves the shop to file */ @@ -324,38 +339,50 @@ public Sign getShopSign() { * Updates the text on the shops sign */ public void updateSign() { - if (signChangeEvent != null) { - updateSign(signChangeEvent); - removeEvent(); - } else { - Sign s = getShopSign(); + Sign s = getShopSign(); - if (s != null) { - String[] signLines = updateSignLines(); + if (s == null) + return; - for (int i = 0; i < 4; i++) { - if (signLines[i] != null) - s.setLine(i, signLines[i]); - } + String[] signLines = updateSignLines(); - s.update(); - } + for (int i = 0; i < 4; i++) { + s.setLine(i, signLines[i]); } + + s.update(); } /** - * Updates the text on the shops sign during SignChangeEvent - * - * @param signEvent SignEvent to update the sign for + * Updates the text on the shops sign using the events sign if it matches location */ - public void updateSign(SignChangeEvent signEvent) { - String[] signLines = updateSignLines(); + public void updateSign(SignChangeEvent event) { + if (event == null || !event.getBlock().getLocation().equals(getShopLocation())) + return; - for (int i = 0; i < 4; i++) { - signEvent.setLine(i, signLines[i]); + String[] signLines = updateSignLines(); + + for (int i = 0; i < 4; i++) { + event.setLine(i, signLines[i]); } } + /** + * Updates the text on the shops sign using the passed sign if it matches location + */ + public void updateSign(Sign sign) { + if (sign == null || !sign.getLocation().equals(getShopLocation())) + return; + + String[] signLines = updateSignLines(); + + for (int i = 0; i < 4; i++) { + sign.setLine(i, signLines[i]); + } + + sign.update(); + } + /** * Updates the text for the shop signs * @@ -364,11 +391,7 @@ public void updateSign(SignChangeEvent signEvent) { private String[] updateSignLines() { String[] signLines = new String[4]; - if (isMissingItems()) { - signLines[0] = utils.colorize(Setting.SHOP_INCOMPLETE_COLOUR.getString() + shopType.toHeader()); - } else { - signLines[0] = utils.colorize(Setting.SHOP_GOOD_COLOUR.getString() + shopType.toHeader()); - } + signLines[0] = utils.colorize((isMissingItems() ? Setting.SHOP_INCOMPLETE_COLOUR : Setting.SHOP_GOOD_COLOUR).getString() + shopType.toHeader()); if (product.isEmpty()) { signLines[1] = ""; @@ -412,6 +435,11 @@ private String[] updateSignLines() { signLines[3] = status.getLine(); + for (int i = 0; i < 4; i++) { + if (signLines[i] == null) + signLines[i] = " "; + } + return signLines; } diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java index 63623367..1f7cb158 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopCreateListener.java @@ -25,9 +25,7 @@ package org.shanerx.tradeshop.shop.listeners; -import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -35,17 +33,10 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.data.config.Message; -import org.shanerx.tradeshop.data.config.Setting; -import org.shanerx.tradeshop.framework.events.PlayerShopCreateEvent; import org.shanerx.tradeshop.item.ShopItemSide; -import org.shanerx.tradeshop.player.ShopRole; -import org.shanerx.tradeshop.player.ShopUser; import org.shanerx.tradeshop.shop.Shop; -import org.shanerx.tradeshop.shop.ShopChest; import org.shanerx.tradeshop.shop.ShopType; import org.shanerx.tradeshop.utils.Utils; -import org.shanerx.tradeshop.utils.objects.Tuple; @SuppressWarnings("unused") public class ShopCreateListener extends Utils implements Listener { @@ -68,78 +59,16 @@ public void onSignChange(SignChangeEvent event) { ShopType shopType = ShopType.getType(shopSign); Player p = event.getPlayer(); - ShopUser owner = new ShopUser(p, ShopRole.OWNER); - if (!shopType.checkPerm(p)) { - failedSign(event, shopType, Message.NO_TS_CREATE_PERMISSION); - return; - } - - if (!checkShopChest(shopSign.getBlock()) && !shopType.isITrade()) { - failedSign(event, shopType, Message.NO_CHEST); - return; - } - - if (Setting.MAX_SHOPS_PER_CHUNK.getInt() <= PLUGIN.getDataStorage().getShopCountInChunk(shopSign.getChunk())) { - failedSign(event, shopType, Message.TOO_MANY_CHESTS); - return; - } - - ShopChest shopChest; - Shop shop; - Block chest = findShopChest(event.getBlock()); - - if (!shopType.isITrade()) { - if (ShopChest.isShopChest(chest)) { - shopChest = new ShopChest(chest.getLocation()); - } else { - shopChest = new ShopChest(chest, p.getUniqueId(), shopSign.getLocation()); - } - - if (shopChest.hasOwner() && !shopChest.getOwner().equals(owner.getUUID())) { - failedSign(event, shopType, Message.NO_SHOP_PERMISSION); - return; - } + // Clear the first line since we already know it is going to be a Shop, and we have the type to pass separately + // Required as the createShop method needs to make sure the first line is blank for commands to avoid overwriting existing shops + shopSign.setLine(0, ""); - if (shopChest.hasShopSign() && !shopChest.getShopSign().getLocation().equals(shopSign.getLocation())) { - failedSign(event, shopType, Message.EXISTING_SHOP); - return; - } + Shop shop = createShop(shopSign, p, shopType, lineCheck(ShopItemSide.COST, event.getLine(2)), lineCheck(ShopItemSide.PRODUCT, event.getLine(1)), event); - shop = new Shop(new Tuple<>(shopSign.getLocation(), shopChest.getChest().getLocation()), shopType, owner); - shopChest.setName(); - - - if (shopChest.isEmpty() && shop.hasSide(ShopItemSide.PRODUCT)) { - p.sendMessage(Message.EMPTY_TS_ON_SETUP.getPrefixed()); - } - } else { - shop = new Shop(shopSign.getLocation(), shopType, owner); + if (shop == null) { + failedSignReset(event, shopType); } - - shop.setEvent(event); - - ItemStack product = lineCheck(ShopItemSide.PRODUCT, event.getLine(1)), - cost = lineCheck(ShopItemSide.COST, event.getLine(2)); - - if (product != null && !shop.hasSide(ShopItemSide.PRODUCT)) - shop.setSideItems(ShopItemSide.PRODUCT, product); - - if (cost != null && !shop.hasSide(ShopItemSide.COST)) - shop.setSideItems(ShopItemSide.COST, cost); - - PlayerShopCreateEvent shopCreateEvent = new PlayerShopCreateEvent(p, shop); - Bukkit.getPluginManager().callEvent(shopCreateEvent); - if (shopCreateEvent.isCancelled()) { - event.setCancelled(true); - return; - } - - shop.updateSign(event); - shop.removeEvent(); - shop.saveShop(); - - p.sendMessage(Message.SUCCESSFUL_SETUP.getPrefixed()); } private ItemStack lineCheck(ShopItemSide side, String line) { diff --git a/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java index 654b8622..f7fe073e 100644 --- a/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java @@ -67,7 +67,7 @@ public static ShopLocation deserialize(String loc) { world = Bukkit.getWorld(locA[1].replace("-", "_")); if (world == null) { throw new IllegalWorldException("Cannot find world " + locA[1], new WorldlessLocation(x, y, z)); - // Not to maintainer: do NOT remove this aritificial error, it is supposed to be catched elsewhere + // Not to maintainer: do NOT remove this artificial error, it is supposed to be caught elsewhere // (Temporary fix for metadata world renaming bug until metadata is removed entirely) } diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 9031dd16..fedfb4d5 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -31,9 +31,9 @@ import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; +import org.bukkit.entity.Player; import org.bukkit.event.block.Action; import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; @@ -42,8 +42,11 @@ import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.data.config.Message; import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.framework.events.PlayerShopCreateEvent; import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.player.ShopRole; +import org.shanerx.tradeshop.player.ShopUser; import org.shanerx.tradeshop.shop.ExchangeStatus; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shop.ShopChest; @@ -215,28 +218,6 @@ public void failedSignReset(SignChangeEvent e, ShopType shop) { e.setLine(3, ""); } - /** - * Sets the event sign to a failed creation sign - * - * @param e event where shop creation failed - * @param shop Shoptype enum to get header - * @param msg The enum constant representing the error message - */ - public void failedSign(SignChangeEvent e, ShopType shop, Message msg) { - failedSignReset(e, shop); - e.getPlayer().sendMessage(colorize(Setting.MESSAGE_PREFIX.getString() + msg)); - } - - /** - * Sets the event sign to a failed creation sign - * - * @param e Event to reset the sign for - * @param msg The enum constant representing the error message - */ - public void failedTrade(PlayerInteractEvent e, Message msg) { - e.getPlayer().sendMessage(colorize(Setting.MESSAGE_PREFIX.getString() + msg)); - } - /** * Checks whether or not it is an illegal material. * @@ -488,6 +469,125 @@ public Tuple> canExchangeAll(Shop shop, Inventor return new Tuple<>(ExchangeStatus.SUCCESS, createBadList()); //Successfully completed trade } + /** + * Create a shop from a non-shop sign in front of the player + * + * @param shopSign sign to make into a shop + * @param creator player that is creating the shop + * @param shopType type of shop to make + * @param cost initial cost item for shop + * @param product initial product item for shop + * @param event SignUpdateEvent if being called from sign creation + * @return returns the shop object that was created + */ + public Shop createShop(Sign shopSign, Player creator, ShopType shopType, ItemStack cost, ItemStack product, SignChangeEvent event) { + if (ShopType.isShop(shopSign)) { + Message.EXISTING_SHOP.sendMessage(creator); + return null; + } + + ShopUser owner = new ShopUser(creator, ShopRole.OWNER); + + if (!checkShopChest(shopSign.getBlock()) && !shopType.isITrade()) { + Message.NO_CHEST.sendMessage(creator); + return null; + } + + if (Setting.MAX_SHOPS_PER_CHUNK.getInt() <= PLUGIN.getDataStorage().getShopCountInChunk(shopSign.getChunk())) { + Message.TOO_MANY_CHESTS.sendMessage(creator); + return null; + } + + ShopChest shopChest; + Shop shop; + Block chest = findShopChest(shopSign.getBlock()); + + if (!shopType.isITrade()) { + if (ShopChest.isShopChest(chest)) { + shopChest = new ShopChest(chest.getLocation()); + } else { + shopChest = new ShopChest(chest, creator.getUniqueId(), shopSign.getLocation()); + } + + if (shopChest.hasOwner() && !shopChest.getOwner().equals(owner.getUUID())) { + Message.NO_SHOP_PERMISSION.sendMessage(creator); + return null; + } + + if (shopChest.hasShopSign() && !shopChest.getShopSign().getLocation().equals(shopSign.getLocation())) { + Message.EXISTING_SHOP.sendMessage(creator); + return null; + } + + shop = new Shop(new Tuple<>(shopSign.getLocation(), shopChest.getChest().getLocation()), shopType, owner); + shopChest.setName(); + + if (cost != null && !shop.hasSide(ShopItemSide.COST)) + shop.setSideItems(ShopItemSide.COST, cost); + + if (product != null && !shop.hasSide(ShopItemSide.PRODUCT)) + shop.setSideItems(ShopItemSide.PRODUCT, product); + + if (shopChest.isEmpty() && shop.hasSide(ShopItemSide.PRODUCT)) { + Message.EMPTY_TS_ON_SETUP.sendMessage(creator); + } + } else { + shop = new Shop(shopSign.getLocation(), shopType, owner); + } + + debugger.log("-----Pre-Event-----", DebugLevels.SHOP_CREATION); + debugger.log(shop.toDebug(), DebugLevels.SHOP_CREATION); + + + debugger.log("-----Post-Event-----", DebugLevels.SHOP_CREATION); + PlayerShopCreateEvent shopCreateEvent = new PlayerShopCreateEvent(creator, shop); + Bukkit.getPluginManager().callEvent(shopCreateEvent); + if (shopCreateEvent.isCancelled()) { + debugger.log("Creation Failed!", DebugLevels.SHOP_CREATION); + return null; + } + + shop.saveShop(); + + if (event != null) { + shop.updateSign(event); + debugger.log("Event Sign Lines: \n" + event.getLine(0) + "\n" + event.getLine(1) + "\n" + event.getLine(2) + "\n" + event.getLine(3), DebugLevels.SHOP_CREATION); + } else { + shop.updateSign(shopSign); + debugger.log("Sign Lines: \n" + shopSign.getLine(0) + "\n" + shopSign.getLine(1) + "\n" + shopSign.getLine(2) + "\n" + shopSign.getLine(3), DebugLevels.SHOP_CREATION); + } + + Message.SUCCESSFUL_SETUP.sendMessage(creator); + debugger.log("Creation Successful!", DebugLevels.SHOP_CREATION); + return shop; + } + + /** + * Create a shop from a non-shop sign in front of the player + * + * @param shopSign sign to make into a shop + * @param creator player that is creating the shop + * @param shopType type of shop to make + * @return returns the shop object that was created + */ + public Shop createShop(Sign shopSign, Player creator, ShopType shopType) { + return createShop(shopSign, creator, shopType, null, null, null); + } + + /** + * Create a shop from a non-shop sign in front of the player + * + * @param shopSign sign to make into a shop + * @param creator player that is creating the shop + * @param shopType type of shop to make + * @param cost initial cost item for shop + * @param product initial product item for shop + * @return returns the shop object that was created + */ + public Shop createShop(Sign shopSign, Player creator, ShopType shopType, ItemStack cost, ItemStack product) { + return createShop(shopSign, creator, shopType, cost, product, null); + } + /** * Returns an arraylist of the ItemStack Objects to be removed/added, if it could not get enough of any items, it will return index 0 as null, followed by ItemStack Objects that could not be retrieved * diff --git a/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java b/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java index d09bacbc..db44c016 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java +++ b/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java @@ -41,7 +41,8 @@ public enum DebugLevels { NAME_COMPARE(7, Level.WARNING), // 64 SHULKERS_SUCK(8, Level.WARNING), // 128 ENCHANT_CHECKS(9, Level.WARNING), // 256 - OUTPUT(10, Level.WARNING) //512 + OUTPUT(10, Level.WARNING), // 512 + SHOP_CREATION(11, Level.INFO) // 1024 ; //position is what value to check for this level in the binary string -1. From 37f8891bfe8792aeb42721bd3df808802dcbf549 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Sun, 12 Jun 2022 21:38:04 -0700 Subject: [PATCH 13/53] Feature Add and Bug Fixes - Added configurable colours for the middle lines on trade sides per material type #135 - Removed Message call in CommandRunner that should never be used and would never actually send if it was. - Added SET_MANAGER and SET_MEMBER commands to the autofill for player names - Added Config support for map values so individual setting enums are not required for settings that may change(like sign types), This should automatically add new items to existing maps as well - Changed SettingSection weights to start at 50 increments based on nest depth to make them more easily readable - Changed Member and Manager Lists into Sets to prevent Duplicates(hopefully) - Added Shop#saveShop with a boolean parameter so that conditional saves don't need a separate if statement - Removed Wall sign types since each sign type is handled the same whether it is on a wall or not - Adjusted sign code to properly handle above - Fixed error in ShoptradeListener where shops in the OOS state but without a product would try to check on stock. --- .../tradeshop/commands/CommandTabCaller.java | 2 + .../commandrunners/CommandRunner.java | 1 - .../tradeshop/data/config/ConfigManager.java | 18 ++++-- .../tradeshop/data/config/Setting.java | 31 +++++++-- .../tradeshop/data/config/SettingSection.java | 47 ++++++++------ .../java/org/shanerx/tradeshop/shop/Shop.java | 53 ++++++++------- .../org/shanerx/tradeshop/shop/ShopSign.java | 64 ++++++++++++------- .../shop/listeners/ShopTradeListener.java | 8 ++- src/main/resources/Lang/en-us.yml | 10 ++- 9 files changed, 157 insertions(+), 77 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java index 202ebbca..579c836e 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java @@ -75,6 +75,8 @@ public List onTabComplete(CommandSender sender, Command cmd, String labe return tabCompleter.fillShopPlayer(); case ADD_MANAGER: case ADD_MEMBER: + case SET_MEMBER: + case SET_MANAGER: case PLAYER_LEVEL: return tabCompleter.fillServerPlayer(); default: diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CommandRunner.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CommandRunner.java index dc4d2926..030d5220 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CommandRunner.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/CommandRunner.java @@ -64,7 +64,6 @@ public CommandRunner(TradeShop instance, CommandPass command) { */ protected Shop findShop() { if (pSender == null) { - Message.PLAYER_ONLY_COMMAND.sendMessage(pSender); return null; } diff --git a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java index 6f110e4b..b8241e72 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java @@ -42,6 +42,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.LinkedHashMap; +import java.util.Map; import java.util.logging.Level; public class ConfigManager { @@ -154,13 +155,13 @@ public void save() { switch (configType) { case CONFIG: Arrays.stream(SettingSection.values()).sorted(new CompareSettingSections()).forEach((section) -> outputMap.put(section.getPath(), section.getFileString())); - Arrays.stream(Setting.values()).forEach((section) -> outputMap.put(section.getSection().getPath(), - outputMap.getOrDefault(section.getSection().getPath(), "") + section.getFileString())); + Arrays.stream(Setting.values()).forEach((setting) -> outputMap.put(setting.getSection().getPath(), + outputMap.getOrDefault(setting.getSection().getPath(), "") + setting.getFileString())); break; case MESSAGES: Arrays.stream(MessageSection.values()).sorted(new CompareMessageSections()).forEach((section) -> outputMap.put(section.getPath(), section.getFileString())); - Arrays.stream(Message.values()).forEach((section) -> outputMap.put(section.getSection().getPath(), - outputMap.getOrDefault(section.getSection().getPath(), "") + section.getFileString())); + Arrays.stream(Message.values()).forEach((message) -> outputMap.put(message.getSection().getPath(), + outputMap.getOrDefault(message.getSection().getPath(), "") + message.getFileString())); break; } @@ -181,7 +182,14 @@ public void save() { } private void addKeyValue(String node, Object value) { - if (config.get(node) == null || (config.get(node) != null && config.get(node).toString().isEmpty())) { + if (value instanceof Map) { + for (Map.Entry entry : ((Map) value).entrySet()) { + String newNode = node + "." + entry.getKey().toString(); + if (config.get(newNode) == null || (config.get(newNode) != null && config.get(newNode).toString().isEmpty())) { + config.set(newNode, entry.getValue().toString()); + } + } + } else if (config.get(node) == null || (config.get(node) != null && config.get(node).toString().isEmpty())) { config.set(node, value); } } diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index efc2ed42..79e24074 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -28,11 +28,12 @@ import org.bukkit.Bukkit; import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.shop.ShopSign; import org.yaml.snakeyaml.Yaml; import java.util.Arrays; import java.util.List; -import java.util.Objects; +import java.util.Map; public enum Setting { @@ -81,7 +82,8 @@ public enum Setting { ALLOW_USER_PURCHASING(SettingSection.SHOP_OPTIONS, "allow-user-purchasing", false), MULTIPLE_ITEMS_ON_SIGN(SettingSection.SHOP_OPTIONS, "multiple-items-on-sign", "Use '/ts what'"), - //Shop Item Default Setting Options + //region Shop Item Settings + //------------------------------------------------------------------------------------------------------------------ COMPARE_DURABILITY_DEFAULT(SettingSection.COMPARE_DURABILITY, "default", 1), COMPARE_ENCHANTMENTS_DEFAULT(SettingSection.COMPARE_ENCHANTMENTS, "default", true), COMPARE_NAME_DEFAULT(SettingSection.COMPARE_NAME, "default", true), @@ -113,6 +115,16 @@ public enum Setting { COMPARE_FIREWORK_DURATION_USER_EDITABLE(SettingSection.COMPARE_FIREWORK_DURATION, "user-editable", true), COMPARE_FIREWORK_EFFECTS_USER_EDITABLE(SettingSection.COMPARE_FIREWORK_EFFECTS, "user-editable", true), + //------------------------------------------------------------------------------------------------------------------ + //endregion + + //region Shop Sign Settings + //------------------------------------------------------------------------------------------------------------------ + SHOP_SIGN_DEFAULT_COLOURS(SettingSection.SHOP_SIGN_OPTIONS, "sign-default-colours", ShopSign.getDefaultColourMap()), + + //------------------------------------------------------------------------------------------------------------------ + //endregion + // Trade Shop Options TRADESHOP_HEADER(SettingSection.TRADE_SHOP_OPTIONS, "header", "Trade"), TRADESHOP_EXPLODE(SettingSection.TRADE_SHOP_OPTIONS, "allow-explode", false), @@ -140,7 +152,7 @@ public enum Setting { PRODUCT_ILLEGAL_ITEMS_TYPE(SettingSection.PRODUCT_ILLEGAL_ITEMS, "type", IllegalItemList.ListType.DISABLED.toString()), PRODUCT_ILLEGAL_ITEMS_LIST(SettingSection.PRODUCT_ILLEGAL_ITEMS, "list", new String[]{}); - public static final TradeShop PLUGIN = Objects.requireNonNull((TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop")); + public static final TradeShop PLUGIN = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); private final String key, path; private final Object defaultValue; @@ -239,6 +251,10 @@ public Object getDefaultValue() { return defaultValue; } + public String getMappedString(String subKey) { + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getString(subKey.toLowerCase().replace("_", "-")); + } + public String getPostComment() { return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING, path); } @@ -262,7 +278,14 @@ public String getFileString() { keyOutput.append(section.getSectionLead()).append("# ").append(PLUGIN.getSettingManager().fixCommentNewLines(section.getSectionLead(), getPreComment())).append("\n"); } - keyOutput.append(section.getSectionLead()).append(getKey()).append(": ").append(new Yaml().dump(getSetting())); + if (defaultValue instanceof Map) { + keyOutput.append(section.getSectionLead()).append(getKey()).append(":\n"); + for (Map.Entry entry : ((Map) defaultValue).entrySet()) { + keyOutput.append(section.getSectionLead() + " ").append(entry.getKey().toString()).append(": ").append(new Yaml().dump(entry.getValue())); + } + } else { + keyOutput.append(section.getSectionLead()).append(getKey()).append(": ").append(new Yaml().dump(getSetting())); + } if (!getPostComment().isEmpty()) { if (getPostComment().equals(" ") || getPostComment().equals("\n")) diff --git a/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java index 6bedaf7d..828b28c1 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java @@ -32,35 +32,44 @@ public enum SettingSection { + //Weight for primary Sections should start at 0 and each sub-section should start at increments of 50 + NONE(0, ""), SYSTEM_OPTIONS(1, "system-options"), LANGUAGE_OPTIONS(2, "language-options"), GLOBAL_OPTIONS(3, "global-options"), - GLOBAL_MULTI_TRADE(0, GLOBAL_OPTIONS, "multi-trade"), + GLOBAL_MULTI_TRADE(50, GLOBAL_OPTIONS, "multi-trade"), SHOP_OPTIONS(4, "shop-options"), - SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS(0, SHOP_OPTIONS, "shop-item-default-settings-options"), - COMPARE_DURABILITY(0, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-durability"), - COMPARE_ENCHANTMENTS(1, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-enchantments"), - COMPARE_NAME(2, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-name"), - COMPARE_LORE(3, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-lore"), - COMPARE_CUSTOM_MODEL_DATA(4, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-custom-data-model"), - COMPARE_ITEM_FLAGS(5, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-item-flags"), - COMPARE_UNBREAKABLE(6, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-unbreakable"), - COMPARE_ATTRIBUTE_MODIFIER(7, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-attribute-modifier"), - COMPARE_BOOK_AUTHOR(8, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-book-author"), - COMPARE_BOOK_PAGES(9, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-book-pages"), - COMPARE_SHULKER_INVENTORY(10, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-shulker-inventory"), - COMPARE_BUNDLE_INVENTORY(11, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-bundle-inventory"), - COMPARE_FIREWORK_DURATION(12, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-firework-duration"), - COMPARE_FIREWORK_EFFECTS(13, SHOP_ITEM_DEFAULT_SETTINGS_OPTIONS, "compare-firework-effects"), + + //region Shop Item Settings + //------------------------------------------------------------------------------------------------------------------ + SHOP_ITEM_SETTINGS(50, SHOP_OPTIONS, "shop-item-default-settings-options"), + COMPARE_DURABILITY(100, SHOP_ITEM_SETTINGS, "compare-durability"), + COMPARE_ENCHANTMENTS(101, SHOP_ITEM_SETTINGS, "compare-enchantments"), + COMPARE_NAME(102, SHOP_ITEM_SETTINGS, "compare-name"), + COMPARE_LORE(103, SHOP_ITEM_SETTINGS, "compare-lore"), + COMPARE_CUSTOM_MODEL_DATA(104, SHOP_ITEM_SETTINGS, "compare-custom-data-model"), + COMPARE_ITEM_FLAGS(105, SHOP_ITEM_SETTINGS, "compare-item-flags"), + COMPARE_UNBREAKABLE(106, SHOP_ITEM_SETTINGS, "compare-unbreakable"), + COMPARE_ATTRIBUTE_MODIFIER(107, SHOP_ITEM_SETTINGS, "compare-attribute-modifier"), + COMPARE_BOOK_AUTHOR(108, SHOP_ITEM_SETTINGS, "compare-book-author"), + COMPARE_BOOK_PAGES(109, SHOP_ITEM_SETTINGS, "compare-book-pages"), + COMPARE_SHULKER_INVENTORY(110, SHOP_ITEM_SETTINGS, "compare-shulker-inventory"), + COMPARE_BUNDLE_INVENTORY(111, SHOP_ITEM_SETTINGS, "compare-bundle-inventory"), + COMPARE_FIREWORK_DURATION(112, SHOP_ITEM_SETTINGS, "compare-firework-duration"), + COMPARE_FIREWORK_EFFECTS(113, SHOP_ITEM_SETTINGS, "compare-firework-effects"), + //------------------------------------------------------------------------------------------------------------------ + //endregion + + SHOP_SIGN_OPTIONS(5, "shop-sign-options"), TRADE_SHOP_OPTIONS(6, "trade-shop-options"), ITRADE_SHOP_OPTIONS(7, "itrade-shop-options"), BITRADE_SHOP_OPTIONS(8, "bitrade-shop-options"), ILLEGAL_ITEM_OPTIONS(9, "illegal-item-options"), - GLOBAL_ILLEGAL_ITEMS(0, ILLEGAL_ITEM_OPTIONS, "global-illegal-items"), - COST_ILLEGAL_ITEMS(1, ILLEGAL_ITEM_OPTIONS, "cost-illegal-items"), - PRODUCT_ILLEGAL_ITEMS(2, ILLEGAL_ITEM_OPTIONS, "product-illegal-items"); + GLOBAL_ILLEGAL_ITEMS(50, ILLEGAL_ITEM_OPTIONS, "global-illegal-items"), + COST_ILLEGAL_ITEMS(51, ILLEGAL_ITEM_OPTIONS, "cost-illegal-items"), + PRODUCT_ILLEGAL_ITEMS(52, ILLEGAL_ITEM_OPTIONS, "product-illegal-items"); public static final TradeShop PLUGIN = Objects.requireNonNull((TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop")); diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 1d21b25b..3c7cf51a 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -59,7 +59,7 @@ public class Shop implements Serializable { private ShopUser owner; - private List managers, members; + private Set managers, members; private ShopType shopType; private final ShopLocation shopLoc; private List product, cost; @@ -79,7 +79,7 @@ public class Shop implements Serializable { * @param items Items to go into the shop as Tuple, left = Product, right = Cost * @param players Users to be added to the shop as Tuple, left = Managers, right = Members */ - public Shop(Tuple locations, ShopType shopType, ShopUser owner, Tuple, List> players, Tuple items) { + public Shop(Tuple locations, ShopType shopType, ShopUser owner, Tuple, Set> players, Tuple items) { shopLoc = new ShopLocation(locations.getLeft()); this.owner = owner; @@ -90,8 +90,8 @@ public Shop(Tuple locations, ShopType shopType, ShopUser own this.shopType = shopType; - managers = players.getLeft() == null ? Collections.emptyList() : players.getLeft(); - members = players.getRight() == null ? Collections.emptyList() : players.getRight(); + managers = players.getLeft() == null ? Collections.emptySet() : players.getLeft(); + members = players.getRight() == null ? Collections.emptySet() : players.getRight(); product = new ArrayList<>(); cost = new ArrayList<>(); @@ -320,6 +320,15 @@ public void saveShop() { updateUserFiles(); } + /** + * Saves the shop to file if passed boolean is true + * + * @param shouldSave true if save should proceed + */ + public void saveShop(boolean shouldSave) { + if (shouldSave) saveShop(); + } + /** * Returns the shops sign as a Sign * @@ -344,7 +353,7 @@ public void updateSign() { if (s == null) return; - String[] signLines = updateSignLines(); + String[] signLines = updateSignLines(Setting.SHOP_SIGN_DEFAULT_COLOURS.getMappedString(Signs.match(s.getType()).name())); for (int i = 0; i < 4; i++) { s.setLine(i, signLines[i]); @@ -360,7 +369,7 @@ public void updateSign(SignChangeEvent event) { if (event == null || !event.getBlock().getLocation().equals(getShopLocation())) return; - String[] signLines = updateSignLines(); + String[] signLines = updateSignLines(Setting.SHOP_SIGN_DEFAULT_COLOURS.getMappedString(Signs.match(event.getBlock().getType()).name())); for (int i = 0; i < 4; i++) { event.setLine(i, signLines[i]); @@ -374,7 +383,7 @@ public void updateSign(Sign sign) { if (sign == null || !sign.getLocation().equals(getShopLocation())) return; - String[] signLines = updateSignLines(); + String[] signLines = updateSignLines(Setting.SHOP_SIGN_DEFAULT_COLOURS.getMappedString(Signs.match(sign.getType()).name())); for (int i = 0; i < 4; i++) { sign.setLine(i, signLines[i]); @@ -383,12 +392,12 @@ public void updateSign(Sign sign) { sign.update(); } - /** - * Updates the text for the shop signs - * - * @return String array containing updated sign lines to be set - */ - private String[] updateSignLines() { + /** + * Updates the text for the shop signs + * + * @return String array containing updated sign lines to be set + */ + private String[] updateSignLines(String defaultColour) { String[] signLines = new String[4]; signLines[0] = utils.colorize((isMissingItems() ? Setting.SHOP_INCOMPLETE_COLOUR : Setting.SHOP_GOOD_COLOUR).getString() + shopType.toHeader()); @@ -405,10 +414,10 @@ private String[] updateSignLines() { sb.append(item.getCleanItemName()); - signLines[1] = sb.substring(0, Math.min(sb.length(), 15)); + signLines[1] = utils.colorize(defaultColour + sb.substring(0, Math.min(sb.length(), 15))); - } else { - signLines[1] = Setting.MULTIPLE_ITEMS_ON_SIGN.getString().replace("%amount%", ""); + } else { + signLines[1] = utils.colorize(defaultColour + Setting.MULTIPLE_ITEMS_ON_SIGN.getString().replace("%amount%", "")); } if (cost.isEmpty()) { @@ -428,8 +437,8 @@ private String[] updateSignLines() { signLines[2] = Setting.MULTIPLE_ITEMS_ON_SIGN.getString(); } - signLines[1] = ChatColor.stripColor(signLines[1]); - signLines[2] = ChatColor.stripColor(signLines[2]); + signLines[1] = utils.colorize(defaultColour + ChatColor.stripColor(signLines[1])); + signLines[2] = utils.colorize(defaultColour + ChatColor.stripColor(signLines[2])); updateStatus(); @@ -742,7 +751,7 @@ public boolean addUser(UUID newUser, ShopRole role) { } } - if (ret) saveShop(); + saveShop(ret); return ret; } @@ -794,7 +803,7 @@ public boolean removeUser(UUID oldUser) { ret = true; } - saveShop(); + saveShop(ret); return ret; } @@ -804,7 +813,7 @@ public boolean removeUser(UUID oldUser) { * * @param users the managers to be set to the shop */ - public boolean setUsers(List users, ShopRole role) { + public boolean setUsers(Set users, ShopRole role) { boolean ret = false; switch (role) { case MANAGER: @@ -817,7 +826,7 @@ public boolean setUsers(List users, ShopRole role) { ret = true; } - if (ret) saveShop(); + saveShop(ret); return ret; } diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java b/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java index 10ae2863..fdbdfab8 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java @@ -32,33 +32,30 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; enum Signs { - SIGN("", "1.13.2"), - OAK_SIGN("1.14.0", ""), - SPRUCE_SIGN("1.14.0", ""), - BIRCH_SIGN("1.14.0", ""), - JUNGLE_SIGN("1.14.0", ""), - ACACIA_SIGN("1.14.0", ""), - DARK_OAK_SIGN("1.14.0", ""), - CRIMSON_SIGN("1.16.0", ""), - WARPED_SIGN("1.16.0", ""), - WALL_SIGN("", "1.13.2"), - OAK_WALL_SIGN("1.14.0", ""), - SPRUCE_WALL_SIGN("1.14.0", ""), - BIRCH_WALL_SIGN("1.14.0", ""), - JUNGLE_WALL_SIGN("1.14.0", ""), - ACACIA_WALL_SIGN("1.14.0", ""), - DARK_OAK_WALL_SIGN("1.14.0", ""), - CRIMSON_WALL_SIGN("1.16.0", ""), - WARPED_WALL_SIGN("1.16.0", ""); + SIGN("", "1.13.2", "&0"), + OAK_SIGN("1.14.0", "", "&0"), + SPRUCE_SIGN("1.14.0", "", "&0"), + BIRCH_SIGN("1.14.0", "", "&0"), + JUNGLE_SIGN("1.14.0", "", "&0"), + ACACIA_SIGN("1.14.0", "", "&0"), + DARK_OAK_SIGN("1.14.0", "", "&f"), + CRIMSON_SIGN("1.16.0", "", "&0"), + WARPED_SIGN("1.16.0", "", "&0"), + MANGROVE_SIGN("1.19.0", "", "&0"); private final List minVer = Arrays.asList(new Integer[3]); private final List maxVer = Arrays.asList(new Integer[3]); private boolean hasMin = true, hasMax = true; + private final String defaultColour; + + Signs(String minVersion, String maxVersion, String defaultColour) { + this.defaultColour = defaultColour; - Signs(String minVersion, String maxVersion) { if (minVersion.equalsIgnoreCase("")) hasMin = false; @@ -104,6 +101,13 @@ public String getMaxVersionAsString() { return hasMaxVersion() ? getMaxVer().get(0) + "." + getMaxVer().get(1) + "." + getMaxVer().get(2) : "None"; } + public static Signs match(Material mat) { + return valueOf(mat.toString().replace("WALL_", "")); + } + + public String getDefaultColour() { + return defaultColour; + } } public class ShopSign extends Utils { @@ -124,16 +128,32 @@ public ShopSign() { pass = false; } - if (pass) + if (pass) { signTypes.add(Material.matchMaterial(type.toString())); + signTypes.add(Material.matchMaterial(type.toString().toUpperCase().replace("_SIGN", "_WALL_SIGN"))); + } } - - } public List getSignTypes() { return signTypes; } + public static Map getDefaultColourMap() { + final BukkitVersion version = new BukkitVersion(); + Map colourMap = new HashMap<>(); + + for (Signs value : Signs.values()) { + String key = value.name().toLowerCase().replace("_", "-"); + + colourMap.put(key, value.getDefaultColour()); + if (value.hasMinVersion() && version.isBelow(value.getMinVer().get(0), value.getMinVer().get(1), value.getMinVer().get(2))) + colourMap.remove(key); + if (value.hasMaxVersion() && version.isAbove(value.getMaxVer().get(0), value.getMaxVer().get(1), value.getMaxVer().get(2))) + colourMap.remove(key); + } + + return colourMap; + } } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java index d22acbf2..43d547f7 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java @@ -139,8 +139,12 @@ public void onBlockInteract(PlayerInteractEvent e) { break; } - List searchResult = getItems(shop.getChestAsSC().getInventory().getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT, doBiTradeAlternate), multiplier); - Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, searchResult)); + if (shop.hasSide(ShopItemSide.PRODUCT)) { + List searchResult = getItems(shop.getChestAsSC().getInventory().getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT, doBiTradeAlternate), multiplier); + Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, searchResult)); + } else { + Message.SHOP_EMPTY.sendMessage(buyer); + } return; case OPEN: break; diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 69ed1666..eea3bb34 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -60,6 +60,8 @@ setting-section: compare-firework-effects: header: "" pre-comment: "Compare Firework Effects" + shop-sign-options: + header: "Shop Sign Options" trade-shop-options: header: "Trade Shop Options" itrade-shop-options: @@ -240,7 +242,11 @@ setting: default: pre-comment: "" user-editable: - pre-comment: "" + post-comment: "\n" + shop-sign-options: + sign-default-colours: + pre-comment: "What colour should be used for line 2/3 on shop signs per each material type." + post-comment: "\n" trade-shop-options: header: pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" @@ -391,7 +397,7 @@ message: too-many-items: default: "&cThis shop cannot take any more %SIDE% items!" updated-shop-users: - default: "&aShop users have tried to update for the below shops! \n{%UPDATED_SHOPS%= %SHOP% -|- %STATUS%}" + default: "&aShop users have tried to update for the below shops! \n{%UPDATEDSHOPS%= %SHOP% -|- %STATUS%}" pre-comment: "Text to display when shop users have been updated." updated-shop-users-successful: default: "&aSuccessful" From b4d1b8f7af9cba174bc6b926cd1c47029933ecaf Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 13 Jun 2022 14:31:00 -0700 Subject: [PATCH 14/53] Bug Fixes - Added conditional saving for Setting and Message files - Added thorough change detection for setting defaults and upgrades to prevent unnecessary saves and fix bug preventing changes to default sign colours to be changed from their default values - Fixed bug preventing setUser commands from working due to failed removal(which wasn't necessary for the set to process) - Added missing return in ShopTradeListener which caused `OOS` code to run after `Incomplete` code in a switch --- .../tradeshop/data/config/ConfigManager.java | 42 ++++++++++++++----- .../tradeshop/data/config/Message.java | 15 ++++++- .../tradeshop/data/config/Setting.java | 30 +++++++++++-- .../java/org/shanerx/tradeshop/shop/Shop.java | 3 +- .../shop/listeners/ShopTradeListener.java | 3 +- 5 files changed, 75 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java index b8241e72..44537f60 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java @@ -29,6 +29,7 @@ import com.google.common.base.Charsets; import com.google.common.io.Files; import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; @@ -41,8 +42,10 @@ import java.io.Writer; import java.util.Arrays; import java.util.Comparator; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Set; import java.util.logging.Level; public class ConfigManager { @@ -78,7 +81,7 @@ public String colour(String toColour) { return ChatColor.translateAlternateColorCodes('&', toColour); } - public void load() { + public boolean load() { try { if (!PLUGIN.getDataFolder().isDirectory()) { PLUGIN.getDataFolder().mkdirs(); @@ -93,23 +96,24 @@ public void load() { config = YamlConfiguration.loadConfiguration(file); - setDefaults(); + return setDefaults(); } public void reload() { - load(); + Set hasUpgraded = new HashSet<>(); + hasUpgraded.add(load()); switch (configType) { case CONFIG: - Setting.upgrade(); + hasUpgraded.add(Setting.upgrade()); PLUGIN.setUseInternalPerms(Setting.USE_INTERNAL_PERMISSIONS.getBoolean()); break; case MESSAGES: - Message.upgrade(); + hasUpgraded.add(Message.upgrade()); break; } - save(); + save(hasUpgraded.contains(true)); PLUGIN.setSkipHopperProtection( Setting.BITRADESHOP_HOPPER_EXPORT.getBoolean() && @@ -118,15 +122,28 @@ public void reload() { Setting.TRADESHOP_HOPPER_EXPORT.getBoolean()); } - public void setDefaults() { + public boolean setDefaults() { + Set hasUpgraded = new HashSet<>(); + switch (configType) { case CONFIG: - Arrays.stream(Setting.values()).forEach((setting) -> addKeyValue(setting.getPath(), setting.getDefaultValue())); + Arrays.stream(Setting.values()).forEach((setting) -> hasUpgraded.add(addKeyValue(setting.getPath(), setting.getDefaultValue()))); break; case MESSAGES: - Arrays.stream(Message.values()).forEach((message) -> addKeyValue(message.getPath(), message.getDefaultValue())); + Arrays.stream(Message.values()).forEach((message) -> hasUpgraded.add(addKeyValue(message.getPath(), message.getDefaultValue()))); break; } + + return hasUpgraded.contains(true); + } + + /** + * Saves the file if passed boolean is true + * + * @param shouldSave true if save should proceed + */ + public void save(boolean shouldSave) { + if (shouldSave) save(); } public void save() { @@ -181,17 +198,22 @@ public void save() { config = YamlConfiguration.loadConfiguration(file); } - private void addKeyValue(String node, Object value) { + private boolean addKeyValue(String node, Object value) { if (value instanceof Map) { for (Map.Entry entry : ((Map) value).entrySet()) { String newNode = node + "." + entry.getKey().toString(); if (config.get(newNode) == null || (config.get(newNode) != null && config.get(newNode).toString().isEmpty())) { + Bukkit.getLogger().log(Level.WARNING, "TS reload issue ->\n" + newNode + " = " + config.get(newNode).toString() + " | " + entry.getValue().toString()); config.set(newNode, entry.getValue().toString()); + return true; } } } else if (config.get(node) == null || (config.get(node) != null && config.get(node).toString().isEmpty())) { config.set(node, value); + return true; } + + return false; } public enum ConfigType { diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java index 8028966a..f2de16e1 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -37,9 +37,11 @@ import org.yaml.snakeyaml.Yaml; import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -117,13 +119,15 @@ public enum Message { } // Method to fix any values that have changed with updates - static void upgrade() { + static boolean upgrade() { double version = MESSAGE_VERSION.getDouble(); + Set hasUpgraded = new HashSet<>(); // Uses this instead of a boolean to later replace below ifs with boolean return methods... //Changes if CONFIG_VERSION is below 1.1, then update to 1.1 if (checkVersion(version, 1.1)) { if (TOO_MANY_ITEMS.getString().equals("&cThis trade can not take any more %side%!")) { TOO_MANY_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, TOO_MANY_ITEMS.getPath())); + hasUpgraded.add(true); } version = 1.1; } @@ -133,8 +137,10 @@ static void upgrade() { Arrays.stream(values()).forEach((message) -> { String str = message.getString().replace("{", "%").replace("}", "%"); - if (!str.equals(message.getString())) + if (!str.equals(message.getString())) { message.setValue(str); + hasUpgraded.add(true); + } }); version = 1.2; @@ -144,12 +150,15 @@ static void upgrade() { if (checkVersion(version, 1.3)) { if (INSUFFICIENT_ITEMS.getString().equals("&cYou do not have &e%AMOUNT% %ITEM%&c!")) { INSUFFICIENT_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, INSUFFICIENT_ITEMS.getPath())); + hasUpgraded.add(true); } if (SHOP_INSUFFICIENT_ITEMS.getString().equals("&cThis shop does not have enough &e%AMOUNT% %ITEM%&c to trade!")) { SHOP_INSUFFICIENT_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, SHOP_INSUFFICIENT_ITEMS.getPath())); + hasUpgraded.add(true); } if (ON_TRADE.getString().equals("&aYou have traded your &e%AMOUNT2% %ITEM2% &afor &e%AMOUNT1% %ITEM1% &awith %SELLER%")) { ON_TRADE.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, ON_TRADE.getPath())); + hasUpgraded.add(true); } @@ -157,6 +166,8 @@ static void upgrade() { } MESSAGE_VERSION.setValue(version != 0.0 ? version : 1.3); + + return hasUpgraded.contains(true); } private static boolean checkVersion(double version, double maxVersion) { diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 79e24074..9a4f6a53 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -32,8 +32,10 @@ import org.yaml.snakeyaml.Yaml; import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; public enum Setting { @@ -170,8 +172,9 @@ public static Setting findSetting(String search) { } // Method to fix any values that have changed with updates - static void upgrade() { + static boolean upgrade() { double version = CONFIG_VERSION.getDouble(); + Set hasUpgraded = new HashSet<>(); // Uses this instead of a boolean to later replace below ifs with boolean return methods... ConfigManager configManager = PLUGIN.getSettingManager(); // 2.2.2 Changed enable debug from true/false to integer @@ -184,46 +187,55 @@ static void upgrade() { if (configManager.getConfig().contains("itradeshop.owner")) { configManager.getConfig().set(ITRADESHOP_OWNER.path, configManager.getConfig().get("itradeshop.owner")); configManager.getConfig().set("itradeshop.owner", null); + hasUpgraded.add(true); } if (configManager.getConfig().contains("itradeshop.header")) { configManager.getConfig().set(ITRADESHOP_HEADER.path, configManager.getConfig().get("itradeshop.header")); configManager.getConfig().set("itradeshop.header", null); + hasUpgraded.add(true); } if (configManager.getConfig().contains("itradeshop.allow-explode")) { configManager.getConfig().set(ITRADESHOP_EXPLODE.path, configManager.getConfig().get("itradeshop.allow-explode")); configManager.getConfig().set("itradeshop.allow-explode", null); + hasUpgraded.add(true); } if (configManager.getConfig().contains("tradeshop.header")) { configManager.getConfig().set(TRADESHOP_HEADER.path, configManager.getConfig().get("tradeshop.header")); configManager.getConfig().set("tradeshop.header", null); + hasUpgraded.add(true); } if (configManager.getConfig().contains("tradeshop.allow-explode")) { configManager.getConfig().set(TRADESHOP_EXPLODE.path, configManager.getConfig().get("tradeshop.allow-explode")); configManager.getConfig().set("tradeshop.allow-explode", null); + hasUpgraded.add(true); } if (configManager.getConfig().contains("tradeshop.allow-hopper-export")) { configManager.getConfig().set(TRADESHOP_HOPPER_EXPORT.path, configManager.getConfig().get("tradeshop.allow-hopper-export")); configManager.getConfig().set("tradeshop.allow-hopper-export", null); + hasUpgraded.add(true); } if (configManager.getConfig().contains("bitradeshop.header")) { configManager.getConfig().set(BITRADESHOP_HEADER.path, configManager.getConfig().get("bitradeshop.header")); configManager.getConfig().set("bitradeshop.header", null); + hasUpgraded.add(true); } if (configManager.getConfig().contains("bitradeshop.allow-explode")) { configManager.getConfig().set(BITRADESHOP_EXPLODE.path, configManager.getConfig().get("bitradeshop.allow-explode")); configManager.getConfig().set("bitradeshop.allow-explode", null); + hasUpgraded.add(true); } if (configManager.getConfig().contains("bitradeshop.allow-hopper-export")) { configManager.getConfig().set(BITRADESHOP_HOPPER_EXPORT.path, configManager.getConfig().get("bitradeshop.allow-hopper-export")); configManager.getConfig().set("bitradeshop.allow-hopper-export", null); + hasUpgraded.add(true); } @@ -235,12 +247,15 @@ static void upgrade() { configManager.getConfig().set(GLOBAL_ILLEGAL_ITEMS_LIST.path, configManager.getConfig().get("global-options.illegal-items")); GLOBAL_ILLEGAL_ITEMS_LIST.setValue(configManager.getConfig().getStringList("global-options.illegal-items").removeAll(Arrays.asList("Air", "Void_Air", "Cave_Air"))); configManager.getConfig().set("global-options.illegal-items", null); + hasUpgraded.add(true); } version = 1.2; } CONFIG_VERSION.setValue(version); + + return hasUpgraded.contains(true); } public String getKey() { @@ -255,6 +270,10 @@ public String getMappedString(String subKey) { return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getString(subKey.toLowerCase().replace("_", "-")); } + public boolean getMappedBoolean(String subKey) { + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getBoolean(subKey.toLowerCase().replace("_", "-")); + } + public String getPostComment() { return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING, path); } @@ -281,7 +300,7 @@ public String getFileString() { if (defaultValue instanceof Map) { keyOutput.append(section.getSectionLead()).append(getKey()).append(":\n"); for (Map.Entry entry : ((Map) defaultValue).entrySet()) { - keyOutput.append(section.getSectionLead() + " ").append(entry.getKey().toString()).append(": ").append(new Yaml().dump(entry.getValue())); + keyOutput.append(section.getSectionLead() + " ").append(entry.getKey().toString()).append(": ").append(new Yaml().dump(entry.getValue())); } } else { keyOutput.append(section.getSectionLead()).append(getKey()).append(": ").append(new Yaml().dump(getSetting())); @@ -301,6 +320,11 @@ public void setValue(Object obj) { PLUGIN.getSettingManager().getConfig().set(getPath(), obj); } + public void setMappedValue(String subKey, Object obj) { + String newNode = getPath() + "." + subKey; + PLUGIN.getSettingManager().getConfig().set(newNode, obj); + } + public void clearSetting() { PLUGIN.getSettingManager().getConfig().set(getPath(), null); } @@ -309,7 +333,7 @@ public Object getSetting() { return PLUGIN.getSettingManager().getConfig().get(getPath()); } - public String getString() { + public String getString() { return PLUGIN.getSettingManager().getConfig().getString(getPath()); } diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 3c7cf51a..6bdc4d44 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -725,7 +725,8 @@ public void setOwner(ShopUser owner) { * @return true if player has been set */ public boolean setUser(UUID newUser, ShopRole role) { - return removeUser(newUser) && addUser(newUser, role); + removeUser(newUser); + return addUser(newUser, role); } /** diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java index 43d547f7..c4bba16c 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java @@ -134,6 +134,7 @@ public void onBlockInteract(PlayerInteractEvent e) { return; case INCOMPLETE: Message.SHOP_EMPTY.sendMessage(buyer); + return; case OUT_OF_STOCK: if (shop.getShopType() == ShopType.ITRADE) { break; @@ -142,8 +143,6 @@ public void onBlockInteract(PlayerInteractEvent e) { if (shop.hasSide(ShopItemSide.PRODUCT)) { List searchResult = getItems(shop.getChestAsSC().getInventory().getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT, doBiTradeAlternate), multiplier); Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, searchResult)); - } else { - Message.SHOP_EMPTY.sendMessage(buyer); } return; case OPEN: From 9bb4c5688d6e297b221be36da1c1799dd6289814 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 13 Jun 2022 15:19:48 -0700 Subject: [PATCH 15/53] Permission improvements - Additions for #138 --- .../java/org/shanerx/tradeshop/TradeShop.java | 3 ++ .../tradeshop/data/config/Language.java | 25 +++++---- .../shanerx/tradeshop/player/Permissions.java | 53 ++++++++++++++----- src/main/resources/Lang/en-us.yml | 22 +++++++- 4 files changed, 80 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/TradeShop.java b/src/main/java/org/shanerx/tradeshop/TradeShop.java index 2d691ccf..975c6d1a 100644 --- a/src/main/java/org/shanerx/tradeshop/TradeShop.java +++ b/src/main/java/org/shanerx/tradeshop/TradeShop.java @@ -36,6 +36,7 @@ import org.shanerx.tradeshop.data.storage.DataStorage; import org.shanerx.tradeshop.data.storage.DataType; import org.shanerx.tradeshop.player.JoinEventListener; +import org.shanerx.tradeshop.player.Permissions; import org.shanerx.tradeshop.shop.ShopSign; import org.shanerx.tradeshop.shop.ShopStorage; import org.shanerx.tradeshop.shop.listeners.ShopCreateListener; @@ -103,6 +104,8 @@ public void onEnable() { getDebugger(); + Permissions.registerPermissions(); + if (getDataStorage() == null) return; diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Language.java b/src/main/java/org/shanerx/tradeshop/data/config/Language.java index 9b37db76..de4f3c72 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Language.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Language.java @@ -106,25 +106,31 @@ public String getLang() { } public String getHeader(LangSection section, String path) { - String fullPath = section + "." + path + ".header"; - return langYAML.getString(fullPath, ""); + return getString(section, path, "header"); } - public Object getDefault(LangSection section, String path) { - String fullPath = section + "." + path + ".default", defaultValue = langYAML.getString(fullPath); - return defaultValue != null ? defaultValue : getDefaultLangValue(fullPath).toString(); + public String getDefault(LangSection section, String path) { + return getStringOrDefault(section, path, "default"); } public String getPreComment(LangSection section, String path) { - String fullPath = section + "." + path + ".pre-comment"; - return langYAML.getString(fullPath, ""); + return getString(section, path, "pre-comment"); } public String getPostComment(LangSection section, String path) { - String fullPath = section + "." + path + ".post-comment"; + return getString(section, path, "post-comment"); + } + + public String getString(LangSection section, String key, String field) { + String fullPath = section + "." + key + "." + field; return langYAML.getString(fullPath, ""); } + public String getStringOrDefault(LangSection section, String key, String field) { + String fullPath = section + "." + key + "." + field, value = getString(section, key, field); + return value != null ? value : getDefaultLangValue(fullPath).toString(); + } + public boolean isLoaded() { return loaded; } @@ -134,7 +140,8 @@ public enum LangSection { MESSAGE_SECTION, MESSAGE, SETTING_SECTION, - SETTING; + SETTING, + PERMISSION; LangSection() { } diff --git a/src/main/java/org/shanerx/tradeshop/player/Permissions.java b/src/main/java/org/shanerx/tradeshop/player/Permissions.java index 62b87417..ac217cc9 100644 --- a/src/main/java/org/shanerx/tradeshop/player/Permissions.java +++ b/src/main/java/org/shanerx/tradeshop/player/Permissions.java @@ -28,37 +28,48 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.data.config.Language; +import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.debug.DebugLevels; public enum Permissions { + //Available defaultState options are: `true`, `false`, `op`, and `not_op` - HELP("help", 0), + HELP("help", 0, "true"), - CREATE("create", 0), + CREATE("create", 0, "true"), - CREATEI("create.infinite", 1), + CREATEI("create.infinite", 1, "op"), - CREATEBI("create.bi", 0), + CREATEBI("create.bi", 0, "true"), - ADMIN("admin", 1), + ADMIN("admin", 1, "op"), - EDIT("edit", 0), // non admin perm + EDIT("edit", 0, "true"), // non admin perm - INFO("info", 0), + INFO("info", 0, "true"), - MANAGE_PLUGIN("manage-plugin", 2), + MANAGE_PLUGIN("manage-plugin", 2, "op"), - PREVENT_TRADE("prevent-trade", -1), + PREVENT_TRADE("prevent-trade", -1, "false"), - NONE("", 0); + TRADE("trade", 0, "true"), + + NONE("", 0, "true"); private final static TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); + private final Utils utils = new Utils(); private final String key; private final int level; + private final String defaultState, description; - Permissions(String key, int level) { + Permissions(String key, int level, String defaultState) { this.key = key; this.level = level; + this.defaultState = defaultState; + this.description = utils.PLUGIN.getLanguage().getString(Language.LangSection.PERMISSION, name().toLowerCase().replace("_", "-"), "description"); } @Override @@ -70,8 +81,12 @@ public String getValue() { return this.toString(); } - public Permission getPerm() { - return new Permission(toString()); + public static void registerPermissions() { + for (Permissions perm : values()) { + Permission permission = perm.getPerm(); + Bukkit.getPluginManager().addPermission(permission); + plugin.getDebugger().log("Permission registered: " + permission, DebugLevels.STARTUP); + } } public static boolean hasPermission(Player player, Permissions permission) { @@ -87,7 +102,19 @@ public static boolean isAdminEnabled(Player player) { return hasPermission(player, Permissions.ADMIN) && plugin.getDataStorage().loadPlayer(player.getUniqueId()).isAdminEnabled(); } + public Permission getPerm() { + return new Permission(toString(), getDescription(), getDefaultState()); + } + public int getLevel() { return level; } + + public PermissionDefault getDefaultState() { + return PermissionDefault.valueOf(defaultState); + } + + public String getDescription() { + return description; + } } \ No newline at end of file diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index eea3bb34..b9399cd5 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -437,4 +437,24 @@ message: failed-trade: default: "&cThe Trade has failed for unknown reasons, please notify an Admin or submit a bug report using '/ts bug'!" pre-comment: "Text to display when a player is too far from a sign" - \ No newline at end of file +permission: + help: + description: 'Allows players to view the help menu containing only commands they have permission to use.' + create: + description: 'Allows players to create standard `Trade` Shops.' + createi: + description: 'Allows players to create infinite `iTrade` Shops.' + createbi: + description: 'Allows players to create bi-directional `biTrade` Shops.' + admin: + description: 'Allows players to use administrator commands as well as giving administrator access to Shop storages. The player must also enable admin mode through commands when they wish to use these privileges.' + edit: + description: 'Allows players to use the edit gui on shops they have created or have a sufficient role for.' + info: + description: 'Allows players to use informational commands on any shops they can see.' + manage-plugin: + description: 'Allows players to use commands that provide plugin management.' + prevent-trade: + description: 'Depreciated, please remove `trade` permission instead.' + trade: + description: 'Allows players to trade with TradeShops.' \ No newline at end of file From a6ca2f14681163bed57946c3f5f0fbbed6615038 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 13 Jun 2022 15:24:41 -0700 Subject: [PATCH 16/53] Bug Fix - Fix for my stupid debug output --- .../java/org/shanerx/tradeshop/data/config/ConfigManager.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java index 44537f60..e0e9b406 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java @@ -29,7 +29,6 @@ import com.google.common.base.Charsets; import com.google.common.io.Files; import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; @@ -203,7 +202,6 @@ private boolean addKeyValue(String node, Object value) { for (Map.Entry entry : ((Map) value).entrySet()) { String newNode = node + "." + entry.getKey().toString(); if (config.get(newNode) == null || (config.get(newNode) != null && config.get(newNode).toString().isEmpty())) { - Bukkit.getLogger().log(Level.WARNING, "TS reload issue ->\n" + newNode + " = " + config.get(newNode).toString() + " | " + entry.getValue().toString()); config.set(newNode, entry.getValue().toString()); return true; } From c322060556f0fb6273fb597f1c64532e1b38297c Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 13 Jun 2022 16:26:45 -0700 Subject: [PATCH 17/53] Bug Fix and Improvements - Fix for more stupid mistakes - Removed `Internal Permissions` as it is replaced by `Registered Permissions` #138 - fixed phrasing in `NO_TRADE_PERMISSION` pre-comment and `NO_TS_CREATE_PERMISSION` default message - Prevent NONE permission from registering - Added Permission registration debug to STARTUP level - Fixed many places where getUsersUUID was not provided with which roles to get users for - Fixed not checking for Create permission in CreateShop method allowing anyone to create and shop type by placing the sign --- .../java/org/shanerx/tradeshop/TradeShop.java | 10 --- .../commandrunners/ShopUserCommand.java | 4 +- .../tradeshop/data/config/ConfigManager.java | 1 - .../tradeshop/data/config/Setting.java | 1 - .../shanerx/tradeshop/player/Permissions.java | 64 ++++++++----------- .../tradeshop/player/PlayerSetting.java | 17 ++--- .../java/org/shanerx/tradeshop/shop/Shop.java | 8 +-- .../listeners/ShopProtectionListener.java | 5 +- .../shop/listeners/ShopTradeListener.java | 5 +- .../tradeshop/utils/MetricsManager.java | 2 - .../org/shanerx/tradeshop/utils/Utils.java | 5 ++ src/main/resources/Lang/en-us.yml | 7 +- 12 files changed, 48 insertions(+), 81 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/TradeShop.java b/src/main/java/org/shanerx/tradeshop/TradeShop.java index 975c6d1a..9b905a16 100644 --- a/src/main/java/org/shanerx/tradeshop/TradeShop.java +++ b/src/main/java/org/shanerx/tradeshop/TradeShop.java @@ -59,8 +59,6 @@ public class TradeShop extends JavaPlugin { private final NamespacedKey signKey = new NamespacedKey(this, "tradeshop-sign-data"); private MetricsManager metricsManager; - - private boolean useInternalPerms = false; private boolean skipHopperProtection = false; private ListManager lists; @@ -141,14 +139,6 @@ public void onDisable() { getListManager().clearManager(); } - public boolean useInternalPerms() { - return useInternalPerms; - } - - public void setUseInternalPerms(boolean useInternalPerms) { - this.useInternalPerms = useInternalPerms; - } - public boolean doSkipHopperProtection() { return skipHopperProtection; } diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java index 2a9c0e5a..c53b703b 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java @@ -160,14 +160,14 @@ public void editUser(ShopRole role, ShopChange change) { { switch (change) { case REMOVE_USER: - if (!shop.getUsersUUID().contains(target.getUniqueId())) { + if (!shop.getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(target.getUniqueId())) { updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_MISSING.toString()); break eachOwnedShop; } break; case ADD_MANAGER: case ADD_MEMBER: - if (shop.getUsersUUID().contains(target.getUniqueId())) { + if (shop.getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(target.getUniqueId())) { updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_EXISTING.toString()); break eachOwnedShop; } else if (shop.getUsers(ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt()) { diff --git a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java index e0e9b406..fb5ed21a 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java @@ -105,7 +105,6 @@ public void reload() { switch (configType) { case CONFIG: hasUpgraded.add(Setting.upgrade()); - PLUGIN.setUseInternalPerms(Setting.USE_INTERNAL_PERMISSIONS.getBoolean()); break; case MESSAGES: hasUpgraded.add(Message.upgrade()); diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 9a4f6a53..45721418 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -50,7 +50,6 @@ public enum Setting { CHECK_UPDATES(SettingSection.SYSTEM_OPTIONS, "check-updates", true), ALLOW_METRICS(SettingSection.SYSTEM_OPTIONS, "allow-metrics", true), UNLIMITED_ADMIN(SettingSection.SYSTEM_OPTIONS, "unlimited-admin", false), - USE_INTERNAL_PERMISSIONS(SettingSection.SYSTEM_OPTIONS, "use-internal-permissions", false), // Language Options MESSAGE_PREFIX(SettingSection.LANGUAGE_OPTIONS, "message-prefix", "&a[&eTradeShop&a] "), diff --git a/src/main/java/org/shanerx/tradeshop/player/Permissions.java b/src/main/java/org/shanerx/tradeshop/player/Permissions.java index ac217cc9..15311b18 100644 --- a/src/main/java/org/shanerx/tradeshop/player/Permissions.java +++ b/src/main/java/org/shanerx/tradeshop/player/Permissions.java @@ -35,39 +35,35 @@ import org.shanerx.tradeshop.utils.debug.DebugLevels; public enum Permissions { - //Available defaultState options are: `true`, `false`, `op`, and `not_op` - HELP("help", 0, "true"), + HELP("help", PermissionDefault.TRUE), - CREATE("create", 0, "true"), + CREATE("create", PermissionDefault.TRUE), - CREATEI("create.infinite", 1, "op"), + CREATEI("create.infinite", PermissionDefault.OP), - CREATEBI("create.bi", 0, "true"), + CREATEBI("create.bi", PermissionDefault.TRUE), - ADMIN("admin", 1, "op"), + ADMIN("admin", PermissionDefault.OP), - EDIT("edit", 0, "true"), // non admin perm + EDIT("edit", PermissionDefault.TRUE), // non admin perm - INFO("info", 0, "true"), + INFO("info", PermissionDefault.TRUE), - MANAGE_PLUGIN("manage-plugin", 2, "op"), + MANAGE_PLUGIN("manage-plugin", PermissionDefault.OP), - PREVENT_TRADE("prevent-trade", -1, "false"), + TRADE("trade", PermissionDefault.TRUE), - TRADE("trade", 0, "true"), - - NONE("", 0, "true"); + NONE("", PermissionDefault.TRUE); private final static TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); private final Utils utils = new Utils(); private final String key; - private final int level; - private final String defaultState, description; + private final PermissionDefault defaultState; + private final String description; - Permissions(String key, int level, String defaultState) { + Permissions(String key, PermissionDefault defaultState) { this.key = key; - this.level = level; this.defaultState = defaultState; this.description = utils.PLUGIN.getLanguage().getString(Language.LangSection.PERMISSION, name().toLowerCase().replace("_", "-"), "description"); } @@ -83,38 +79,28 @@ public String getValue() { public static void registerPermissions() { for (Permissions perm : values()) { - Permission permission = perm.getPerm(); - Bukkit.getPluginManager().addPermission(permission); - plugin.getDebugger().log("Permission registered: " + permission, DebugLevels.STARTUP); + if (!perm.equals(Permissions.NONE)) { + Permission permission = perm.getPerm(); + Bukkit.getPluginManager().addPermission(permission); + plugin.getDebugger().log("Permission registered: " + permission.getName() + " | State: " + permission.getDefault(), DebugLevels.STARTUP); + } } + + StringBuilder str = new StringBuilder(); + str.append("defaultPermissions: \n"); + Bukkit.getPluginManager().getDefaultPermissions(false).forEach((perm) -> str.append(perm.getName()).append("\n")); + plugin.getDebugger().log(str.toString(), DebugLevels.STARTUP); } public static boolean hasPermission(Player player, Permissions permission) { - if (plugin.useInternalPerms()) { - return plugin.getDataStorage().loadPlayer(player.getUniqueId()).getType() >= permission.getLevel(); - } else { - return permission.equals(Permissions.NONE) || player.hasPermission(permission.getPerm()); - } + return permission.equals(Permissions.NONE) || player.hasPermission(permission.getPerm()); } - public static boolean isAdminEnabled(Player player) { return hasPermission(player, Permissions.ADMIN) && plugin.getDataStorage().loadPlayer(player.getUniqueId()).isAdminEnabled(); } public Permission getPerm() { - return new Permission(toString(), getDescription(), getDefaultState()); - } - - public int getLevel() { - return level; - } - - public PermissionDefault getDefaultState() { - return PermissionDefault.valueOf(defaultState); - } - - public String getDescription() { - return description; + return new Permission(toString(), description, defaultState); } } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java index 1cf5f09d..42577f80 100644 --- a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java +++ b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java @@ -53,7 +53,7 @@ public class PlayerSetting implements Serializable { private boolean showInvolvedStatus, adminEnabled = true; - private int type = 0, multi = Setting.MULTI_TRADE_DEFAULT.getInt(); + private int multi = Setting.MULTI_TRADE_DEFAULT.getInt(); private final Set staffShops; private transient Utils utils = new Utils(); @@ -61,7 +61,6 @@ public PlayerSetting(UUID playerUUID, Map data) { this.uuid = playerUUID; this.uuidString = uuid.toString(); - if (data.containsKey("type")) type = data.get("type"); if (data.containsKey("multi")) multi = data.get("multi"); ownedShops = Sets.newHashSet(); @@ -94,14 +93,6 @@ public void setAdminEnabled(boolean adminEnabled) { this.adminEnabled = adminEnabled; } - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - public int getMulti() { return multi; } @@ -118,7 +109,7 @@ public void addShop(Shop shop) { if (shop.getOwner().getUUID().equals(uuid) && !ownedShops.contains(shop.getShopLocationAsSL().serialize())) ownedShops.add(shop.getShopLocationAsSL().serialize()); - else if (shop.getUsersUUID().contains(uuid) && + else if (shop.getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(uuid) && !ownedShops.contains(shop.getShopLocationAsSL().serialize())) staffShops.add(shop.getShopLocationAsSL().serialize()); } @@ -133,8 +124,8 @@ public void removeShop(String shop) { staffShops.remove(shop); } - public void updateShops(Shop shop) { - if (!shop.getUsersUUID().contains(uuid)) + public void updateShop(Shop shop) { + if (!shop.getUsersUUID(ShopRole.OWNER, ShopRole.MANAGER, ShopRole.MEMBER).contains(uuid)) removeShop(shop); else addShop(shop); diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 6bdc4d44..5ba947e5 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -741,7 +741,7 @@ public boolean addUser(UUID newUser, ShopRole role) { return false; boolean ret = false; - if (!getUsersUUID().contains(newUser)) { + if (!getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(newUser)) { switch (role) { case MANAGER: managers.add(newUser); @@ -837,9 +837,9 @@ public boolean setUsers(Set users, ShopRole role) { */ private void updateUserFiles() { TradeShop plugin = new Utils().PLUGIN; - for (UUID user : getUsersUUID()) { + for (UUID user : getUsersUUID(ShopRole.OWNER, ShopRole.MANAGER, ShopRole.MEMBER)) { PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(user); - playerSetting.updateShops(this); + playerSetting.updateShop(this); plugin.getDataStorage().savePlayer(playerSetting); } } @@ -849,7 +849,7 @@ private void updateUserFiles() { */ private void purgeFromUserFiles() { TradeShop plugin = new Utils().PLUGIN; - for (UUID user : getUsersUUID()) { + for (UUID user : getUsersUUID(ShopRole.OWNER, ShopRole.MANAGER, ShopRole.MEMBER)) { PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(user); playerSetting.removeShop(this); plugin.getDataStorage().savePlayer(playerSetting); diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java index 4f8f9c6d..63cdc20a 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java @@ -49,6 +49,7 @@ import org.shanerx.tradeshop.framework.events.PlayerShopDestroyEvent; import org.shanerx.tradeshop.framework.events.PlayerShopInventoryOpenEvent; import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shop.ShopChest; import org.shanerx.tradeshop.shop.ShopType; @@ -309,7 +310,7 @@ public void onChestOpen(PlayerInteractEvent e) { return; } - if (!Permissions.isAdminEnabled(e.getPlayer()) && !shop.getUsersUUID().contains(e.getPlayer().getUniqueId())) { + if (!Permissions.isAdminEnabled(e.getPlayer()) && !shop.getUsersUUID(ShopRole.OWNER, ShopRole.MANAGER, ShopRole.MEMBER).contains(e.getPlayer().getUniqueId())) { openEvent.setCancelled(true); } @@ -342,7 +343,7 @@ public void onBlockPlace(BlockPlaceEvent event) { if (shop.getShopType().isITrade()) return; - if (shop.getUsersUUID().contains(event.getPlayer().getUniqueId())) { + if (shop.getUsersUUID(ShopRole.OWNER, ShopRole.MANAGER).contains(event.getPlayer().getUniqueId())) { if (!shop.hasStorage()) { new ShopChest(block, shop.getOwner().getUUID(), shopSign.getLocation()).setEventName(event); shop.setInventoryLocation(block.getLocation()); diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java index c4bba16c..68bf8011 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java @@ -47,6 +47,7 @@ import org.shanerx.tradeshop.framework.events.PlayerSuccessfulTradeEvent; import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.player.Permissions; +import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.shop.ExchangeStatus; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shop.ShopType; @@ -90,7 +91,7 @@ public void onBlockInteract(PlayerInteractEvent e) { return; } - if (Permissions.hasPermission(buyer, Permissions.PREVENT_TRADE) && !buyer.isOp()) { + if (!Permissions.hasPermission(buyer, Permissions.TRADE)) { Message.NO_TRADE_PERMISSION.sendMessage(buyer); return; } @@ -99,7 +100,7 @@ public void onBlockInteract(PlayerInteractEvent e) { return; } - if (!shop.getShopType().equals(ShopType.ITRADE) && shop.getUsersUUID().contains(buyer.getUniqueId()) && !Setting.ALLOW_USER_PURCHASING.getBoolean()) { + if (!shop.getShopType().equals(ShopType.ITRADE) && shop.getUsersUUID(ShopRole.OWNER, ShopRole.MANAGER, ShopRole.MEMBER).contains(buyer.getUniqueId()) && !Setting.ALLOW_USER_PURCHASING.getBoolean()) { Message.SELF_OWNED.sendMessage(buyer); return; } diff --git a/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java b/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java index 78f34f32..e227c8f3 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java +++ b/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java @@ -102,7 +102,6 @@ public Map call() throws Exception { Map map = new HashMap<>(); List booleanSettingList = Arrays.asList(Setting.CHECK_UPDATES, Setting.UNLIMITED_ADMIN, - Setting.USE_INTERNAL_PERMISSIONS, Setting.ALLOW_TOGGLE_STATUS, Setting.ALLOW_SIGN_BREAK, Setting.ALLOW_CHEST_BREAK, @@ -223,7 +222,6 @@ private void addOtherSettingMetrics() { private void addFeaturePieMetrics() { List booleanSettingList = Arrays.asList(Setting.CHECK_UPDATES, Setting.UNLIMITED_ADMIN, - Setting.USE_INTERNAL_PERMISSIONS, Setting.ALLOW_TOGGLE_STATUS, Setting.ALLOW_SIGN_BREAK, Setting.ALLOW_CHEST_BREAK, diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index fedfb4d5..6dccc07a 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -486,6 +486,11 @@ public Shop createShop(Sign shopSign, Player creator, ShopType shopType, ItemSta return null; } + if (!shopType.checkPerm(creator)) { + Message.NO_TS_CREATE_PERMISSION.sendMessage(creator); + return null; + } + ShopUser owner = new ShopUser(creator, ShopRole.OWNER); if (!checkShopChest(shopSign.getBlock()) && !shopType.isITrade()) { diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index b9399cd5..8996f62e 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -99,9 +99,6 @@ setting: pre-comment: "Allow us to connect anonymous metrics so we can see how our plugin is being used to better develop it" unlimited-admin: pre-comment: "We do not recommend enabling this setting since any editing an admin should need to do can be done without this.\n Should players with Admin permission be able to use any commands on any shops?" - use-internal-permissions: - pre-comment: "Should our internal permission system be used? (Only enable if you aren't using a permission plugin)" - post-comment: "\n" language-options: message-prefix: pre-comment: "The prefix the displays before all plugin messages" @@ -341,12 +338,12 @@ message: default: "&cYou do not have permission to edit that shop." no-trade-permission: default: "&cYou do not have permission to trade with TradeShops" - pre-comment: "Text to display when a player attempts to trade while having the `Prevent Trade` permission:" + pre-comment: "Text to display when a player attempts to trade while not having the `Trade` permission:" no-sighted-shop: default: "&cNo shop in range!" pre-comment: "Text to display when a player is too far from a shop" no-ts-create-permission: - default: "&cYou don't have permission to create TradeShops!" + default: "&cYou don't have permission to create this type of TradeShop!" pre-comment: "Text to display when a player attempts to setup a shoptype they are not allowed to create:" no-ts-destroy: default: "&cYou may not destroy that TradeShop" From aae215a1183349306011736bb89ae80fca82fedd Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 13 Jun 2022 16:31:18 -0700 Subject: [PATCH 18/53] Bug Fix and Improvements - Remove `Player Level` command --- .../tradeshop/commands/CommandCaller.java | 3 -- .../tradeshop/commands/CommandTabCaller.java | 1 - .../shanerx/tradeshop/commands/Commands.java | 1 - .../commands/commandrunners/AdminCommand.java | 29 ------------------- 4 files changed, 34 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java index ee98c192..27666d66 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandCaller.java @@ -154,9 +154,6 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String case REMOVE_COST: new ShopItemCommand(plugin, cmdPass, ShopItemSide.COST).removeSide(); break; - case PLAYER_LEVEL: - new AdminCommand(plugin, cmdPass).playerLevel(); - break; case STATUS: new GeneralPlayerCommand(plugin, cmdPass).status(); break; diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java index 579c836e..509636d0 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCaller.java @@ -77,7 +77,6 @@ public List onTabComplete(CommandSender sender, Command cmd, String labe case ADD_MEMBER: case SET_MEMBER: case SET_MANAGER: - case PLAYER_LEVEL: return tabCompleter.fillServerPlayer(); default: return Collections.EMPTY_LIST; diff --git a/src/main/java/org/shanerx/tradeshop/commands/Commands.java b/src/main/java/org/shanerx/tradeshop/commands/Commands.java index e04df6e4..1ba23831 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/Commands.java +++ b/src/main/java/org/shanerx/tradeshop/commands/Commands.java @@ -79,7 +79,6 @@ public enum Commands { HELP(Lists.newArrayList("help", "?"), Permissions.HELP, 1, 2, false, "Display help message", "/tradeshop $cmd$ [command]"), SETUP(Lists.newArrayList("setup", "start", "create", "make"), Permissions.HELP, 1, 1, false, "Display shop setup tutorial", "/tradeshop $cmd$"), BUGS(Lists.newArrayList("bugs", "bug"), Permissions.NONE, 1, 1, false, "Report bugs to the developers", "/tradeshop $cmd$"), - PLAYER_LEVEL(Lists.newArrayList("playerlevel", "pl"), Permissions.MANAGE_PLUGIN, 2, 3, false, "If Internal Permissions is enable this allows the getting and setting of player permission levels.", "/tradeshop $cmd$ "), TOGGLE_ADMIN(Lists.newArrayList("toggleadmin", "tadmin", "ta"), Permissions.ADMIN, 1, 1, true, "Toggles Admin mode for players with the admin permission", "/tradeshop $cmd$"), ADMIN(Lists.newArrayList("admin"), Permissions.ADMIN, 1, 2, true, "Shows players their current admin mode or changes with optional variable", "/tradeshop $cmd$ [True/False]"), RELOAD(Lists.newArrayList("reload"), Permissions.MANAGE_PLUGIN, 1, 1, false, "Reload configuration files", "/tradeshop $cmd$"); diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java index 106b396a..c065d34c 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java @@ -108,33 +108,4 @@ public void admin() { Message.ADMIN_TOGGLED.sendMessage(pSender, new Tuple<>(Variable.STATE.toString(), playerSetting.isAdminEnabled() ? "enabled" : "disabled")); } - - /** - * Changes/Sets the players permission level if internal permissions is enabled - */ - public void playerLevel() { - if (Bukkit.getOfflinePlayer(command.getArgAt(1)).hasPlayedBefore()) { - PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(Bukkit.getOfflinePlayer(command.getArgAt(1)).getUniqueId()); - if (command.argsSize() == 2) { - Message.VIEW_PLAYER_LEVEL.sendMessage(pSender, - new Tuple<>(Variable.PLAYER.toString(), Bukkit.getOfflinePlayer(command.getArgAt(1)).getName()), - new Tuple<>(Variable.LEVEL.toString(), playerSetting.getType() + "")); - } else { - if (isInt(command.getArgAt(2))) { - int newLevel = Integer.parseInt(command.getArgAt(2)); - - playerSetting.setType(newLevel); - plugin.getDataStorage().savePlayer(playerSetting); - - Message.SET_PLAYER_LEVEL.sendMessage(pSender, - new Tuple<>(Variable.PLAYER.toString(), Bukkit.getOfflinePlayer(command.getArgAt(1)).getName()), - new Tuple<>(Variable.LEVEL.toString(), playerSetting.getType() + "")); - } else { - Message.INVALID_ARGUMENTS.sendMessage(pSender); - } - } - } else { - Message.PLAYER_NOT_FOUND.sendMessage(pSender); - } - } } From 2cfd3aa6a6bf740c08f9a75ab421e84be1d62c11 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Tue, 14 Jun 2022 14:07:07 -0700 Subject: [PATCH 19/53] Bug Fix - Fix for double message when shop could not be found during ShopUserCommands - Added all as an option for targeting all shops when using ShopUserCommands --- .../tradeshop/commands/commandrunners/ShopUserCommand.java | 4 ++-- src/main/java/org/shanerx/tradeshop/utils/Utils.java | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java index c53b703b..40c19697 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java @@ -137,7 +137,7 @@ public void who() { * Adds or Removes the specified player to/from the shop as the specified role */ public void editUser(ShopRole role, ShopChange change) { - boolean applyAllOwned = command.hasArgAt(2) && toBool(command.getArgAt(2)); + boolean applyAllOwned = command.hasArgAt(2) && command.getArgAt(2).length() > 0 && toBool(command.getArgAt(2)); Set ownedShops = new HashSet<>(); Map updateStatuses = new HashMap<>(); @@ -236,7 +236,7 @@ private Shop shopUserCommandStart(boolean applyAllOwned) { Shop shop = findShop(); if (shop == null) { - Message.NO_SIGHTED_SHOP.sendMessage(pSender); + // Message.NO_SIGHTED_SHOP.sendMessage(pSender); // Message is sent by findShop() target = null; return null; } diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 6dccc07a..a5c15933 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -689,6 +689,7 @@ public boolean toBool(String check) { case "t": case "yes": case "y": + case "all": return true; default: return false; From 2322feabd04e84dde4bc89b5c645fac5b8e332c1 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Tue, 14 Jun 2022 18:44:10 -0700 Subject: [PATCH 20/53] Mapped Setting Improvements - Mapped Setting now supports nested maps(so section > setting groups can be generated) this has no limit but cannot be changed externally so it should be fine and not encounter any un-ending loops - Changed Per-Item settings to use Mapped values instead of individual settings and sections - Changed ShopItemStackSettingKeys to load settings on each get call rather than when enums are created(since I think the latter could have problems when reloading) --- .../tradeshop/data/config/Setting.java | 77 +++++------ .../tradeshop/data/config/SettingSection.java | 44 ++----- .../item/ShopItemStackSettingKeys.java | 69 ++++++---- src/main/resources/Lang/en-us.yml | 120 +----------------- 4 files changed, 96 insertions(+), 214 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 45721418..955d2313 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -28,10 +28,13 @@ import org.bukkit.Bukkit; import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.item.IllegalItemList; +import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; import org.shanerx.tradeshop.shop.ShopSign; import org.yaml.snakeyaml.Yaml; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -83,48 +86,9 @@ public enum Setting { ALLOW_USER_PURCHASING(SettingSection.SHOP_OPTIONS, "allow-user-purchasing", false), MULTIPLE_ITEMS_ON_SIGN(SettingSection.SHOP_OPTIONS, "multiple-items-on-sign", "Use '/ts what'"), - //region Shop Item Settings - //------------------------------------------------------------------------------------------------------------------ - COMPARE_DURABILITY_DEFAULT(SettingSection.COMPARE_DURABILITY, "default", 1), - COMPARE_ENCHANTMENTS_DEFAULT(SettingSection.COMPARE_ENCHANTMENTS, "default", true), - COMPARE_NAME_DEFAULT(SettingSection.COMPARE_NAME, "default", true), - COMPARE_LORE_DEFAULT(SettingSection.COMPARE_LORE, "default", true), - COMPARE_CUSTOM_MODEL_DATA_DEFAULT(SettingSection.COMPARE_CUSTOM_MODEL_DATA, "default", true), - COMPARE_ITEM_FLAGS_DEFAULT(SettingSection.COMPARE_ITEM_FLAGS, "default", true), - COMPARE_UNBREAKABLE_DEFAULT(SettingSection.COMPARE_UNBREAKABLE, "default", true), - COMPARE_ATTRIBUTE_MODIFIER_DEFAULT(SettingSection.COMPARE_ATTRIBUTE_MODIFIER, "default", true), - COMPARE_BOOK_AUTHOR_DEFAULT(SettingSection.COMPARE_BOOK_AUTHOR, "default", true), - COMPARE_BOOK_PAGES_DEFAULT(SettingSection.COMPARE_BOOK_PAGES, "default", true), - COMPARE_SHULKER_INVENTORY_DEFAULT(SettingSection.COMPARE_SHULKER_INVENTORY, "default", true), - COMPARE_BUNDLE_INVENTORY_DEFAULT(SettingSection.COMPARE_BUNDLE_INVENTORY, "default", true), - COMPARE_FIREWORK_DURATION_DEFAULT(SettingSection.COMPARE_FIREWORK_DURATION, "default", true), - COMPARE_FIREWORK_EFFECTS_DEFAULT(SettingSection.COMPARE_FIREWORK_EFFECTS, "default", true), - - //Shop Item Setting User Editable Options - COMPARE_DURABILITY_USER_EDITABLE(SettingSection.COMPARE_DURABILITY, "user-editable", true), - COMPARE_ENCHANTMENTS_USER_EDITABLE(SettingSection.COMPARE_ENCHANTMENTS, "user-editable", true), - COMPARE_NAME_USER_EDITABLE(SettingSection.COMPARE_NAME, "user-editable", true), - COMPARE_LORE_USER_EDITABLE(SettingSection.COMPARE_LORE, "user-editable", true), - COMPARE_CUSTOM_MODEL_DATA_USER_EDITABLE(SettingSection.COMPARE_CUSTOM_MODEL_DATA, "user-editable", true), - COMPARE_ITEM_FLAGS_USER_EDITABLE(SettingSection.COMPARE_ITEM_FLAGS, "user-editable", true), - COMPARE_UNBREAKABLE_USER_EDITABLE(SettingSection.COMPARE_UNBREAKABLE, "user-editable", true), - COMPARE_ATTRIBUTE_MODIFIER_USER_EDITABLE(SettingSection.COMPARE_ATTRIBUTE_MODIFIER, "user-editable", true), - COMPARE_BOOK_AUTHOR_USER_EDITABLE(SettingSection.COMPARE_BOOK_AUTHOR, "user-editable", true), - COMPARE_BOOK_PAGES_USER_EDITABLE(SettingSection.COMPARE_BOOK_PAGES, "user-editable", true), - COMPARE_SHULKER_INVENTORY_USER_EDITABLE(SettingSection.COMPARE_SHULKER_INVENTORY, "user-editable", true), - COMPARE_BUNDLE_INVENTORY_USER_EDITABLE(SettingSection.COMPARE_BUNDLE_INVENTORY, "user-editable", true), - COMPARE_FIREWORK_DURATION_USER_EDITABLE(SettingSection.COMPARE_FIREWORK_DURATION, "user-editable", true), - COMPARE_FIREWORK_EFFECTS_USER_EDITABLE(SettingSection.COMPARE_FIREWORK_EFFECTS, "user-editable", true), - - //------------------------------------------------------------------------------------------------------------------ - //endregion - - //region Shop Sign Settings - //------------------------------------------------------------------------------------------------------------------ - SHOP_SIGN_DEFAULT_COLOURS(SettingSection.SHOP_SIGN_OPTIONS, "sign-default-colours", ShopSign.getDefaultColourMap()), + SHOP_PER_ITEM_SETTINGS(SettingSection.SHOP_ITEM_OPTIONS, "shop-per-item-settings", ShopItemStackSettingKeys.getDefaultConfigMap()), - //------------------------------------------------------------------------------------------------------------------ - //endregion + SHOP_SIGN_DEFAULT_COLOURS(SettingSection.SHOP_SIGN_OPTIONS, "sign-default-colours", ShopSign.getDefaultColourMap()), // Trade Shop Options TRADESHOP_HEADER(SettingSection.TRADE_SHOP_OPTIONS, "header", "Trade"), @@ -159,6 +123,8 @@ public enum Setting { private final Object defaultValue; private final SettingSection section; + private final String leadIncrease = " "; + Setting(SettingSection section, String key, Object defaultValue) { this.section = section; this.key = key; @@ -273,6 +239,10 @@ public boolean getMappedBoolean(String subKey) { return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getBoolean(subKey.toLowerCase().replace("_", "-")); } + public Object getMappedObject(String subKey) { + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).get(subKey.toLowerCase().replace("_", "-")); + } + public String getPostComment() { return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING, path); } @@ -289,6 +259,27 @@ public String getPath() { return path; } + private String processMapValue(Map valueMap, String localLead) { + StringBuilder processed = new StringBuilder(); + + List sortedKeys = new ArrayList<>(valueMap.keySet()); + Collections.sort(sortedKeys, (o1, o2) -> o1.toString().compareTo(o1.toString())); + + //PLUGIN.getDebugger().log("Sorted Value: " + sortedValue +"\nValue: " + valueMap, DebugLevels.DATA_ERROR); + + for (Object key : sortedKeys) { + Object value = valueMap.get(key); + if (value instanceof Map) { + processed.append(localLead).append(getKey()).append(":\n"); + processed.append(processMapValue(((Map) value), localLead + leadIncrease)); + } else { + processed.append(localLead).append(key.toString()).append(": ").append(new Yaml().dump(value)); + } + } + + return processed.toString(); + } + public String getFileString() { StringBuilder keyOutput = new StringBuilder(); @@ -298,9 +289,7 @@ public String getFileString() { if (defaultValue instanceof Map) { keyOutput.append(section.getSectionLead()).append(getKey()).append(":\n"); - for (Map.Entry entry : ((Map) defaultValue).entrySet()) { - keyOutput.append(section.getSectionLead() + " ").append(entry.getKey().toString()).append(": ").append(new Yaml().dump(entry.getValue())); - } + keyOutput.append(processMapValue(((Map) defaultValue), section.getSectionLead() + leadIncrease)); } else { keyOutput.append(section.getSectionLead()).append(getKey()).append(": ").append(new Yaml().dump(getSetting())); } diff --git a/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java index 828b28c1..43014fc8 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java @@ -41,32 +41,14 @@ public enum SettingSection { GLOBAL_MULTI_TRADE(50, GLOBAL_OPTIONS, "multi-trade"), SHOP_OPTIONS(4, "shop-options"), - //region Shop Item Settings - //------------------------------------------------------------------------------------------------------------------ - SHOP_ITEM_SETTINGS(50, SHOP_OPTIONS, "shop-item-default-settings-options"), - COMPARE_DURABILITY(100, SHOP_ITEM_SETTINGS, "compare-durability"), - COMPARE_ENCHANTMENTS(101, SHOP_ITEM_SETTINGS, "compare-enchantments"), - COMPARE_NAME(102, SHOP_ITEM_SETTINGS, "compare-name"), - COMPARE_LORE(103, SHOP_ITEM_SETTINGS, "compare-lore"), - COMPARE_CUSTOM_MODEL_DATA(104, SHOP_ITEM_SETTINGS, "compare-custom-data-model"), - COMPARE_ITEM_FLAGS(105, SHOP_ITEM_SETTINGS, "compare-item-flags"), - COMPARE_UNBREAKABLE(106, SHOP_ITEM_SETTINGS, "compare-unbreakable"), - COMPARE_ATTRIBUTE_MODIFIER(107, SHOP_ITEM_SETTINGS, "compare-attribute-modifier"), - COMPARE_BOOK_AUTHOR(108, SHOP_ITEM_SETTINGS, "compare-book-author"), - COMPARE_BOOK_PAGES(109, SHOP_ITEM_SETTINGS, "compare-book-pages"), - COMPARE_SHULKER_INVENTORY(110, SHOP_ITEM_SETTINGS, "compare-shulker-inventory"), - COMPARE_BUNDLE_INVENTORY(111, SHOP_ITEM_SETTINGS, "compare-bundle-inventory"), - COMPARE_FIREWORK_DURATION(112, SHOP_ITEM_SETTINGS, "compare-firework-duration"), - COMPARE_FIREWORK_EFFECTS(113, SHOP_ITEM_SETTINGS, "compare-firework-effects"), - //------------------------------------------------------------------------------------------------------------------ - //endregion - - SHOP_SIGN_OPTIONS(5, "shop-sign-options"), - - TRADE_SHOP_OPTIONS(6, "trade-shop-options"), - ITRADE_SHOP_OPTIONS(7, "itrade-shop-options"), - BITRADE_SHOP_OPTIONS(8, "bitrade-shop-options"), - ILLEGAL_ITEM_OPTIONS(9, "illegal-item-options"), + SHOP_ITEM_OPTIONS(5, SHOP_OPTIONS, "shop-per-item-options"), + + SHOP_SIGN_OPTIONS(6, "shop-sign-options"), + + TRADE_SHOP_OPTIONS(7, "trade-shop-options"), + ITRADE_SHOP_OPTIONS(8, "itrade-shop-options"), + BITRADE_SHOP_OPTIONS(9, "bitrade-shop-options"), + ILLEGAL_ITEM_OPTIONS(10, "illegal-item-options"), GLOBAL_ILLEGAL_ITEMS(50, ILLEGAL_ITEM_OPTIONS, "global-illegal-items"), COST_ILLEGAL_ITEMS(51, ILLEGAL_ITEM_OPTIONS, "cost-illegal-items"), PRODUCT_ILLEGAL_ITEMS(52, ILLEGAL_ITEM_OPTIONS, "product-illegal-items"); @@ -85,7 +67,7 @@ public enum SettingSection { this.weight = weight; this.key = key; this.parent = parent; - this.lineLead = !key.isEmpty() ? parent != null ? parent.lineLead + " " : " " : ""; + this.lineLead = !key.isEmpty() ? " " : ""; } public String getKey() { @@ -113,15 +95,15 @@ public boolean hasParent() { } public String getPostComment() { - return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING_SECTION, name().toLowerCase().replace("_", "-")); + return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING_SECTION, key); } public String getPreComment() { - return PLUGIN.getLanguage().getPreComment(Language.LangSection.SETTING_SECTION, name().toLowerCase().replace("_", "-")); + return PLUGIN.getLanguage().getPreComment(Language.LangSection.SETTING_SECTION, key); } public String getSectionHeader() { - return PLUGIN.getLanguage().getHeader(Language.LangSection.SETTING_SECTION, name().toLowerCase().replace("_", "-")); + return PLUGIN.getLanguage().getHeader(Language.LangSection.SETTING_SECTION, key); } public String getFileString() { @@ -155,7 +137,7 @@ public String getFileString() { } // Add Sections Key line - sectionHeader.append(getLineLead()).append(getKey()).append(": ").append("\n"); + sectionHeader.append(getLineLead()).append(getKey()).append(": \n"); // If Section has a Post Comment add it if (!getPostComment().isEmpty()) { diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java index 08148492..666730fd 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java @@ -30,37 +30,50 @@ import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.utils.objects.ObjectHolder; +import java.util.HashMap; +import java.util.Map; + public enum ShopItemStackSettingKeys { //New per shop settings and their default value should be added below and will be added to the shops - COMPARE_DURABILITY(new ObjectHolder<>(Setting.COMPARE_DURABILITY_DEFAULT.getInt()), new ItemStack(Material.DAMAGED_ANVIL)), // -1 == 'off', 0 == '<=', 1 == '==', 2 == '>=' - COMPARE_ENCHANTMENTS(new ObjectHolder<>(Setting.COMPARE_ENCHANTMENTS_DEFAULT.getBoolean()), new ItemStack(Material.ENCHANTED_BOOK)), - COMPARE_NAME(new ObjectHolder<>(Setting.COMPARE_NAME_DEFAULT.getBoolean()), new ItemStack(Material.NAME_TAG)), - COMPARE_LORE(new ObjectHolder<>(Setting.COMPARE_LORE_DEFAULT.getBoolean()), new ItemStack(Material.BOOK)), - COMPARE_CUSTOM_MODEL_DATA(new ObjectHolder<>(Setting.COMPARE_CUSTOM_MODEL_DATA_DEFAULT.getBoolean()), new ItemStack(Material.STICK)), - COMPARE_ITEM_FLAGS(new ObjectHolder<>(Setting.COMPARE_ITEM_FLAGS_DEFAULT.getBoolean()), new ItemStack(Material.WHITE_BANNER)), - COMPARE_UNBREAKABLE(new ObjectHolder<>(Setting.COMPARE_UNBREAKABLE_DEFAULT.getBoolean()), new ItemStack(Material.BEDROCK)), - COMPARE_ATTRIBUTE_MODIFIER(new ObjectHolder<>(Setting.COMPARE_ATTRIBUTE_MODIFIER_DEFAULT.getBoolean()), new ItemStack(Material.BARRIER)), - COMPARE_BOOK_AUTHOR(new ObjectHolder<>(Setting.COMPARE_BOOK_AUTHOR_DEFAULT.getBoolean()), new ItemStack(Material.PLAYER_HEAD)), - COMPARE_BOOK_PAGES(new ObjectHolder<>(Setting.COMPARE_BOOK_PAGES_DEFAULT.getBoolean()), new ItemStack(Material.PAPER)), - COMPARE_SHULKER_INVENTORY(new ObjectHolder<>(Setting.COMPARE_SHULKER_INVENTORY_DEFAULT.getBoolean()), new ItemStack(Material.CHEST_MINECART)), - COMPARE_BUNDLE_INVENTORY(new ObjectHolder<>(Setting.COMPARE_BUNDLE_INVENTORY_DEFAULT.getBoolean()), new ItemStack(Material.CHEST_MINECART)), - COMPARE_FIREWORK_DURATION(new ObjectHolder<>(Setting.COMPARE_FIREWORK_DURATION_DEFAULT.getBoolean()), new ItemStack(Material.GUNPOWDER)), - COMPARE_FIREWORK_EFFECTS(new ObjectHolder<>(Setting.COMPARE_FIREWORK_EFFECTS_DEFAULT.getBoolean()), new ItemStack(Material.FIREWORK_STAR)); - - private final ObjectHolder defaultValue; - private final boolean userEditable; + COMPARE_DURABILITY(new ItemStack(Material.DAMAGED_ANVIL), 1), // -1 == 'off', 0 == '<=', 1 == '==', 2 == '>=' + COMPARE_ENCHANTMENTS(new ItemStack(Material.ENCHANTED_BOOK), true), + COMPARE_NAME(new ItemStack(Material.NAME_TAG), true), + COMPARE_LORE(new ItemStack(Material.BOOK), true), + COMPARE_CUSTOM_MODEL_DATA(new ItemStack(Material.STICK), true), + COMPARE_ITEM_FLAGS(new ItemStack(Material.WHITE_BANNER), true), + COMPARE_UNBREAKABLE(new ItemStack(Material.BEDROCK), true), + COMPARE_ATTRIBUTE_MODIFIER(new ItemStack(Material.BARRIER), true), + COMPARE_BOOK_AUTHOR(new ItemStack(Material.PLAYER_HEAD), true), + COMPARE_BOOK_PAGES(new ItemStack(Material.PAPER), true), + COMPARE_SHULKER_INVENTORY(new ItemStack(Material.CHEST_MINECART), true), + COMPARE_BUNDLE_INVENTORY(new ItemStack(Material.CHEST_MINECART), true), + COMPARE_FIREWORK_DURATION(new ItemStack(Material.GUNPOWDER), true), + COMPARE_FIREWORK_EFFECTS(new ItemStack(Material.FIREWORK_STAR), true); + private final ItemStack displayItem; + private static final String defaultKey = "default", userEditableKey = "userEditable"; + private final Object preConfigDefault; - ShopItemStackSettingKeys(ObjectHolder defaultValue, ItemStack displayItem) { - this.defaultValue = defaultValue; - this.userEditable = Setting.findSetting(this.name() + "_USER_EDITABLE").getBoolean(); + ShopItemStackSettingKeys(ItemStack displayItem, Object preConfigDefault) { this.displayItem = displayItem; + this.preConfigDefault = preConfigDefault; } - public ObjectHolder getDefaultValue() { - return defaultValue; + public static Map getDefaultConfigMap() { + Map configMap = new HashMap<>(); + + for (ShopItemStackSettingKeys value : values()) { + String key = value.getConfigName(); + Map subConfigMap = new HashMap<>(); + subConfigMap.put(defaultKey, value.preConfigDefault); + subConfigMap.put(userEditableKey, true); + + configMap.put(key, subConfigMap); + } + + return configMap; } public String makeReadable() { @@ -85,11 +98,19 @@ else if (ch == '_') } - public boolean isUserEditable() { - return userEditable; + public ObjectHolder getDefaultValue() { + return new ObjectHolder<>(Setting.SHOP_PER_ITEM_SETTINGS.getMappedObject(getConfigName() + "." + defaultKey)); } public ItemStack getDisplayItem() { return displayItem; } + + public boolean isUserEditable() { + return Setting.SHOP_PER_ITEM_SETTINGS.getMappedBoolean(getConfigName() + "." + userEditableKey); + } + + public String getConfigName() { + return name().toLowerCase().replace("_", "-"); + } } diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 8996f62e..e729bd4e 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -16,50 +16,8 @@ setting-section: header: "" shop-options: header: "Shop Options" - shop-item-default-settings-options: - header: "Shop Item Default Settings Options" - compare-durability: - header: "" - pre-comment: "Compare Durability" - compare-enchantments: - header: "" - pre-comment: "Compare Enchantments" - compare-name: - header: "" - pre-comment: "Compare Name" - compare-lore: - header: "" - pre-comment: "Compare Lore" - compare-custom-data-model: - header: "" - pre-comment: "Compare Custom Data Model" - compare-item-flags: - header: "" - pre-comment: "Compare Item Flags" - compare-unbreakable: - header: "" - pre-comment: "Compare Unbreakable" - compare-attribute-modifier: - header: "" - pre-comment: "Compare Attribute Modifier" - compare-book-author: - header: "" - pre-comment: "Compare Book Author" - compare-book-pages: - header: "" - pre-comment: "Compare Book Pages" - compare-shulker-inventory: - header: "" - pre-comment: "Compare Shulker Inventory" - compare-bundle-inventory: - header: "" - pre-comment: "Compare Bundle Inventory" - compare-firework-duration: - header: "" - pre-comment: "Compare Firework Duration" - compare-firework-effects: - header: "" - pre-comment: "Compare Firework Effects" + shop-per-item-options: + header: "Shop Per Item Options" shop-sign-options: header: "Shop Sign Options" trade-shop-options: @@ -169,77 +127,9 @@ setting: multiple-items-on-sign: pre-comment: "Text that shows on trade signs that contain more than 1 item\n Available variables are: %AMOUNT%" post-comment: "\n" - shop-item-default-settings-options: - compare-durability: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-enchantments: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-name: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-lore: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-custom-data-model: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-item-flags: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-unbreakable: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-attribute-modifier: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-book-author: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-book-pages: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-shulker-inventory: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-bundle-inventory: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-firework-duration: - default: - pre-comment: "" - user-editable: - pre-comment: "" - compare-firework-effects: - default: - pre-comment: "" - user-editable: - post-comment: "\n" + shop-per-item-options: + shop-per-item-settings: + post-comment: "\n" shop-sign-options: sign-default-colours: pre-comment: "What colour should be used for line 2/3 on shop signs per each material type." From 28f2c1bb646f0471983443469cd837b0f57fdab2 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 22 Jun 2022 21:24:23 -0700 Subject: [PATCH 21/53] Per Shop Setting and necessary bug fixes - Remove Debugger from utils to prevent early access - Add in server default and user-editable settings for per-shop settings including hopper import/export and no-cost - Update old values into new locations including no-cost-text, no-cost-amount, and existing hopper settings - Fix for improper mapped settings writing - Remove hopper settings from Metrics, need to add back before 2.6.0 - Add in asType settings to ObjectHolder so conversion code doesn't need to be added after retrieval. - Changed old makeReadable Code to utilize WordUtils. - Removed getString from ShopType to avoid early setting calls, replace with Setting enum value - Add try/catch to skippableHoppers boolean updater to avoid early settings call - Call updateSkippableHoppers a second time after settings has been fully initiated - Add ShopSettingKeys - Add Edit Settings GUI to `/ts edit` menu - Added skippableShop cache so shops can be handled with a different time values and be removed when their settings are changed and should be reprocessed. - Added try/catch for IlleaglWorldException to PlayerSetting#getInvolvedStatus methods to prevent error when trying to load shops from unloaded worlds - Fix for null appearing on shop sign lines 2/3 due to color being added - Change availableTradeAmount for iTrade Shops to be 999 - Change updateStatus to change to OPEN when availableTrade > 0 - Change getFullTradeCount to check if costs can be traded on BiTrade Shops when no Product is in stock - Change Hopper protection to not skip shop hoppers(code is commented out dependent on input) - Add delayed Shop sign and available trade update on inventory close(when it is a shop inventory) - Changed trade and trade check code to support new noCost setting --- .../java/org/shanerx/tradeshop/TradeShop.java | 2 + .../commands/commandrunners/AdminCommand.java | 4 +- .../commands/commandrunners/EditCommand.java | 106 ++++++++++++-- .../commands/commandrunners/GUICommand.java | 11 +- .../tradeshop/data/config/ConfigManager.java | 26 +++- .../tradeshop/data/config/Message.java | 4 +- .../tradeshop/data/config/Setting.java | 73 ++++++++-- .../tradeshop/data/storage/DataStorage.java | 2 +- .../tradeshop/item/IllegalItemList.java | 2 +- .../shanerx/tradeshop/item/ShopItemStack.java | 65 ++++----- .../item/ShopItemStackSettingKeys.java | 22 +-- .../tradeshop/player/PlayerSetting.java | 121 +++++++++------- .../java/org/shanerx/tradeshop/shop/Shop.java | 134 ++++++++++++++++-- .../tradeshop/shop/ShopSettingKeys.java | 119 ++++++++++++++++ .../org/shanerx/tradeshop/shop/ShopSign.java | 6 +- .../shanerx/tradeshop/shop/ShopStorage.java | 10 +- .../org/shanerx/tradeshop/shop/ShopType.java | 27 ++-- .../listeners/ShopProtectionListener.java | 67 ++++++--- .../shop/listeners/ShopTradeListener.java | 134 +++++++----------- .../shanerx/tradeshop/utils/ListManager.java | 50 +++++-- .../tradeshop/utils/MetricsManager.java | 18 +-- .../org/shanerx/tradeshop/utils/Utils.java | 124 ++++++---------- .../tradeshop/utils/objects/ObjectHolder.java | 20 ++- src/main/resources/Lang/en-us.yml | 9 +- 24 files changed, 759 insertions(+), 397 deletions(-) create mode 100644 src/main/java/org/shanerx/tradeshop/shop/ShopSettingKeys.java diff --git a/src/main/java/org/shanerx/tradeshop/TradeShop.java b/src/main/java/org/shanerx/tradeshop/TradeShop.java index 9b905a16..0430f3d3 100644 --- a/src/main/java/org/shanerx/tradeshop/TradeShop.java +++ b/src/main/java/org/shanerx/tradeshop/TradeShop.java @@ -100,6 +100,8 @@ public void onEnable() { getSettingManager().reload(); getMessageManager().reload(); + getSettingManager().updateSkipHoppers(); + getDebugger(); Permissions.registerPermissions(); diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java index c065d34c..c9c732fb 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java @@ -60,8 +60,8 @@ public void reload() { try { plugin.getDataStorage().reload(DataType.valueOf(Setting.DATA_STORAGE_TYPE.getString().toUpperCase())); } catch (IllegalArgumentException iae) { - debugger.log("Config value for data storage set to an invalid value: " + Setting.DATA_STORAGE_TYPE.getString(), DebugLevels.DATA_ERROR); - debugger.log("TradeShop will now disable...", DebugLevels.DATA_ERROR); + PLUGIN.getDebugger().log("Config value for data storage set to an invalid value: " + Setting.DATA_STORAGE_TYPE.getString(), DebugLevels.DATA_ERROR); + PLUGIN.getDebugger().log("TradeShop will now disable...", DebugLevels.DATA_ERROR); plugin.getServer().getPluginManager().disablePlugin(plugin); return; } diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java index b9781210..002d3f2d 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java @@ -25,6 +25,7 @@ package org.shanerx.tradeshop.commands.commandrunners; +import de.themoep.inventorygui.GuiElement; import de.themoep.inventorygui.GuiElementGroup; import de.themoep.inventorygui.GuiStateElement; import de.themoep.inventorygui.InventoryGui; @@ -40,8 +41,12 @@ import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.player.ShopUser; import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shop.ShopSettingKeys; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; +import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Set; /** @@ -55,7 +60,8 @@ public class EditCommand extends GUICommand { private InventoryGui mainMenu, userEdit, costEdit, - productEdit; + productEdit, + settingEdit; public EditCommand(TradeShop instance, CommandPass command) { @@ -82,7 +88,87 @@ public void edit() { mainMenu.setFiller(new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1)); // ShopUser edit menu, currently can only change/remove. Adding only available through commands - mainMenu.addElement(new StaticGuiElement('a', new ItemStack(Material.PLAYER_HEAD), click -> { + mainMenu.addElement(editUserMenu('a')); + + mainMenu.addElement(editCostMenu('b')); + + mainMenu.addElement(editProductMenu('c')); + + mainMenu.addElement(editSettingsMenu('d')); + + mainMenu.show(pSender); + } + + private GuiElement editSettingsMenu(char slotChar) { + return new StaticGuiElement(slotChar, new ItemStack(Material.CRAFTING_TABLE), click -> { + Map> changedSettings = new HashMap<>(); + + settingEdit = new InventoryGui(plugin, "Edit Shop Settings", SETTING_LAYOUT); + GuiElementGroup viewGroup = new GuiElementGroup('g'), + changeGroup = new GuiElementGroup('h'); + + shop.getShopSettings().forEach((key, value) -> { + viewGroup.addElement(new StaticGuiElement('e', key.getDisplayItem(), key.makeReadable(), value.toString())); + + ObjectHolder state = shop.getShopSetting(key); + if (!(state == null || state.getObject() == null)) { + if (state.isBoolean()) { + if (key.isUserEditable(shop.getShopType())) { + changeGroup.addElement(new GuiStateElement('e', + state.asBoolean().toString(), + new GuiStateElement.State(change -> { + if (!state.asBoolean()) + changedSettings.put(key, new ObjectHolder<>(true)); + else + changedSettings.remove(key); + }, + "true", + getBooleanItem(true), + key.makeReadable(), + "State: True" + ), + new GuiStateElement.State(change -> { + if (state.asBoolean()) + changedSettings.put(key, new ObjectHolder<>(false)); + else + changedSettings.remove(key); + }, + "false", + getBooleanItem(false), + key.makeReadable(), + "State: False" + ))); + } else { + changeGroup.addElement(new StaticGuiElement('e', getBooleanItem(state.asBoolean()), key.makeReadable(), value.toString())); + } + + + } // Add else-if later if other type settings are added... + } + }); + + // Add Cancel Button - Cancels changes and Goes to previous screen + settingEdit.addElement(getBackButton(true)); + + // Add Save Button - Saves and Goes to previous menu + settingEdit.addElement(new StaticGuiElement('s', new ItemStack(Material.ANVIL), click3 -> { + shop.setShopSettings(changedSettings); + shop.saveShop(changedSettings.size() > 0); + InventoryGui.goBack(pSender); + return true; + }, "Save Changes")); + + settingEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.YELLOW_STAINED_GLASS_PANE), " ")); + + settingEdit.addElements(getNextButton(), getPrevButton(), viewGroup, changeGroup); + + settingEdit.show(pSender); + return true; + }, colorize("&eEdit Shop Settings")); + } + + private GuiElement editUserMenu(char slotChar) { + return new StaticGuiElement(slotChar, new ItemStack(Material.PLAYER_HEAD), click -> { userEdit = new InventoryGui(plugin, "Edit Users", EDIT_LAYOUT); Set shopUsers = new HashSet<>(); GuiElementGroup userGroup = new GuiElementGroup('g'); @@ -155,9 +241,11 @@ public void edit() { userEdit.addElement(userGroup); userEdit.show(pSender); return true; - }, "Edit Shop Users")); + }, colorize("&eEdit Shop Users")); + } - mainMenu.addElement(new StaticGuiElement('b', new ItemStack(Material.GOLD_NUGGET), click -> { + private GuiElement editCostMenu(char slotChar) { + return new StaticGuiElement(slotChar, new ItemStack(Material.GOLD_NUGGET), click -> { costEdit = new InventoryGui(plugin, "Edit Costs", EDIT_LAYOUT); if (costItems.isEmpty()) { for (ShopItemStack item : shop.getSideList(ShopItemSide.COST)) { @@ -196,9 +284,11 @@ public void edit() { costEdit.addElement(costGroup); costEdit.show(pSender); return true; - }, "Edit Shop Costs")); + }, colorize("&eEdit Shop Costs")); + } - mainMenu.addElement(new StaticGuiElement('c', new ItemStack(Material.GRASS_BLOCK), click -> { + private GuiElement editProductMenu(char slotChar) { + return new StaticGuiElement(slotChar, new ItemStack(Material.GRASS_BLOCK), click -> { productEdit = new InventoryGui(plugin, "Edit Products", EDIT_LAYOUT); if (productItems.isEmpty()) { for (ShopItemStack item : shop.getSideList(ShopItemSide.PRODUCT)) { @@ -237,8 +327,6 @@ public void edit() { productEdit.addElement(productGroup); productEdit.show(pSender); return true; - }, "Edit Shop Products")); - - mainMenu.show(pSender); + }, colorize("&eEdit Shop Products")); } } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java index c4a42030..62a346ae 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java @@ -58,9 +58,10 @@ public class GUICommand extends CommandRunner { //------------------------------------------------------------------------------------------------------------------ - protected final String[] MENU_LAYOUT = {"a b c"}, + protected final String[] MENU_LAYOUT = {"ad bc"}, EDIT_LAYOUT = {"aggggggga", "ap c s na"}, ITEM_LAYOUT = {"u ggggggg", "j hhhhhhh", "ap cbs na"}, + SETTING_LAYOUT = {"ggggggggg", "hhhhhhhhh", "ap cbs na"}, WHAT_MENU = {"141125333", "1qqq2eee3", "11p123n33"}; protected List costItems = new ArrayList<>(), productItems = new ArrayList<>(); @@ -99,11 +100,11 @@ protected StaticGuiElement itemSettingMenu(int index, ShopItemSide side, boolean GuiElementGroup itemGroup = new GuiElementGroup('g'), settingGroup = new GuiElementGroup('h'); - // Cancel and Back - itemEdit.addElement(getBackButton(true)); + // Add Cancel button when editable and Back button when not - Goes to previous screen without saving changes + itemEdit.addElement(getBackButton(editable)); - // Save and Back - itemEdit.addElement(new StaticGuiElement('s', new ItemStack(Material.ANVIL), click3 -> { + // Add Save button only when editable - Saves and Goes to previous screen + if (editable) itemEdit.addElement(new StaticGuiElement('s', new ItemStack(Material.ANVIL), click3 -> { (side.equals(ShopItemSide.COST) ? costItems : productItems).set(index, item); InventoryGui.goBack(pSender); return true; diff --git a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java index fb5ed21a..563e5fed 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java @@ -33,6 +33,8 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.shop.ShopSettingKeys; +import org.shanerx.tradeshop.shop.ShopType; import java.io.File; import java.io.FileOutputStream; @@ -113,11 +115,25 @@ public void reload() { save(hasUpgraded.contains(true)); - PLUGIN.setSkipHopperProtection( - Setting.BITRADESHOP_HOPPER_EXPORT.getBoolean() && - Setting.BITRADESHOP_HOPPER_IMPORT.getBoolean() && - Setting.TRADESHOP_HOPPER_IMPORT.getBoolean() && - Setting.TRADESHOP_HOPPER_EXPORT.getBoolean()); + updateSkipHoppers(); + } + + public void updateSkipHoppers() { + try { + Set skipCheck = new HashSet<>(); + skipCheck.add(ShopSettingKeys.HOPPER_EXPORT.getDefaultValue(ShopType.TRADE).asBoolean()); + skipCheck.add(ShopSettingKeys.HOPPER_IMPORT.getDefaultValue(ShopType.TRADE).asBoolean()); + skipCheck.add(ShopSettingKeys.HOPPER_EXPORT.getDefaultValue(ShopType.BITRADE).asBoolean()); + skipCheck.add(ShopSettingKeys.HOPPER_IMPORT.getDefaultValue(ShopType.BITRADE).asBoolean()); + skipCheck.add(!ShopSettingKeys.HOPPER_EXPORT.isUserEditable(ShopType.TRADE)); + skipCheck.add(!ShopSettingKeys.HOPPER_IMPORT.isUserEditable(ShopType.TRADE)); + skipCheck.add(!ShopSettingKeys.HOPPER_EXPORT.isUserEditable(ShopType.BITRADE)); + skipCheck.add(!ShopSettingKeys.HOPPER_IMPORT.isUserEditable(ShopType.BITRADE)); + skipCheck.remove(true); + + PLUGIN.setSkipHopperProtection(!skipCheck.contains(false)); + } catch (NullPointerException ignored) { + } } public boolean setDefaults() { diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java index f2de16e1..83013b8e 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -293,7 +293,7 @@ public final void sendItemMultiLineMessage(Player player, Map> entry : itemsToFill.entrySet()) { Pattern pattern = Pattern.compile(MULTILINEREGEX.replace("&V&", entry.getKey().toString())); @@ -340,7 +340,7 @@ public final void sendUserEditMultiLineMessage(Player player, Map> entry : valuesToFill.entrySet()) { Pattern pattern = Pattern.compile(MULTILINEREGEX.replace("&V&", entry.getKey().toString())); diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 955d2313..3b6d5c0c 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -29,7 +29,9 @@ import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.item.IllegalItemList; import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; +import org.shanerx.tradeshop.shop.ShopSettingKeys; import org.shanerx.tradeshop.shop.ShopSign; +import org.shanerx.tradeshop.shop.ShopType; import org.yaml.snakeyaml.Yaml; import java.util.ArrayList; @@ -45,7 +47,7 @@ public enum Setting { // PostComment " " adds single newline below setting and "\n" adds 2 newlines below // PreComment `/n ` will have a new comment marker added after a sufficient space for proper formatting - CONFIG_VERSION(SettingSection.NONE, "config-version", 0.0), + CONFIG_VERSION(SettingSection.NONE, "config-version", 1.3), // System Options DATA_STORAGE_TYPE(SettingSection.SYSTEM_OPTIONS, "data-storage-type", "FLATFILE"), @@ -85,6 +87,8 @@ public enum Setting { MAX_ITEMS_PER_TRADE_SIDE(SettingSection.SHOP_OPTIONS, "max-items-per-trade-side", 6), ALLOW_USER_PURCHASING(SettingSection.SHOP_OPTIONS, "allow-user-purchasing", false), MULTIPLE_ITEMS_ON_SIGN(SettingSection.SHOP_OPTIONS, "multiple-items-on-sign", "Use '/ts what'"), + NO_COST_TEXT(SettingSection.SHOP_OPTIONS, "no-cost-text", "nothing"), + NO_COST_AMOUNT(SettingSection.SHOP_OPTIONS, "no-cost-amount", "1"), SHOP_PER_ITEM_SETTINGS(SettingSection.SHOP_ITEM_OPTIONS, "shop-per-item-settings", ShopItemStackSettingKeys.getDefaultConfigMap()), @@ -93,21 +97,18 @@ public enum Setting { // Trade Shop Options TRADESHOP_HEADER(SettingSection.TRADE_SHOP_OPTIONS, "header", "Trade"), TRADESHOP_EXPLODE(SettingSection.TRADE_SHOP_OPTIONS, "allow-explode", false), - TRADESHOP_HOPPER_EXPORT(SettingSection.TRADE_SHOP_OPTIONS, "allow-hopper-export", false), - TRADESHOP_HOPPER_IMPORT(SettingSection.TRADE_SHOP_OPTIONS, "allow-hopper-import", false), + TRADE_PER_SHOP_SETTINGS(SettingSection.TRADE_SHOP_OPTIONS, "trade-per-shop-settings", ShopSettingKeys.getSettingConfigMap(ShopType.TRADE)), // ITrade Shop Options ITRADESHOP_OWNER(SettingSection.ITRADE_SHOP_OPTIONS, "owner", "Server Shop"), ITRADESHOP_HEADER(SettingSection.ITRADE_SHOP_OPTIONS, "header", "iTrade"), ITRADESHOP_EXPLODE(SettingSection.ITRADE_SHOP_OPTIONS, "allow-explode", false), - ITRADESHOP_NO_COST_TEXT(SettingSection.ITRADE_SHOP_OPTIONS, "no-cost-text", "nothing"), - ITRADESHOP_NO_COST_AMOUNT(SettingSection.ITRADE_SHOP_OPTIONS, "no-cost-amount", "1"), + ITRADE_PER_SHOP_SETTINGS(SettingSection.ITRADE_SHOP_OPTIONS, "itrade-per-shop-settings", ShopSettingKeys.getSettingConfigMap(ShopType.ITRADE)), // BiTrade Shop Options BITRADESHOP_HEADER(SettingSection.BITRADE_SHOP_OPTIONS, "header", "BiTrade"), BITRADESHOP_EXPLODE(SettingSection.BITRADE_SHOP_OPTIONS, "allow-explode", false), - BITRADESHOP_HOPPER_EXPORT(SettingSection.BITRADE_SHOP_OPTIONS, "allow-hopper-export", false), - BITRADESHOP_HOPPER_IMPORT(SettingSection.BITRADE_SHOP_OPTIONS, "allow-hopper-import", false), + BITRADE_PER_SHOP_SETTINGS(SettingSection.BITRADE_SHOP_OPTIONS, "bitrade-per-shop-settings", ShopSettingKeys.getSettingConfigMap(ShopType.BITRADE)), // Illegal Item Options GLOBAL_ILLEGAL_ITEMS_TYPE(SettingSection.GLOBAL_ILLEGAL_ITEMS, "type", IllegalItemList.ListType.BLACKLIST.toString()), @@ -180,7 +181,7 @@ static boolean upgrade() { } if (configManager.getConfig().contains("tradeshop.allow-hopper-export")) { - configManager.getConfig().set(TRADESHOP_HOPPER_EXPORT.path, configManager.getConfig().get("tradeshop.allow-hopper-export")); + configManager.getConfig().set("trade-shop-options.allow-hopper-export", configManager.getConfig().get("tradeshop.allow-hopper-export")); configManager.getConfig().set("tradeshop.allow-hopper-export", null); hasUpgraded.add(true); } @@ -198,7 +199,7 @@ static boolean upgrade() { } if (configManager.getConfig().contains("bitradeshop.allow-hopper-export")) { - configManager.getConfig().set(BITRADESHOP_HOPPER_EXPORT.path, configManager.getConfig().get("bitradeshop.allow-hopper-export")); + configManager.getConfig().set("bitrade-shop-options.allow-hopper-export", configManager.getConfig().get("bitradeshop.allow-hopper-export")); configManager.getConfig().set("bitradeshop.allow-hopper-export", null); hasUpgraded.add(true); } @@ -218,6 +219,52 @@ static boolean upgrade() { version = 1.2; } + if (version < 1.3) { + String oldKey = "itrade-shop-options.no-cost-text"; + if (configManager.getConfig().contains(oldKey)) { + configManager.getConfig().set(NO_COST_TEXT.path, configManager.getConfig().get(oldKey)); + configManager.getConfig().set(oldKey, null); + hasUpgraded.add(true); + } + + oldKey = "itrade-shop-options.no-cost-amount"; + if (configManager.getConfig().contains(oldKey)) { + configManager.getConfig().set(NO_COST_AMOUNT.path, configManager.getConfig().get(oldKey)); + configManager.getConfig().set(oldKey, null); + hasUpgraded.add(true); + } + + oldKey = "bitrade-shop-options.allow-hopper-export"; + if (configManager.getConfig().contains(oldKey)) { + configManager.getConfig().set(BITRADE_PER_SHOP_SETTINGS.getPath() + ".allow-hopper-export", configManager.getConfig().get(oldKey)); + configManager.getConfig().set(oldKey, null); + hasUpgraded.add(true); + } + + oldKey = "bitrade-shop-options.allow-hopper-import";// + if (configManager.getConfig().contains(oldKey)) { + configManager.getConfig().set(BITRADE_PER_SHOP_SETTINGS.getPath() + ".allow-hopper-import", configManager.getConfig().get(oldKey)); + configManager.getConfig().set(oldKey, null); + hasUpgraded.add(true); + } + + oldKey = "trade-shop-options.allow-hopper-export";// + if (configManager.getConfig().contains(oldKey)) { + configManager.getConfig().set(TRADE_PER_SHOP_SETTINGS.getPath() + ".allow-hopper-export", configManager.getConfig().get(oldKey)); + configManager.getConfig().set(oldKey, null); + hasUpgraded.add(true); + } + + oldKey = "trade-shop-options.allow-hopper-import";// + if (configManager.getConfig().contains(oldKey)) { + configManager.getConfig().set(TRADE_PER_SHOP_SETTINGS.getPath() + ".allow-hopper-import", configManager.getConfig().get(oldKey)); + configManager.getConfig().set(oldKey, null); + hasUpgraded.add(true); + } + + version = 1.3; + } + CONFIG_VERSION.setValue(version); return hasUpgraded.contains(true); @@ -232,15 +279,15 @@ public Object getDefaultValue() { } public String getMappedString(String subKey) { - return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getString(subKey.toLowerCase().replace("_", "-")); + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getString(subKey.replace("_", "-")); } public boolean getMappedBoolean(String subKey) { - return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getBoolean(subKey.toLowerCase().replace("_", "-")); + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getBoolean(subKey.replace("_", "-")); } public Object getMappedObject(String subKey) { - return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).get(subKey.toLowerCase().replace("_", "-")); + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).get(subKey.replace("_", "-")); } public String getPostComment() { @@ -270,7 +317,7 @@ private String processMapValue(Map valueMap, String localLead) { for (Object key : sortedKeys) { Object value = valueMap.get(key); if (value instanceof Map) { - processed.append(localLead).append(getKey()).append(":\n"); + processed.append(localLead).append(key.toString()).append(":\n"); processed.append(processMapValue(((Map) value), localLead + leadIncrease)); } else { processed.append(localLead).append(key.toString()).append(": ").append(new Yaml().dump(value)); diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java index ce55ac6a..23afbc86 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java @@ -50,7 +50,7 @@ public DataStorage(DataType dataType) { public void reload(DataType dataType) { this.dataType = dataType; - debugger.log("Data storage set to: " + dataType.name(), DebugLevels.DISABLED); + PLUGIN.getDebugger().log("Data storage set to: " + dataType.name(), DebugLevels.DISABLED); } public Shop loadShopFromSign(ShopLocation sign) { diff --git a/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java b/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java index cb36fb4c..667c970a 100644 --- a/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java +++ b/src/main/java/org/shanerx/tradeshop/item/IllegalItemList.java @@ -80,7 +80,7 @@ public void clear() { } public boolean add(Material mat) { - debugger.log("Material being added to Illegal Item List: " + mat, DebugLevels.ILLEGAL_ITEMS_LIST); + PLUGIN.getDebugger().log("Material being added to Illegal Item List: " + mat, DebugLevels.ILLEGAL_ITEMS_LIST); return list.add(mat); } diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index cf6cf229..83aa1052 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -55,6 +55,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; +import java.util.Map; import java.util.Objects; public class ShopItemStack implements Serializable, Cloneable { @@ -64,32 +65,32 @@ public class ShopItemStack implements Serializable, Cloneable { private String itemStackB64; - private HashMap> shopSettings; + private Map> itemSettings; public ShopItemStack(ItemStack itemStack) { this.itemStack = itemStack; - shopSettings = new HashMap<>(); + itemSettings = new HashMap<>(); buildMap(); toBase64(); } public ShopItemStack(ItemStack itemStack, HashMap> settingMap) { this.itemStack = itemStack; - this.shopSettings = settingMap; + this.itemSettings = settingMap; buildMap(); toBase64(); } public ShopItemStack(String itemStackB64) { this.itemStackB64 = itemStackB64; - shopSettings = new HashMap<>(); + itemSettings = new HashMap<>(); buildMap(); fromBase64(); } public ShopItemStack(String itemStackB64, HashMap> settingMap) { this.itemStackB64 = itemStackB64; - this.shopSettings = settingMap; + this.itemSettings = settingMap; buildMap(); fromBase64(); } @@ -102,26 +103,26 @@ public ShopItemStack(String itemStackB64, int compareDurability, boolean compare boolean compareBookAuthor, boolean compareBookPages, boolean compareShulkerInventory) { this.itemStackB64 = itemStackB64; - shopSettings = new HashMap<>(); + itemSettings = new HashMap<>(); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_DURABILITY, new ObjectHolder<>(compareDurability)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_NAME, new ObjectHolder<>(compareName)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_LORE, new ObjectHolder<>(compareLore)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA, new ObjectHolder<>(compareCustomModelData)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS, new ObjectHolder<>(compareItemFlags)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE, new ObjectHolder<>(compareUnbreakable)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER, new ObjectHolder<>(compareAttributeModifier)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR, new ObjectHolder<>(compareBookAuthor)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES, new ObjectHolder<>(compareBookPages)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY, new ObjectHolder<>(compareShulkerInventory)); - shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS, new ObjectHolder<>(compareEnchantments)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_DURABILITY, new ObjectHolder<>(compareDurability)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_NAME, new ObjectHolder<>(compareName)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_LORE, new ObjectHolder<>(compareLore)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA, new ObjectHolder<>(compareCustomModelData)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS, new ObjectHolder<>(compareItemFlags)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE, new ObjectHolder<>(compareUnbreakable)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER, new ObjectHolder<>(compareAttributeModifier)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR, new ObjectHolder<>(compareBookAuthor)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES, new ObjectHolder<>(compareBookPages)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY, new ObjectHolder<>(compareShulkerInventory)); + itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS, new ObjectHolder<>(compareEnchantments)); buildMap(); fromBase64(); } - public HashMap> getShopSettings() { - return shopSettings; + public Map> getItemSettings() { + return itemSettings; } public static ShopItemStack deserialize(String serialized) { @@ -134,8 +135,8 @@ public static ShopItemStack deserialize(String serialized) { public boolean getShopSettingAsBoolean(ShopItemStackSettingKeys key) { if (key.isUserEditable()) { try { - ObjectHolder tempObj = shopSettings.get(key); - return shopSettings.containsKey(key) ? (Boolean) tempObj.getObject() : (Boolean) key.getDefaultValue().getObject(); + ObjectHolder tempObj = itemSettings.get(key); + return itemSettings.containsKey(key) ? (Boolean) tempObj.getObject() : (Boolean) key.getDefaultValue().getObject(); } catch (ClassCastException | NullPointerException ignored) { } } @@ -145,8 +146,8 @@ public boolean getShopSettingAsBoolean(ShopItemStackSettingKeys key) { public int getShopSettingAsInteger(ShopItemStackSettingKeys key) { if (key.isUserEditable()) { try { - ObjectHolder tempObj = shopSettings.get(key); - return shopSettings.containsKey(key) ? (Integer) tempObj.getObject() : (Integer) key.getDefaultValue().getObject(); + ObjectHolder tempObj = itemSettings.get(key); + return itemSettings.containsKey(key) ? (Integer) tempObj.getObject() : (Integer) key.getDefaultValue().getObject(); } catch (ClassCastException | NullPointerException ignored) { } } @@ -155,12 +156,12 @@ public int getShopSettingAsInteger(ShopItemStackSettingKeys key) { } private void buildMap() { - if (shopSettings == null) { - shopSettings = new HashMap<>(); + if (itemSettings == null) { + itemSettings = new HashMap<>(); } for (ShopItemStackSettingKeys key : ShopItemStackSettingKeys.values()) { - shopSettings.putIfAbsent(key, key.getDefaultValue()); + itemSettings.putIfAbsent(key, key.getDefaultValue()); } } @@ -177,12 +178,12 @@ public ShopItemStack clone() { } public boolean setShopSettings(ShopItemStackSettingKeys key, ObjectHolder value) { - if (shopSettings == null) { - shopSettings = new HashMap<>(); + if (itemSettings == null) { + itemSettings = new HashMap<>(); buildMap(); } - shopSettings.put(key, value); + itemSettings.put(key, value); return false; } @@ -206,7 +207,7 @@ public boolean hasBase64() { } public boolean isSimilar(ItemStack toCompare) { - debugger = new Utils().debugger; + debugger = new Utils().PLUGIN.getDebugger(); // Return False if either item is null if (itemStack == null || toCompare == null) { @@ -516,7 +517,7 @@ public String getCleanItemName() { } public String getStateString(ShopItemStackSettingKeys key) { - return getStateString(shopSettings.get(key)); + return getStateString(itemSettings.get(key)); } public String getStateString(ObjectHolder stateSetting) { @@ -562,7 +563,7 @@ public String serialize() { public String toString() { return "ShopItemStack{" + "itemStack=" + getItemStack() + - ", shopSettings=" + shopSettings + + ", shopSettings=" + itemSettings + '}'; } diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java index 666730fd..6f10f7fd 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java @@ -25,6 +25,7 @@ package org.shanerx.tradeshop.item; +import org.apache.commons.lang.WordUtils; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.data.config.Setting; @@ -53,8 +54,8 @@ public enum ShopItemStackSettingKeys { COMPARE_FIREWORK_EFFECTS(new ItemStack(Material.FIREWORK_STAR), true); private final ItemStack displayItem; - private static final String defaultKey = "default", userEditableKey = "userEditable"; private final Object preConfigDefault; + private static final String defaultKey = "default", userEditableKey = "userEditable"; ShopItemStackSettingKeys(ItemStack displayItem, Object preConfigDefault) { this.displayItem = displayItem; @@ -77,24 +78,7 @@ public static Map getDefaultConfigMap() { } public String makeReadable() { - StringBuilder ret = new StringBuilder(); - - //Replaces '_' with ' ' followed by a Capital letter, other letters are lower cased. - for (int i = 0; i < name().length(); i++) { - char ch = name().charAt(i); - - if (i == 0) - ret.append(Character.toUpperCase(ch)); - else if (ret.charAt(i - 1) == ' ') - ret.append(Character.toUpperCase(ch)); - else if (ch == '_') - ret.append(" "); - else - ret.append(Character.toLowerCase(ch)); - } - - //removes any Leading/Trailing spaces and returns - return ret.toString().trim(); + return WordUtils.capitalizeFully(name().replace("_", " ")); } diff --git a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java index 42577f80..dbb19973 100644 --- a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java +++ b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java @@ -36,6 +36,7 @@ import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shoplocation.IllegalWorldException; import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; @@ -157,29 +158,37 @@ public String getInvolvedStatusesString() { sb.append("&eShop Role &f| &eType &f| &eAvailable Trades &f| &eLocation &f| &eInventory Status\n&b"); if (getOwnedShops().size() > 0) { getOwnedShops().forEach(s -> { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); - if (shop == null) { - nullShops.add(s); - } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { - sb.append(shop.checkRole(uuid).toString()).append(" &f|&a "); - sb.append(shop.getShopType().toString()).append(" &f|&b "); - sb.append(shop.getAvailableTrades()).append(" &f|&d "); - sb.append(s).append(" &f| "); - sb.append(shop.getStatus().getLine()).append("\n&b"); + try { + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); + if (shop == null) { + nullShops.add(s); + } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { + sb.append(shop.checkRole(uuid).toString()).append(" &f|&a "); + sb.append(shop.getShopType().toString()).append(" &f|&b "); + sb.append(shop.getAvailableTrades()).append(" &f|&d "); + sb.append(s).append(" &f| "); + sb.append(shop.getStatus().getLine()).append("\n&b"); + } + } catch (IllegalWorldException ignored) { + //Prevents IllegalWorldException when a player has shops in a world that is not loaded, They are not removed in case the world is loaded again... } }); } if (getStaffShops().size() > 0) { getStaffShops().forEach(s -> { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); - if (shop == null) { - nullShops.add(s); - } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { - sb.append(shop.checkRole(uuid).toString()).append(" &f|&a "); - sb.append(shop.getShopType().toString()).append(" &f|&b "); - sb.append(shop.getAvailableTrades()).append(" &f|&d "); - sb.append(s).append(" &f| "); - sb.append(shop.getStatus().getLine()).append("\n&b"); + try { + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); + if (shop == null) { + nullShops.add(s); + } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { + sb.append(shop.checkRole(uuid).toString()).append(" &f|&a "); + sb.append(shop.getShopType().toString()).append(" &f|&b "); + sb.append(shop.getAvailableTrades()).append(" &f|&d "); + sb.append(s).append(" &f| "); + sb.append(shop.getStatus().getLine()).append("\n&b"); + } + } catch (IllegalWorldException ignored) { + //Prevents IllegalWorldException when a player has shops in a world that is not loaded, They are not removed in case the world is loaded again... } }); } @@ -196,45 +205,53 @@ public InventoryGui getInvolvedStatusesInventory() { GuiElementGroup group = new GuiElementGroup('g'); if (getOwnedShops().size() > 0) { getOwnedShops().forEach(s -> { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); - if (shop == null) { - nullShops.add(s); - } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { - group.addElement(new StaticGuiElement('e', - new ItemStack(shop.getInventoryLocation() != null ? - shop.getInventoryLocation().getBlock().getType() : - Material.getMaterial(shop.getShopLocation().getBlock().getType().toString().replaceAll("WALL_", ""))), - Math.min(shop.getAvailableTrades(), 64), - click -> { - return true; //Prevents clicking the item from doing anything, required parameter when using amount - }, - utils.colorize("&d" + s), - utils.colorize("&a" + shop.getShopType().toString()), - utils.colorize("&b" + shop.checkRole(uuid).toString()), - utils.colorize("&bAvailable Trades: " + shop.getAvailableTrades()), - utils.colorize(shop.getStatus().getLine()))); + try { + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); + if (shop == null) { + nullShops.add(s); + } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { + group.addElement(new StaticGuiElement('e', + new ItemStack(shop.getInventoryLocation() != null ? + shop.getInventoryLocation().getBlock().getType() : + Material.getMaterial(shop.getShopLocation().getBlock().getType().toString().replaceAll("WALL_", ""))), + Math.min(shop.getAvailableTrades(), 64), + click -> { + return true; //Prevents clicking the item from doing anything, required parameter when using amount + }, + utils.colorize("&d" + s), + utils.colorize("&a" + shop.getShopType().toString()), + utils.colorize("&b" + shop.checkRole(uuid).toString()), + utils.colorize("&bAvailable Trades: " + shop.getAvailableTrades()), + utils.colorize(shop.getStatus().getLine()))); + } + } catch (IllegalWorldException ignored) { + //Prevents IllegalWorldException when a player has shops in a world that is not loaded, They are not removed in case the world is loaded again... } }); } if (getStaffShops().size() > 0) { getStaffShops().forEach(s -> { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); - if (shop == null) { - nullShops.add(s); - } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { - group.addElement(new StaticGuiElement('e', - new ItemStack(shop.getInventoryLocation() != null ? - shop.getInventoryLocation().getBlock().getType() : - Material.getMaterial(shop.getShopLocation().getBlock().getType().toString().replaceAll("WALL_", ""))), - Math.min(shop.getAvailableTrades(), 64), - click -> { - return true; //Prevents clicking the item from doing anything, required parameter when using amount - }, - utils.colorize("&d" + s), - utils.colorize("&a" + shop.getShopType().toString()), - utils.colorize("&b" + shop.checkRole(uuid).toString()), - utils.colorize("&bAvailable Trades: " + shop.getAvailableTrades()), - utils.colorize(shop.getStatus().getLine()))); + try { + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); + if (shop == null) { + nullShops.add(s); + } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { + group.addElement(new StaticGuiElement('e', + new ItemStack(shop.getInventoryLocation() != null ? + shop.getInventoryLocation().getBlock().getType() : + Material.getMaterial(shop.getShopLocation().getBlock().getType().toString().replaceAll("WALL_", ""))), + Math.min(shop.getAvailableTrades(), 64), + click -> { + return true; //Prevents clicking the item from doing anything, required parameter when using amount + }, + utils.colorize("&d" + s), + utils.colorize("&a" + shop.getShopType().toString()), + utils.colorize("&b" + shop.checkRole(uuid).toString()), + utils.colorize("&bAvailable Trades: " + shop.getAvailableTrades()), + utils.colorize(shop.getStatus().getLine()))); + } + } catch (IllegalWorldException ignored) { + //Prevents IllegalWorldException when a player has shops in a world that is not loaded, They are not removed in case the world is loaded again... } }); } diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 5ba947e5..064641dc 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -26,7 +26,6 @@ package org.shanerx.tradeshop.shop; import com.google.gson.Gson; -import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Block; @@ -46,12 +45,15 @@ import org.shanerx.tradeshop.shoplocation.ShopChunk; import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; import org.shanerx.tradeshop.utils.objects.Tuple; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; @@ -68,6 +70,8 @@ public class Shop implements Serializable { private transient Utils utils = new Utils(); private ShopStatus status = ShopStatus.INCOMPLETE; + private Map> shopSettings; + private int availableTrades = 0; /** @@ -224,6 +228,9 @@ public ShopType getShopType() { * @param newType new type as ShopType */ public void setShopType(ShopType newType) { + if (shopType != newType) + setShopSettings(newType); + shopType = newType; } @@ -269,6 +276,7 @@ public ShopLocation getInventoryLocationAsSL() { public void fixAfterLoad() { if (utils == null) utils = new Utils(); + shopLoc.stringToWorld(); if (!getShopType().isITrade() && chestLoc != null) { chestLoc.stringToWorld(); @@ -276,6 +284,8 @@ public void fixAfterLoad() { utils.PLUGIN.getDataStorage().addChestLinkage(chestLoc, shopLoc); } + setShopSettings(); + if (getShopSign() != null) updateSign(); } @@ -432,14 +442,11 @@ private String[] updateSignLines(String defaultColour) { sb.append(item.getCleanItemName()); - signLines[2] = sb.substring(0, Math.min(sb.length(), 15)); + signLines[2] = utils.colorize(defaultColour + sb.substring(0, Math.min(sb.length(), 15))); } else { - signLines[2] = Setting.MULTIPLE_ITEMS_ON_SIGN.getString(); + signLines[2] = utils.colorize(defaultColour + Setting.MULTIPLE_ITEMS_ON_SIGN.getString()); } - signLines[1] = utils.colorize(defaultColour + ChatColor.stripColor(signLines[1])); - signLines[2] = utils.colorize(defaultColour + ChatColor.stripColor(signLines[2])); - updateStatus(); signLines[3] = status.getLine(); @@ -513,7 +520,7 @@ public ShopStatus setOpen() { public void updateStatus() { if (!status.equals(ShopStatus.CLOSED)) { if (!isMissingItems() && (chestLoc != null || shopType.isITrade())) { - if (shopType.isITrade() || hasSideStock(ShopItemSide.PRODUCT) || (shopType.isBiTrade() && hasSideStock(ShopItemSide.COST))) + if (getAvailableTrades() > 0) setStatus(ShopStatus.OPEN); else setStatus(ShopStatus.OUT_OF_STOCK); @@ -580,34 +587,119 @@ private boolean areItemsValid(ShopItemSide side, List items) { * Updates the number of trades the shop can make */ public void updateFullTradeCount() { + if (getShopType().equals(ShopType.ITRADE) && hasSide(ShopItemSide.PRODUCT)) { + availableTrades = 999; + return; + } + if (!hasStorage() || !hasSide(ShopItemSide.PRODUCT)) { availableTrades = 0; return; } - Inventory shopInventory = hasStorage() ? getChestAsSC().getInventory() : null; + Inventory shopInventory = getChestAsSC().getInventory(); + + int count = countItems(getSideList(ShopItemSide.PRODUCT), shopInventory.getStorageContents()); + + if (count == 0 && getShopType().equals(ShopType.BITRADE)) { + count = countItems(getSideList(ShopItemSide.COST), shopInventory.getStorageContents()); + } + + availableTrades = count; + } + + private int countItems(List countItems, ItemStack[] storageContents) { + Inventory storage = Bukkit.createInventory(null, storageContents.length); + storage.setContents(storageContents); - Inventory clone = Bukkit.createInventory(null, shopInventory.getStorageContents().length); - clone.setContents(shopInventory.getStorageContents()); int totalCount = 0, currentCount = 0; - for (ShopItemStack item : getSideList(ShopItemSide.PRODUCT)) { + for (ShopItemStack item : countItems) { totalCount += item.getItemStack().getAmount(); int traded; - for (ItemStack storageItem : clone.getStorageContents()) { + for (ItemStack storageItem : storage.getStorageContents()) { if (storageItem != null && item.isSimilar(storageItem)) { traded = Math.min(storageItem.getAmount(), item.getItemStack().getMaxStackSize()); storageItem.setAmount(traded); - clone.removeItem(storageItem); + storage.removeItem(storageItem); currentCount += traded; } } } - availableTrades = currentCount == 0 || totalCount == 0 ? 0 : currentCount / totalCount; + return (currentCount == 0 || totalCount == 0) ? 0 : currentCount / totalCount; + } + + + //region Setting Management - Methods for managing a shops settings + //------------------------------------------------------------------------------------------------------------------ + + /** + * Sets the Shops settings based on the ShopType and server defaults. + */ + public void setShopSettings() { + setShopSettings(shopType); } + /** + * Retrieves the specified setting if it is usable on the shop + */ + public ObjectHolder getShopSetting(ShopSettingKeys settingKey) { + return settingKey.isUsable(shopType) ? shopSettings.get(settingKey) : null; + } + + /** + * Retrieves the specified setting if it is usable on the shop + */ + public boolean hasShopSetting(ShopSettingKeys settingKey) { + return settingKey.isUsable(shopType) && shopSettings.containsKey(settingKey); + } + + /** + * Retrieves the specified setting if it is usable on the shop + */ + public Map> getShopSettings() { + return shopSettings; + } + + /** + * Sets the Shops settings based on the passed ShopType + */ + public void setShopSettings(ShopType type) { + if (shopSettings == null) + shopSettings = new HashMap<>(); + + for (ShopSettingKeys settingKey : ShopSettingKeys.values()) { + if (shopSettings.containsKey(settingKey) && !settingKey.isUsable(type)) { + shopSettings.remove(settingKey); + } else { + shopSettings.putIfAbsent(settingKey, settingKey.getDefaultValue(type)); + } + + if (!settingKey.isUserEditable(type) && shopSettings.get(settingKey) != settingKey.getDefaultValue(type)) { + shopSettings.put(settingKey, settingKey.getDefaultValue(type)); + } + } + } + + /** + * Retrieves the specified setting if it is usable on the shop + */ + public void setShopSettings(Map> newSettings) { + if (newSettings.size() > 0) + new Utils().PLUGIN.getListManager().removeSkippableShop(getShopLocation()); + + for (ShopSettingKeys settingKey : newSettings.keySet()) { + if (settingKey.isUsable(shopType) && newSettings.get(settingKey) != null) { + shopSettings.put(settingKey, newSettings.get(settingKey)); + } + } + } + + //------------------------------------------------------------------------------------------------------------------ + //endregion + //region User Management - Methods for adding/deleting/updating/viewing a shops users //------------------------------------------------------------------------------------------------------------------ @@ -878,7 +970,19 @@ public boolean hasSide(ShopItemSide side) { * @return true if items are missing */ public boolean isMissingItems() { - return shopType.equals(ShopType.ITRADE) ? product.isEmpty() : product.isEmpty() || cost.isEmpty(); + return isNoCost() ? product.isEmpty() : product.isEmpty() || cost.isEmpty(); + } + + /** + * Checks if the shop is set to not use cost + * + * @return true if cost is not needed + */ + public boolean isNoCost() { + if (!ShopSettingKeys.NO_COST.isUsable(getShopType())) return false; + + Boolean noCost = shopSettings.get(ShopSettingKeys.NO_COST).asBoolean(); + return noCost != null ? noCost : false; } /** diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopSettingKeys.java b/src/main/java/org/shanerx/tradeshop/shop/ShopSettingKeys.java new file mode 100644 index 00000000..8a8fa69c --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopSettingKeys.java @@ -0,0 +1,119 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.shop; + +import org.apache.commons.lang.WordUtils; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.utils.objects.ObjectHolder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public enum ShopSettingKeys { + + // Use null as default if the shop type does not use this setting + + HOPPER_IMPORT(new ItemStack(Material.HOPPER), false, false, null), + HOPPER_EXPORT(new ItemStack(Material.DISPENSER), false, false, null), + NO_COST(new ItemStack(Material.GOLD_INGOT), false, null, false); + + public static final String defaultKey = "default", userEditableKey = "userEditable"; + private final ItemStack displayItem; + private final Map defaults; + + ShopSettingKeys(ItemStack displayItem, Object tradeDefault, Object biTradeDefault, Object iTradeDefault) { + this.displayItem = displayItem; + defaults = new HashMap<>(); + defaults.put(ShopType.TRADE, tradeDefault); + defaults.put(ShopType.BITRADE, biTradeDefault); + defaults.put(ShopType.ITRADE, iTradeDefault); + } + + public static Map getSettingConfigMap(ShopType type) { + Map configMap = new HashMap<>(); + + for (ShopSettingKeys value : getValidSettings(type)) { + Map subConfigMap = new HashMap<>(); + subConfigMap.put(defaultKey, value.defaults.get(type)); + subConfigMap.put(userEditableKey, true); + + configMap.put(value.getConfigKey(), subConfigMap); + } + return configMap; + } + + public static List getValidSettings(ShopType type) { + List settings = new ArrayList<>(); + + Arrays.stream(values()).forEach((setting) -> { + if (setting.defaults.get(type) != null) settings.add(setting); + }); + + return settings; + } + + public static ShopSettingKeys findShopSetting(String search) { + return valueOf(search.toUpperCase().replace("-", "_")); + } + + public static Setting settingExpand(ShopType type) { + return Setting.findSetting(type.name() + "_PER_SHOP_SETTINGS"); + } + + public String makeReadable() { + return WordUtils.capitalizeFully(name().replace("_", " ")); + + } + + public ObjectHolder getDefaultValue(ShopType type) { + return isUsable(type) ? new ObjectHolder<>(settingExpand(type).getMappedObject(getConfigKey() + "." + defaultKey)) : null; + } + + public ObjectHolder getDefault(ShopType type) { + return isUsable(type) ? new ObjectHolder<>(defaults.get(type)) : null; + } + + public boolean isUserEditable(ShopType type) { + return isUsable(type) && settingExpand(type).getMappedBoolean(getConfigKey() + "." + userEditableKey); + } + + public boolean isUsable(ShopType type) { + return defaults.get(type) != null; + } + + public ItemStack getDisplayItem() { + return displayItem; + } + + public String getConfigKey() { + return name().toLowerCase().replace("_", "-"); + } +} diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java b/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java index fdbdfab8..7bd9af73 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopSign.java @@ -118,9 +118,9 @@ public class ShopSign extends Utils { public ShopSign() { for (Signs type : Signs.values()) { boolean pass = true; - debugger.log(type.toString(), DebugLevels.STARTUP); - debugger.log(String.format("MinVer: %s", type.getMinVersionAsString()), DebugLevels.STARTUP); - debugger.log(String.format("MaxVer: %s", type.getMaxVersionAsString()), DebugLevels.STARTUP); + PLUGIN.getDebugger().log(type.toString(), DebugLevels.STARTUP); + PLUGIN.getDebugger().log(String.format("MinVer: %s", type.getMinVersionAsString()), DebugLevels.STARTUP); + PLUGIN.getDebugger().log(String.format("MaxVer: %s", type.getMaxVersionAsString()), DebugLevels.STARTUP); if (type.hasMinVersion() && version.isBelow(type.getMinVer().get(0), type.getMinVer().get(1), type.getMinVer().get(2))) { pass = false; diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopStorage.java b/src/main/java/org/shanerx/tradeshop/shop/ShopStorage.java index c60499e4..9b859d20 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopStorage.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopStorage.java @@ -44,10 +44,10 @@ public class ShopStorage extends Utils { public ShopStorage() { for (Storages type : Storages.values()) { - debugger.log(type.toString(), DebugLevels.STARTUP); - debugger.log(String.format("- MinVer: %s", type.getMinVersionAsString()), DebugLevels.STARTUP); - debugger.log(String.format("- MaxVer: %s", type.getMaxVersionAsString()), DebugLevels.STARTUP); - debugger.log(String.format("- Weight: %s", type.getWeight()), DebugLevels.STARTUP); + PLUGIN.getDebugger().log(type.toString(), DebugLevels.STARTUP); + PLUGIN.getDebugger().log(String.format("- MinVer: %s", type.getMinVersionAsString()), DebugLevels.STARTUP); + PLUGIN.getDebugger().log(String.format("- MaxVer: %s", type.getMaxVersionAsString()), DebugLevels.STARTUP); + PLUGIN.getDebugger().log(String.format("- Weight: %s", type.getWeight()), DebugLevels.STARTUP); boolean added = false; @@ -57,7 +57,7 @@ public ShopStorage() { added = true; } - debugger.log(String.format("- Added: %s", added), DebugLevels.STARTUP); + PLUGIN.getDebugger().log(String.format("- Added: %s", added), DebugLevels.STARTUP); } } diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopType.java b/src/main/java/org/shanerx/tradeshop/shop/ShopType.java index 69af9931..3b54008e 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopType.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopType.java @@ -34,25 +34,23 @@ import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.player.Permissions; -import org.shanerx.tradeshop.player.ShopRole; import java.io.Serializable; public enum ShopType implements Serializable { - TRADE(Setting.TRADESHOP_HEADER.getString(), Permissions.CREATE), + TRADE(Permissions.CREATE), - ITRADE(Setting.ITRADESHOP_HEADER.getString(), Permissions.CREATEI), + ITRADE(Permissions.CREATEI), - BITRADE(Setting.BITRADESHOP_HEADER.getString(), Permissions.CREATEBI); + BITRADE(Permissions.CREATEBI); private final static TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); - private final String key; + private Setting key; private final transient Permissions perm; - ShopType(String key, Permissions perm) { - this.key = key; + ShopType(Permissions perm) { this.perm = perm; } @@ -84,18 +82,23 @@ public static ShopType getType(Sign s) { return null; } - public static ShopRole deserialize(String serialized) { - ShopRole shopRole = new Gson().fromJson(serialized, ShopRole.class); - return shopRole; + public static ShopType deserialize(String serialized) { + return new Gson().fromJson(serialized, ShopType.class); } @Override public String toString() { - return key; + return getKey().getString(); } public String toHeader() { - return "[" + key + "]"; + return "[" + getKey().getString() + "]"; + } + + private Setting getKey() { + if (key == null) + key = Setting.findSetting(name() + "SHOP_HEADER"); + return key; } public boolean checkPerm(Player pl) { diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java index 63cdc20a..17669242 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java @@ -39,6 +39,7 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; @@ -52,6 +53,7 @@ import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shop.ShopChest; +import org.shanerx.tradeshop.shop.ShopSettingKeys; import org.shanerx.tradeshop.shop.ShopType; import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; @@ -86,13 +88,11 @@ public void onInventoryMoveItem(InventoryMoveItemEvent event) { Boolean skip = plugin.getListManager().canSkipHopper(event.getInitiator().getLocation()); if (skip != null) { - event.setCancelled(skip); + if (skip) event.setCancelled(true); return; } - boolean fromHopper; - - fromHopper = event.getInitiator().equals(event.getSource()); + boolean fromHopper = event.getInitiator().equals(event.getSource()); Block invBlock; @@ -101,31 +101,36 @@ public void onInventoryMoveItem(InventoryMoveItemEvent event) { invBlock = (fromHopper ? event.getDestination() : event.getSource()).getLocation().getBlock(); } catch (NullPointerException ignored) { plugin.getListManager().addSkippableHopper(event.getInitiator().getLocation(), false); + plugin.getDebugger().log("Protection Null Catch for \n " + event.getInitiator().getLocation(), DebugLevels.PROTECTION); return; } if (!plugin.getListManager().isInventory(invBlock)) { plugin.getListManager().addSkippableHopper(event.getInitiator().getLocation(), false); + plugin.getDebugger().log("Protection Inventory Catch for \n " + event.getInitiator().getLocation(), DebugLevels.PROTECTION); return; } if (!ShopChest.isShopChest(invBlock)) { - plugin.getListManager().addSkippableHopper(event.getInitiator().getLocation(), false); + //Just return as adding these to the skip would often catch the second half of hoppers pulling from shops then pushing to a chest + + //plugin.getListManager().addSkippableHopper(event.getInitiator().getLocation(), false); + //plugin.getDebugger().log("Protection ShopChest Catch for \n " + event.getInitiator().getLocation() + "\n Source: " + event.getSource().getLocation() + "\n Destination: " + event.getDestination().getLocation(), DebugLevels.PROTECTION); return; } Shop shop = plugin.getDataStorage().loadShopFromStorage(new ShopLocation(invBlock.getLocation())); - boolean isForbidden = !Setting.findSetting(shop.getShopType().name() + "SHOP_HOPPER_" + (fromHopper ? "IMPORT" : "EXPORT")).getBoolean(); + boolean isForbidden = !(fromHopper ? shop.getShopSetting(ShopSettingKeys.HOPPER_IMPORT).asBoolean() : shop.getShopSetting(ShopSettingKeys.HOPPER_EXPORT).asBoolean()); if (isForbidden) { event.setCancelled(true); - plugin.getListManager().addSkippableHopper(event.getInitiator().getLocation(), true); + //plugin.getListManager().addSkippableShop(event.getInitiator().getLocation(), true); return; } - debugger.log("ShopProtectionListener: Triggered > " + (fromHopper ? "FROM_HOPPER" : "TO_HOPPER"), DebugLevels.PROTECTION); - debugger.log("ShopProtectionListener: Shop Location as SL > " + shop.getInventoryLocationAsSL().serialize(), DebugLevels.PROTECTION); - debugger.log("ShopProtectionListener: checked hopper setting > " + shop.getShopType().name() + "SHOP_HOPPER_EXPORT", DebugLevels.PROTECTION); + plugin.getDebugger().log("ShopProtectionListener: Triggered > " + (fromHopper ? "FROM_HOPPER" : "TO_HOPPER"), DebugLevels.PROTECTION); + plugin.getDebugger().log("ShopProtectionListener: Shop Location as SL > " + shop.getInventoryLocationAsSL().serialize(), DebugLevels.PROTECTION); + plugin.getDebugger().log("ShopProtectionListener: checked hopper setting > " + shop.getShopType().name() + "SHOP_HOPPER_EXPORT", DebugLevels.PROTECTION); HopperShopAccessEvent hopperEvent = new HopperShopAccessEvent( shop, event.getSource(), @@ -133,22 +138,15 @@ public void onInventoryMoveItem(InventoryMoveItemEvent event) { event.getItem(), fromHopper ? HopperShopAccessEvent.HopperDirection.FROM_HOPPER : HopperShopAccessEvent.HopperDirection.TO_HOPPER ); - debugger.log("ShopProtectionListener: (TSAF) HopperEvent fired! ", DebugLevels.PROTECTION); + plugin.getDebugger().log("ShopProtectionListener: (TSAF) HopperEvent fired! ", DebugLevels.PROTECTION); Bukkit.getPluginManager().callEvent(hopperEvent); - debugger.log("ShopProtectionListener: (TSAF) HopperEvent recovered! ", DebugLevels.PROTECTION); - debugger.log("ShopProtectionListener: (TSAF) HopperEvent isForbidden: " + hopperEvent.isForbidden(), DebugLevels.PROTECTION); + plugin.getDebugger().log("ShopProtectionListener: (TSAF) HopperEvent recovered! ", DebugLevels.PROTECTION); + plugin.getDebugger().log("ShopProtectionListener: (TSAF) HopperEvent isForbidden: " + hopperEvent.isForbidden(), DebugLevels.PROTECTION); event.setCancelled(hopperEvent.isForbidden()); - plugin.getListManager().addSkippableHopper(event.getInitiator().getLocation(), hopperEvent.isForbidden()); + //plugin.getListManager().addSkippableShop(event.getInitiator().getLocation(), hopperEvent.isForbidden()); if (!hopperEvent.isForbidden()) { - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - public void run() { - shop.updateSign(); - shop.saveShop(); - } - }, 2L); - + scheduleShopDelayUpdate(shop, 2L); } } @@ -322,6 +320,19 @@ public void onChestOpen(PlayerInteractEvent e) { } } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onChestInventoryClose(InventoryCloseEvent e) { + if (e.getInventory().getLocation() == null) + return; + + Block block = e.getInventory().getLocation().getBlock(); + + if (ShopChest.isShopChest(block)) { + scheduleShopDelayUpdate(new ShopChest(block.getLocation()).getShop(), 2L); + } + + } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { @@ -354,4 +365,16 @@ public void onBlockPlace(BlockPlaceEvent event) { } return; } + + private void scheduleShopDelayUpdate(Shop shop, Long delay) { + plugin.getDebugger().log("Shop Being updated from ProtectionListener...\n " + shop.getShopLocationAsSL().serialize(), DebugLevels.PROTECTION); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + @Override + public void run() { + shop.updateFullTradeCount(); + shop.updateSign(); + shop.saveShop(); + } + }, delay); + } } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java index 68bf8011..106f73be 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java @@ -188,13 +188,16 @@ public void onBlockInteract(PlayerInteractEvent e) { tradedItems.put(Variable.GIVEN_LINES, tradeReturn.getRight()); tradedItems.put(Variable.RECEIVED_LINES, tradeReturn.getLeft()); - if (tradeReturn.getLeft().get(0) != null && tradeReturn.getRight().get(0) != null) { - Message.ON_TRADE.sendItemMultiLineMessage(buyer, tradedItems, - new Tuple<>(Variable.SELLER.toString(), shop.getShopType().isITrade() ? Setting.ITRADESHOP_OWNER.getString() : owner)); - } else { + if (tradeReturn.getLeft().get(0) == null && tradeReturn.getRight().get(0) == null) { Message.FAILED_TRADE.sendMessage(buyer); + + } else { + Message.ON_TRADE.sendItemMultiLineMessage(buyer, tradedItems, + new Tuple<>(Variable.SELLER.toString(), shop.getShopType().equals(ShopType.ITRADE) ? Setting.ITRADESHOP_OWNER.getString() : owner)); } + + shop.updateFullTradeCount(); shop.updateSign(); shop.saveShop(); } @@ -205,113 +208,78 @@ private Tuple, List> tradeAllItems(Shop shop, int mul Inventory shopInventory = shop.hasStorage() ? shop.getChestAsSC().getInventory() : null; Inventory playerInventory = buyer.getInventory(); - if (shop.getShopType() == ShopType.ITRADE && action.equals(Action.RIGHT_CLICK_BLOCK)) { //ITrade trade - - if (shop.hasSide(ShopItemSide.COST)) { - costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); - if (costItems.get(0) == null) { - ItemStack item = costItems.get(1); - Message.INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, costItems)); - return new Tuple<>(productItems, costItems); - } - - for (ItemStack item : costItems) { - playerInventory.removeItem(item); - } - } else { - costItems.clear(); - - //Create Free item and set amount/name - ItemStack noCostITradeItem = new ItemStack(Material.STICK, Setting.ITRADESHOP_NO_COST_AMOUNT.getInt()); - ItemMeta noCostITradeMeta = noCostITradeItem.getItemMeta(); - noCostITradeMeta.setDisplayName(Setting.ITRADESHOP_NO_COST_TEXT.getString()); - noCostITradeItem.setItemMeta(noCostITradeMeta); - - costItems.add(noCostITradeItem); - } - - Inventory iTradeVirtualInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getSideList(ShopItemSide.PRODUCT).size() / 9.0) * 9) * multiplier, 54)); - while (iTradeVirtualInventory.firstEmpty() != -1) { + if (shop.getShopType().equals(ShopType.ITRADE)) { + shopInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getSideList(ShopItemSide.PRODUCT).size() / 9.0) * 9) * multiplier, 54)); + while (shopInventory.firstEmpty() != -1) { for (ItemStack item : shop.getSideItemStacks(ShopItemSide.PRODUCT)) { item.setAmount(item.getMaxStackSize()); - iTradeVirtualInventory.addItem(item); + shopInventory.addItem(item); } } + } - productItems = getItems(iTradeVirtualInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); - - for (ItemStack item : productItems) { - playerInventory.addItem(item); - } - - Bukkit.getPluginManager().callEvent(new PlayerSuccessfulTradeEvent(buyer, costItems, productItems, shop, event.getClickedBlock(), event.getBlockFace())); - PLUGIN.getMetricsManager().addTrade(); - return new Tuple<>(productItems, costItems); //Successfully completed trade - } else if (shop.getShopType() == ShopType.BITRADE && action == Action.LEFT_CLICK_BLOCK) { //BiTrade Reversed Trade + boolean isBi = shop.getShopType().equals(ShopType.BITRADE) && action.equals(Action.LEFT_CLICK_BLOCK), + useCost = !shop.isNoCost() || shop.hasSide(ShopItemSide.COST); - //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); //Reverse BiTrade, Product is Cost + //Method to find Cost items in player inventory and add to cost array + if (useCost) { + costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST, isBi), multiplier); if (costItems.get(0) == null) { ItemStack item = costItems.get(1); Message.INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, costItems)); return new Tuple<>(productItems, costItems); } + } else { + costItems.clear(); - //Method to find Product items in shop inventory and add to product array - productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); //Reverse BiTrade, Cost is Product - if (productItems.get(0) == null) { - ItemStack item = productItems.get(1); - shop.updateStatus(); - Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, productItems)); - return new Tuple<>(productItems, costItems); - } - } else if (action.equals(Action.RIGHT_CLICK_BLOCK)) { // Normal Trade + ItemStack noCostItem = new ItemStack(Material.STICK, Setting.NO_COST_AMOUNT.getInt()); + ItemMeta noCostMeta = noCostItem.getItemMeta(); + noCostMeta.setDisplayName(Setting.NO_COST_TEXT.getString()); + noCostItem.setItemMeta(noCostMeta); - //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); - if (costItems.get(0) == null) { - ItemStack item = costItems.get(1); - Message.INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, costItems)); - return new Tuple<>(productItems, costItems); - } + costItems.add(noCostItem); + } - //Method to find Product items in shop inventory and add to product array - productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); - if (productItems.get(0) == null) { - ItemStack item = productItems.get(1); - shop.updateStatus(); - Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, productItems)); - return new Tuple<>(productItems, costItems); - } + //Method to find Product items in shop inventory and add to product array + productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT, isBi), multiplier); + if (productItems.get(0) == null) { + ItemStack item = productItems.get(1); + shop.updateStatus(); + Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, productItems)); + return new Tuple<>(productItems, costItems); + } + if (costItems.size() == 0) { + return new Tuple<>(productItems, costItems); // Failed Trade } - if (costItems.size() > 0) { + if (useCost) { //For loop to remove cost items from player inventory for (ItemStack item : costItems) { playerInventory.removeItem(item); } + } - //For loop to remove product items from shop inventory - for (ItemStack item : productItems) { - shopInventory.removeItem(item); - } + //For loop to remove product items from shop inventory + for (ItemStack item : productItems) { + shopInventory.removeItem(item); + } + if (useCost) { //For loop to put cost items in shop inventory for (ItemStack item : costItems) { shopInventory.addItem(item); } + } - //For loop to put product items in player inventory - for (ItemStack item : productItems) { - playerInventory.addItem(item); - } - - Bukkit.getPluginManager().callEvent(new PlayerSuccessfulTradeEvent(buyer, costItems, productItems, shop, event.getClickedBlock(), event.getBlockFace())); - PLUGIN.getMetricsManager().addTrade(); - return new Tuple<>(productItems, costItems); //Successfully completed trade - } else { - return new Tuple<>(productItems, costItems); + //For loop to put product items in player inventory + for (ItemStack item : productItems) { + playerInventory.addItem(item); } + + Bukkit.getPluginManager().callEvent(new PlayerSuccessfulTradeEvent(buyer, costItems, productItems, shop, event.getClickedBlock(), event.getBlockFace())); + PLUGIN.getMetricsManager().addTrade(); + + return new Tuple<>(productItems, costItems); //Successfully completed trade } } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/ListManager.java b/src/main/java/org/shanerx/tradeshop/utils/ListManager.java index 30dc1840..fe052930 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/ListManager.java +++ b/src/main/java/org/shanerx/tradeshop/utils/ListManager.java @@ -54,7 +54,7 @@ public class ListManager extends Utils { private final ArrayList gameMats = new ArrayList<>(); private final ArrayList addOnMats = new ArrayList<>(); - private Cache skippableHoppers; //second data type doesn't matter and isn't used, boolean chosen as it is the smallest + private Cache skippableHoppers, skippableShop; public ListManager() { @@ -62,24 +62,46 @@ public ListManager() { setGameMatList(); } - private void initSkippableHoppers() { + private void initSkip() { skippableHoppers = CacheBuilder.newBuilder() .maximumSize(100000) .expireAfterAccess(1000, TimeUnit.MILLISECONDS) .build(); + skippableShop = CacheBuilder.newBuilder() + .maximumSize(1000) + .expireAfterWrite(1500, TimeUnit.MILLISECONDS) + .build(); } + /** + * Check if a hopper has already been processed and stored in the cache + * + * @param location What location to check for + * @return return null if not in cache(un-unprocessed) or true/false representing whether to block movement + */ public Boolean canSkipHopper(Location location) { - if (skippableHoppers.getIfPresent(location) == null) + if (skippableHoppers.getIfPresent(location) == null && skippableShop.getIfPresent(location) == null) return null; - else + else if (skippableHoppers.getIfPresent(location) != null) return skippableHoppers.getIfPresent(location); + else if (skippableShop.getIfPresent(location) != null) + return skippableShop.getIfPresent(location); + + return null; } public void addSkippableHopper(Location location, boolean shouldBlock) { skippableHoppers.put(location, shouldBlock); } + public void addSkippableShop(Location location, boolean shouldBlock) { + skippableShop.put(location, shouldBlock); + } + + public void removeSkippableShop(Location location) { + skippableShop.invalidate(location); + } + public ArrayList getDirections() { return directions; @@ -121,7 +143,7 @@ public boolean isInventory(Block block) { Material blockMaterial = block.getType(); Boolean found = false; - debugger.log("isInventory Block Material: " + blockMaterial.name(), DebugLevels.LIST_MANAGER); + PLUGIN.getDebugger().log("isInventory Block Material: " + blockMaterial.name(), DebugLevels.LIST_MANAGER); //For each ShopStorage.Storages in inventories, check if their block list contains the block material. end loop if true. for (ShopStorage.Storages storage : inventories) { @@ -129,9 +151,9 @@ public boolean isInventory(Block block) { found = true; break; } - } + } - debugger.log("isInventory Block Material found: " + found, DebugLevels.LIST_MANAGER); + PLUGIN.getDebugger().log("isInventory Block Material found: " + found, DebugLevels.LIST_MANAGER); return found; } @@ -141,7 +163,7 @@ public void reload() { updateDirections(); updateInventoryMats(); setGameMatList(); - initSkippableHoppers(); + initSkip(); } public void clearManager() { @@ -168,7 +190,7 @@ private void updateIllegalLists() { if (globalList.getType().equals(IllegalItemList.ListType.DISABLED)) globalList.setType(IllegalItemList.ListType.BLACKLIST); - debugger.log("Loading GLOBAL Illegal Item List with mode: " + globalList.getType(), DebugLevels.ILLEGAL_ITEMS_LIST); + PLUGIN.getDebugger().log("Loading GLOBAL Illegal Item List with mode: " + globalList.getType(), DebugLevels.ILLEGAL_ITEMS_LIST); if (globalList.getType().equals(IllegalItemList.ListType.BLACKLIST)) { // Add non-removable blacklist items globalList.add(Material.AIR); @@ -184,12 +206,12 @@ private void updateIllegalLists() { globalList.checkAndAdd(str); } - debugger.log("Loading COST Illegal Item List with mode: " + costList.getType(), DebugLevels.ILLEGAL_ITEMS_LIST); + PLUGIN.getDebugger().log("Loading COST Illegal Item List with mode: " + costList.getType(), DebugLevels.ILLEGAL_ITEMS_LIST); for (String str : Setting.COST_ILLEGAL_ITEMS_LIST.getStringList()) { costList.checkAndAdd(str); } - debugger.log("Loading PRODUCT Illegal Item List with mode: " + productList.getType(), DebugLevels.ILLEGAL_ITEMS_LIST); + PLUGIN.getDebugger().log("Loading PRODUCT Illegal Item List with mode: " + productList.getType(), DebugLevels.ILLEGAL_ITEMS_LIST); for (String str : Setting.PRODUCT_ILLEGAL_ITEMS_LIST.getStringList()) { productList.checkAndAdd(str); } @@ -229,8 +251,8 @@ private void updateInventoryMats() { //Clears the list before updating inventories.clear(); - debugger.log("Inventory Materials from Config:", DebugLevels.STARTUP); - debugger.log("Config String | Status | Matching Type", DebugLevels.STARTUP); + PLUGIN.getDebugger().log("Inventory Materials from Config:", DebugLevels.STARTUP); + PLUGIN.getDebugger().log("Config String | Status | Matching Type", DebugLevels.STARTUP); //For each String in the Allowed shops config setting, check if it is a valid inventory and add the ShopStorage.Storages object to the list for (String str : Setting.ALLOWED_SHOPS.getStringList()) { @@ -244,7 +266,7 @@ private void updateInventoryMats() { logMsg += " | InValid"; } - debugger.log(logMsg, DebugLevels.STARTUP); + PLUGIN.getDebugger().log(logMsg, DebugLevels.STARTUP); } } } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java b/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java index e227c8f3..630c8f69 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java +++ b/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java @@ -100,7 +100,8 @@ private void addFeatureMetric() { @Override public Map call() throws Exception { Map map = new HashMap<>(); - List booleanSettingList = Arrays.asList(Setting.CHECK_UPDATES, + List booleanSettingList = Arrays.asList( + Setting.CHECK_UPDATES, Setting.UNLIMITED_ADMIN, Setting.ALLOW_TOGGLE_STATUS, Setting.ALLOW_SIGN_BREAK, @@ -108,12 +109,8 @@ public Map call() throws Exception { Setting.ALLOW_MULTI_TRADE, Setting.ALLOW_USER_PURCHASING, Setting.TRADESHOP_EXPLODE, - Setting.TRADESHOP_HOPPER_EXPORT, - Setting.TRADESHOP_HOPPER_IMPORT, Setting.ITRADESHOP_EXPLODE, - Setting.BITRADESHOP_EXPLODE, - Setting.BITRADESHOP_HOPPER_EXPORT, - Setting.BITRADESHOP_HOPPER_IMPORT); + Setting.BITRADESHOP_EXPLODE); for (Setting setting : booleanSettingList) { if (setting.getBoolean()) { @@ -220,7 +217,8 @@ private void addOtherSettingMetrics() { // Temporary solutions while Bar graphs are unavailable private void addFeaturePieMetrics() { - List booleanSettingList = Arrays.asList(Setting.CHECK_UPDATES, + List booleanSettingList = Arrays.asList( + Setting.CHECK_UPDATES, Setting.UNLIMITED_ADMIN, Setting.ALLOW_TOGGLE_STATUS, Setting.ALLOW_SIGN_BREAK, @@ -228,12 +226,8 @@ private void addFeaturePieMetrics() { Setting.ALLOW_MULTI_TRADE, Setting.ALLOW_USER_PURCHASING, Setting.TRADESHOP_EXPLODE, - Setting.TRADESHOP_HOPPER_EXPORT, - Setting.TRADESHOP_HOPPER_IMPORT, Setting.ITRADESHOP_EXPLODE, - Setting.BITRADESHOP_EXPLODE, - Setting.BITRADESHOP_HOPPER_EXPORT, - Setting.BITRADESHOP_HOPPER_IMPORT); + Setting.BITRADESHOP_EXPLODE); for (Setting setting : booleanSettingList) { metrics.addCustomChart(new SimplePie(setting.name().toLowerCase(), () -> { diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index a5c15933..a64055db 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -52,7 +52,6 @@ import org.shanerx.tradeshop.shop.ShopChest; import org.shanerx.tradeshop.shop.ShopType; import org.shanerx.tradeshop.shoplocation.ShopLocation; -import org.shanerx.tradeshop.utils.debug.Debug; import org.shanerx.tradeshop.utils.debug.DebugLevels; import org.shanerx.tradeshop.utils.objects.Tuple; @@ -77,10 +76,7 @@ public class Utils { public final TradeShop PLUGIN = Objects.requireNonNull((TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop")); protected PluginDescriptionFile pdf = PLUGIN.getDescription(); - public Debug debugger; - public Utils() { - debugger = PLUGIN.getDebugger(); } public UUID[] getMakers() { @@ -371,80 +367,44 @@ public Tuple> canExchangeAll(Shop shop, Inventor Inventory shopInventory = null; - if (shop.getShopType() != ShopType.ITRADE) { - Inventory shopInv = shop.getChestAsSC().getInventory(); - shopInventory = Bukkit.createInventory(null, shopInv.getStorageContents().length); - shopInventory.setContents(shopInv.getStorageContents().clone()); - } - - List costItems, productItems; - - if (shop.getShopType() == ShopType.ITRADE) { //ITrade trade - - //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); - - if (!costItems.isEmpty()) { - if (costItems.get(0) == null) { - return new Tuple<>(ExchangeStatus.PLAYER_NO_COST, costItems); - } - - for (ItemStack item : costItems) { - playerInventory.removeItem(item); - } - } - - Inventory iTradeVirtualInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getSideList(ShopItemSide.PRODUCT).size() / 9.0) * 9) * multiplier, 54)); - while (iTradeVirtualInventory.firstEmpty() != -1) { + if (shop.getShopType().equals(ShopType.ITRADE)) { + shopInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getSideList(ShopItemSide.PRODUCT).size() / 9.0) * 9) * multiplier, 54)); + while (shopInventory.firstEmpty() != -1) { for (ItemStack item : shop.getSideItemStacks(ShopItemSide.PRODUCT)) { item.setAmount(item.getMaxStackSize()); - iTradeVirtualInventory.addItem(item); + shopInventory.addItem(item); } } + } else { + Inventory shopInv = shop.getChestAsSC().getInventory(); + shopInventory = Bukkit.createInventory(null, shopInv.getStorageContents().length); + shopInventory.setContents(shopInv.getStorageContents().clone()); + } - productItems = getItems(iTradeVirtualInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); - - for (ItemStack item : productItems) { - if (!playerInventory.addItem(item).isEmpty()) { - return new Tuple<>(ExchangeStatus.PLAYER_NO_SPACE, createBadList()); - } - } - - return new Tuple<>(ExchangeStatus.SUCCESS, createBadList()); //Successfully completed trade - } else if (shop.getShopType() == ShopType.BITRADE && action == Action.LEFT_CLICK_BLOCK) { //BiTrade Reversed Trade - - //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); //Reverse BiTrade, Product is Cost - if (costItems.get(0) == null) { - return new Tuple<>(ExchangeStatus.PLAYER_NO_COST, costItems); - } + List costItems = new ArrayList<>(), productItems; - //Method to find Product items in shop inventory and add to product array - productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); //Reverse BiTrade, Cost is Product - if (productItems.get(0) == null) { - shop.updateStatus(); - return new Tuple<>(ExchangeStatus.SHOP_NO_PRODUCT, productItems); - } - } else { // Normal Trade + boolean isBi = shop.getShopType().equals(ShopType.BITRADE) && action.equals(Action.LEFT_CLICK_BLOCK); - //Method to find Cost items in player inventory and add to cost array - costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST), multiplier); + //Method to find Cost items in player inventory and add to cost array + if (!shop.isNoCost() || shop.hasSide(ShopItemSide.COST)) { + costItems = getItems(playerInventory.getStorageContents(), shop.getSideList(ShopItemSide.COST, isBi), multiplier); if (costItems.get(0) == null) { return new Tuple<>(ExchangeStatus.PLAYER_NO_COST, costItems); } + } - //Method to find Product items in shop inventory and add to product array - productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT), multiplier); - if (productItems.get(0) == null) { - shop.updateStatus(); - return new Tuple<>(ExchangeStatus.SHOP_NO_PRODUCT, productItems); - } - + //Method to find Product items in shop inventory and add to product array + productItems = getItems(shopInventory.getStorageContents(), shop.getSideList(ShopItemSide.PRODUCT, isBi), multiplier); + if (productItems.get(0) == null) { + shop.updateStatus(); + return new Tuple<>(ExchangeStatus.SHOP_NO_PRODUCT, productItems); } - //For loop to remove cost items from player inventory - for (ItemStack item : costItems) { - playerInventory.removeItem(item); + if (costItems.size() > 0) { + //For loop to remove cost items from player inventory + for (ItemStack item : costItems) { + playerInventory.removeItem(item); + } } //For loop to remove product items from shop inventory @@ -452,10 +412,12 @@ public Tuple> canExchangeAll(Shop shop, Inventor shopInventory.removeItem(item); } - //For loop to put cost items in shop inventory - for (ItemStack item : costItems) { - if (!shopInventory.addItem(item).isEmpty()) { - return new Tuple<>(ExchangeStatus.SHOP_NO_SPACE, createBadList()); + if (costItems.size() > 0) { + //For loop to put cost items in shop inventory + for (ItemStack item : costItems) { + if (!shopInventory.addItem(item).isEmpty()) { + return new Tuple<>(ExchangeStatus.SHOP_NO_SPACE, createBadList()); + } } } @@ -540,15 +502,15 @@ public Shop createShop(Sign shopSign, Player creator, ShopType shopType, ItemSta shop = new Shop(shopSign.getLocation(), shopType, owner); } - debugger.log("-----Pre-Event-----", DebugLevels.SHOP_CREATION); - debugger.log(shop.toDebug(), DebugLevels.SHOP_CREATION); + PLUGIN.getDebugger().log("-----Pre-Event-----", DebugLevels.SHOP_CREATION); + PLUGIN.getDebugger().log(shop.toDebug(), DebugLevels.SHOP_CREATION); - debugger.log("-----Post-Event-----", DebugLevels.SHOP_CREATION); + PLUGIN.getDebugger().log("-----Post-Event-----", DebugLevels.SHOP_CREATION); PlayerShopCreateEvent shopCreateEvent = new PlayerShopCreateEvent(creator, shop); Bukkit.getPluginManager().callEvent(shopCreateEvent); if (shopCreateEvent.isCancelled()) { - debugger.log("Creation Failed!", DebugLevels.SHOP_CREATION); + PLUGIN.getDebugger().log("Creation Failed!", DebugLevels.SHOP_CREATION); return null; } @@ -556,14 +518,14 @@ public Shop createShop(Sign shopSign, Player creator, ShopType shopType, ItemSta if (event != null) { shop.updateSign(event); - debugger.log("Event Sign Lines: \n" + event.getLine(0) + "\n" + event.getLine(1) + "\n" + event.getLine(2) + "\n" + event.getLine(3), DebugLevels.SHOP_CREATION); + PLUGIN.getDebugger().log("Event Sign Lines: \n" + event.getLine(0) + "\n" + event.getLine(1) + "\n" + event.getLine(2) + "\n" + event.getLine(3), DebugLevels.SHOP_CREATION); } else { shop.updateSign(shopSign); - debugger.log("Sign Lines: \n" + shopSign.getLine(0) + "\n" + shopSign.getLine(1) + "\n" + shopSign.getLine(2) + "\n" + shopSign.getLine(3), DebugLevels.SHOP_CREATION); + PLUGIN.getDebugger().log("Sign Lines: \n" + shopSign.getLine(0) + "\n" + shopSign.getLine(1) + "\n" + shopSign.getLine(2) + "\n" + shopSign.getLine(3), DebugLevels.SHOP_CREATION); } Message.SUCCESSFUL_SETUP.sendMessage(creator); - debugger.log("Creation Successful!", DebugLevels.SHOP_CREATION); + PLUGIN.getDebugger().log("Creation Successful!", DebugLevels.SHOP_CREATION); return shop; } @@ -605,7 +567,7 @@ public List getItems(ItemStack[] storageContents, List Map storage = new HashMap<>(), found = new HashMap<>(); List good = new ArrayList(), bad = createBadList(); - debugger.log("Utils > getItems > Search List: " + search, DebugLevels.TRADE); + PLUGIN.getDebugger().log("Utils > getItems > Search List: " + search, DebugLevels.TRADE); for (ItemStack itemStack : storageContents.clone()) { if (itemStack != null) { @@ -618,7 +580,7 @@ public List getItems(ItemStack[] storageContents, List } } - debugger.log("Utils > getItems > Storage List: " + storage, DebugLevels.TRADE); + PLUGIN.getDebugger().log("Utils > getItems > Storage List: " + storage, DebugLevels.TRADE); int totalCount = 0, currentCount = 0; @@ -654,9 +616,9 @@ public List getItems(ItemStack[] storageContents, List } } - debugger.log("Utils > getItems > Good List: " + good, DebugLevels.TRADE); - debugger.log("Utils > getItems > Bad List: " + bad, DebugLevels.TRADE); - debugger.log("Utils > getItems > Return Status: " + (currentCount != totalCount ? "bad" : "good"), DebugLevels.TRADE); + PLUGIN.getDebugger().log("Utils > getItems > Good List: " + good, DebugLevels.TRADE); + PLUGIN.getDebugger().log("Utils > getItems > Bad List: " + bad, DebugLevels.TRADE); + PLUGIN.getDebugger().log("Utils > getItems > Return Status: " + (currentCount != totalCount ? "bad" : "good"), DebugLevels.TRADE); return currentCount != totalCount ? bad : good; } diff --git a/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java index 037481e5..95a01c69 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java @@ -38,19 +38,31 @@ public Type getObject() { } public boolean isBoolean() { - return obj instanceof Boolean; + return obj != null && obj instanceof Boolean; } public boolean isInteger() { - return obj instanceof Integer; + return obj != null && obj instanceof Integer; } public boolean isDouble() { - return obj instanceof Double; + return obj != null && obj instanceof Double; } public boolean isString() { - return obj instanceof String; + return obj != null && obj instanceof String; + } + + public Boolean asBoolean() { + return isBoolean() ? Boolean.parseBoolean(obj.toString()) : null; + } + + public Integer asInteger() { + return isInteger() ? Integer.parseInt(obj.toString()) : null; + } + + public Double asDouble() { + return isDouble() ? Double.parseDouble(obj.toString()) : null; } @Override diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index e729bd4e..8308fc1b 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -126,6 +126,10 @@ setting: pre-comment: "Can players purchase from a shop in which they are a user of (true/false)" multiple-items-on-sign: pre-comment: "Text that shows on trade signs that contain more than 1 item\n Available variables are: %AMOUNT%" + no-cost-text: + pre-comment: "What text should be used for successful trades when no cost is present" + no-cost-amount: + pre-comment: "What amount should be used for successful trades when no cost is present(must be greater than 0)" post-comment: "\n" shop-per-item-options: shop-per-item-settings: @@ -151,11 +155,6 @@ setting: pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" allow-explode: pre-comment: "Can explosions damage the shop sign (true/false)" - no-cost-text: - pre-comment: "What text should be used for successful trades when no cost is present" - no-cost-amount: - pre-comment: "What amount should be used for successful trades when no cost is present(must be greater than 0)" - post-comment: "\n" bitrade-shop-options: header: pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" From 3ea9ed079fa22ad24c67e6c25634e4546b542b11 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 22 Jun 2022 22:11:12 -0700 Subject: [PATCH 22/53] Bug Fix - Fix for bug reported by LewisB1#9506 on Discord where errors were being caused by old shops that required `/ts what` to view. --- .../java/org/shanerx/tradeshop/shop/Shop.java | 18 +++++++++++++++++- .../org/shanerx/tradeshop/shop/ShopChest.java | 10 ++++++++-- .../org/shanerx/tradeshop/utils/Utils.java | 16 ++++++++++------ 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 064641dc..2e7593bb 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -1065,6 +1065,22 @@ public void setSideItems(ShopItemSide side, ItemStack newItem) { addSideItem(side, newItem); } + /** + * Attempts to fix the side of the trade in cases where an error was found. + * + * @param side Side of the trade to fix + */ + public void fixSide(ShopItemSide side) { + getSide(side).clear(); + try { + getSideItemStacks(side).forEach((item) -> { + if (item != null) addSideItem(side, item); + }); + } catch (NullPointerException ignored) { + getSide(side).clear(); + } + } + /** * Adds more items to the specified side * @@ -1107,7 +1123,7 @@ public void addSideItem(ShopItemSide side, ItemStack newItem) { * Checks if the shop has sufficient stock to make a trade on specified side */ public boolean hasSideStock(ShopItemSide side) { - return !shopType.isITrade() && hasSide(side) && getChestAsSC() != null && getChestAsSC().hasStock(getSideList(side)); + return !shopType.isITrade() && hasSide(side) && getChestAsSC() != null && getChestAsSC().hasStock(side, getSideList(side)); } /** diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java index 45a8bed4..6c727fca 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java @@ -39,6 +39,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.persistence.PersistentDataType; import org.shanerx.tradeshop.TradeShop; +import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.shoplocation.IllegalWorldException; import org.shanerx.tradeshop.shoplocation.ShopLocation; @@ -208,8 +209,13 @@ public Inventory getInventory() { return null; } - public boolean hasStock(List itemToCheck) { - return itemToCheck.size() > 0 && getItems(getInventory().getStorageContents(), itemToCheck, 1).get(0) != null; + public boolean hasStock(ShopItemSide side, List itemToCheck) { + List result = getItems(getInventory().getStorageContents(), itemToCheck, 1); + if (result.get(0) == null && result.size() == 1) { + getShop().fixSide(side); + } + + return itemToCheck.size() > 0 && result.get(0) != null; } public void loadFromName() { diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index a64055db..4d937dfb 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -589,14 +589,18 @@ public List getItems(ItemStack[] storageContents, List totalCount += count; for (ItemStack storageItem : storage.keySet()) { - boolean isSimilar = item.isSimilar(storageItem); - if (isSimilar) { - int taken = megaMin(storage.get(storageItem), count, storageItem.getMaxStackSize()); + if (item.isSimilar(storageItem)) { + int taken; + try { + taken = megaMin(storage.get(storageItem), count, storageItem.getMaxStackSize()); - if (found.putIfAbsent(item.getItemStack(), taken) != null) - found.put(item.getItemStack(), storage.get(storageItem) + taken); + if (found.putIfAbsent(item.getItemStack(), taken) != null) + found.put(item.getItemStack(), storage.get(storageItem) + taken); - storage.put(storageItem, storage.get(storageItem) - taken); + storage.put(storageItem, storage.get(storageItem) - taken); + } catch (NullPointerException ignored) { + return createBadList(); + } ItemStack goodItem = storageItem; goodItem.setAmount(taken); From 9233527a5c2ab3acd7928d2fba5a223ed0bb3563 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Sun, 26 Jun 2022 17:57:57 -0700 Subject: [PATCH 23/53] Bug Fixes - Proper fix for null appearing on signs(was due to the new sign color settings not being loaded) - Changed serialized value for ObjectHolder so data storage is more readable - Fix for bad data on a shop sign(That side of the trade will more than likely be removed) - Dry'd Line formatting on signs for lines 2/3 - Added serialized name for `itemSettings` to properly read in the object with the old `shopSettings` name - Added method to add ItemStacks to an inventory while temporary setting the inventories Max Stack Size to prevent overstacking items(May add as a shop setting in the future) - Added updateFullTradeCount and updateSign to what command --- .../commands/commandrunners/WhatCommand.java | 3 + .../tradeshop/data/config/ConfigManager.java | 15 ++- .../tradeshop/data/config/Setting.java | 6 +- .../shanerx/tradeshop/item/ShopItemStack.java | 32 +++-- .../item/ShopItemStackSettingKeys.java | 4 + .../java/org/shanerx/tradeshop/shop/Shop.java | 123 ++++++++++-------- .../org/shanerx/tradeshop/shop/ShopChest.java | 10 +- .../shop/listeners/ShopTradeListener.java | 19 ++- .../org/shanerx/tradeshop/utils/Utils.java | 32 +++-- .../tradeshop/utils/objects/ObjectHolder.java | 3 + 10 files changed, 145 insertions(+), 102 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java index f2f38752..a1699523 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java @@ -61,6 +61,9 @@ public void what() { if (shop == null) return; + shop.updateFullTradeCount(); + shop.updateSign(); + if (!Permissions.hasPermission(pSender, Permissions.INFO)) { command.sendMessage(Message.NO_COMMAND_PERMISSION.getPrefixed()); return; diff --git a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java index 563e5fed..8eab75e8 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/ConfigManager.java @@ -185,14 +185,14 @@ public void save() { switch (configType) { case CONFIG: - Arrays.stream(SettingSection.values()).sorted(new CompareSettingSections()).forEach((section) -> outputMap.put(section.getPath(), section.getFileString())); - Arrays.stream(Setting.values()).forEach((setting) -> outputMap.put(setting.getSection().getPath(), - outputMap.getOrDefault(setting.getSection().getPath(), "") + setting.getFileString())); + Arrays.stream(SettingSection.values()).sorted(new CompareSettingSections()).forEach((section) -> outputMap.put(section.getPath().toLowerCase().replace("_", "-"), section.getFileString())); + Arrays.stream(Setting.values()).forEach((setting) -> outputMap.put(setting.getSection().getPath().toLowerCase().replace("_", "-"), + outputMap.getOrDefault(setting.getSection().getPath().toLowerCase().replace("_", "-"), "") + setting.getFileString())); break; case MESSAGES: - Arrays.stream(MessageSection.values()).sorted(new CompareMessageSections()).forEach((section) -> outputMap.put(section.getPath(), section.getFileString())); - Arrays.stream(Message.values()).forEach((message) -> outputMap.put(message.getSection().getPath(), - outputMap.getOrDefault(message.getSection().getPath(), "") + message.getFileString())); + Arrays.stream(MessageSection.values()).sorted(new CompareMessageSections()).forEach((section) -> outputMap.put(section.getPath().toLowerCase().replace("_", "-"), section.getFileString())); + Arrays.stream(Message.values()).forEach((message) -> outputMap.put(message.getSection().getPath().toLowerCase().replace("_", "-"), + outputMap.getOrDefault(message.getSection().getPath().toLowerCase().replace("_", "-"), "") + message.getFileString())); break; } @@ -213,9 +213,10 @@ public void save() { } private boolean addKeyValue(String node, Object value) { + node = node.toLowerCase().replace("_", "-"); if (value instanceof Map) { for (Map.Entry entry : ((Map) value).entrySet()) { - String newNode = node + "." + entry.getKey().toString(); + String newNode = node + "." + entry.getKey().toString().toLowerCase().replace("_", "-"); if (config.get(newNode) == null || (config.get(newNode) != null && config.get(newNode).toString().isEmpty())) { config.set(newNode, entry.getValue().toString()); return true; diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 3b6d5c0c..3b39c1c7 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -279,15 +279,15 @@ public Object getDefaultValue() { } public String getMappedString(String subKey) { - return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getString(subKey.replace("_", "-")); + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getString(subKey.toLowerCase().replace("_", "-")); } public boolean getMappedBoolean(String subKey) { - return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getBoolean(subKey.replace("_", "-")); + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).getBoolean(subKey.toLowerCase().replace("_", "-")); } public Object getMappedObject(String subKey) { - return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).get(subKey.replace("_", "-")); + return PLUGIN.getSettingManager().getConfig().getConfigurationSection(getPath()).get(subKey.toLowerCase().replace("_", "-")); } public String getPostComment() { diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index 83aa1052..c8e9b38f 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -28,6 +28,7 @@ import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.annotations.SerializedName; import net.md_5.bungee.api.ChatColor; import org.apache.commons.lang.WordUtils; import org.bukkit.FireworkEffect; @@ -65,32 +66,30 @@ public class ShopItemStack implements Serializable, Cloneable { private String itemStackB64; + @SerializedName(value = "itemSettings", alternate = "shopSettings") private Map> itemSettings; public ShopItemStack(ItemStack itemStack) { - this.itemStack = itemStack; - itemSettings = new HashMap<>(); - buildMap(); - toBase64(); + this(itemStack, new HashMap<>()); } - public ShopItemStack(ItemStack itemStack, HashMap> settingMap) { + public ShopItemStack(ItemStack itemStack, HashMap> itemSettings) { this.itemStack = itemStack; - this.itemSettings = settingMap; + this.itemSettings = itemSettings; buildMap(); toBase64(); } public ShopItemStack(String itemStackB64) { - this.itemStackB64 = itemStackB64; - itemSettings = new HashMap<>(); - buildMap(); - fromBase64(); + this(itemStackB64, new HashMap<>()); } - public ShopItemStack(String itemStackB64, HashMap> settingMap) { + public ShopItemStack(String itemStackB64, HashMap> itemSettings) { this.itemStackB64 = itemStackB64; - this.itemSettings = settingMap; + this.itemSettings = new HashMap<>(); + + itemSettings.forEach((key, value) -> this.itemSettings.put(ShopItemStackSettingKeys.match(key), value)); + buildMap(); fromBase64(); } @@ -125,6 +124,10 @@ public Map> getItemSettings() { return itemSettings; } + public String serialize() { + return new Gson().toJson(this); + } + public static ShopItemStack deserialize(String serialized) { ShopItemStack item = new Gson().fromJson(serialized, ShopItemStack.class); item.fromBase64(); @@ -555,10 +558,6 @@ public String getStateString(ObjectHolder stateSetting) { } } - public String serialize() { - return new Gson().toJson(this); - } - @Override public String toString() { return "ShopItemStack{" + @@ -613,5 +612,4 @@ private void fromBase64() { public String toConsoleText() { return new GsonBuilder().setPrettyPrinting().create().toJson(this); } - } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java index 6f10f7fd..fb8fb88a 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java @@ -97,4 +97,8 @@ public boolean isUserEditable() { public String getConfigName() { return name().toLowerCase().replace("_", "-"); } + + public static ShopItemStackSettingKeys match(String name) { + return valueOf(name.toUpperCase().replace("-", "_")); + } } diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 2e7593bb..bdc1c9e8 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -27,7 +27,9 @@ import com.google.gson.Gson; import org.bukkit.Bukkit; +import org.bukkit.ChatColor; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Container; @@ -52,6 +54,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -271,7 +274,7 @@ public ShopLocation getInventoryLocationAsSL() { } /** - * Fixes values that cannot be serialized after loading + * Fixes values and objects after loading or creating a Shop */ public void fixAfterLoad() { if (utils == null) @@ -286,6 +289,9 @@ public void fixAfterLoad() { setShopSettings(); + fixSide(ShopItemSide.COST); + fixSide(ShopItemSide.PRODUCT); + if (getShopSign() != null) updateSign(); } @@ -415,36 +421,17 @@ private String[] updateSignLines(String defaultColour) { if (product.isEmpty()) { signLines[1] = ""; } else if (product.size() == 1) { - StringBuilder sb = new StringBuilder(); - - ShopItemStack item = product.get(0); - - sb.append(item.getItemStack().getAmount()); - sb.append(" "); - - sb.append(item.getCleanItemName()); - - signLines[1] = utils.colorize(defaultColour + sb.substring(0, Math.min(sb.length(), 15))); - + signLines[1] = itemLineFormatter(defaultColour, String.valueOf(product.get(0).getItemStack().getAmount()), " ", product.get(0).getCleanItemName()); } else { - signLines[1] = utils.colorize(defaultColour + Setting.MULTIPLE_ITEMS_ON_SIGN.getString().replace("%amount%", "")); - } + signLines[1] = itemLineFormatter(defaultColour, Setting.MULTIPLE_ITEMS_ON_SIGN.getString().replace("%amount%", "")); + } if (cost.isEmpty()) { signLines[2] = ""; } else if (cost.size() == 1) { - StringBuilder sb = new StringBuilder(); - - ShopItemStack item = cost.get(0); - - sb.append(item.getItemStack().getAmount()); - sb.append(" "); - - sb.append(item.getCleanItemName()); - - signLines[2] = utils.colorize(defaultColour + sb.substring(0, Math.min(sb.length(), 15))); + signLines[2] = itemLineFormatter(defaultColour, String.valueOf(cost.get(0).getItemStack().getAmount()), " ", cost.get(0).getCleanItemName()); } else { - signLines[2] = utils.colorize(defaultColour + Setting.MULTIPLE_ITEMS_ON_SIGN.getString()); + signLines[2] = itemLineFormatter(defaultColour, Setting.MULTIPLE_ITEMS_ON_SIGN.getString().replace("%amount%", "")); } updateStatus(); @@ -459,6 +446,18 @@ private String[] updateSignLines(String defaultColour) { return signLines; } + private String itemLineFormatter(String defaultColour, String... strings) { + StringBuilder sb = new StringBuilder(); + + for (String s : strings) { + sb.append(s); + } + + String colorFix = ChatColor.stripColor(utils.colorize(sb.toString())); + + return utils.colorize(defaultColour + colorFix.substring(0, Math.min(colorFix.length(), 15))); + } + /** * Returns the shops inventory as a BlockState * @@ -955,6 +954,34 @@ private void purgeFromUserFiles() { //region Item Management - Methods for adding/deleting/updating/viewing Cost and Product lists //------------------------------------------------------------------------------------------------------------------ + /** + * Checks if shop has a bade side and fixes if necessary + */ + public void fixSide(ShopItemSide side) { + List ogItems = (side.equals(ShopItemSide.PRODUCT) ? product : cost); + + Set matSet = new HashSet<>(); + + ogItems.forEach((item) -> matSet.add(item.getItemStack().getType())); + + + if (ogItems.size() > 1 && ogItems.size() != matSet.size()) { + List scrapList = new ArrayList<>(ogItems); + (side.equals(ShopItemSide.PRODUCT) ? product : cost).clear(); + + ogItems.forEach((item) -> { + while (scrapList.contains(item)) { + addSideItem(side, item); + scrapList.remove(scrapList.lastIndexOf(item)); + } + }); + + updateFullTradeCount(); + updateSign(); + saveShop(); + } + } + /** * Checks if shop has items on specified side * @@ -1065,42 +1092,24 @@ public void setSideItems(ShopItemSide side, ItemStack newItem) { addSideItem(side, newItem); } - /** - * Attempts to fix the side of the trade in cases where an error was found. - * - * @param side Side of the trade to fix - */ - public void fixSide(ShopItemSide side) { - getSide(side).clear(); - try { - getSideItemStacks(side).forEach((item) -> { - if (item != null) addSideItem(side, item); - }); - } catch (NullPointerException ignored) { - getSide(side).clear(); - } - } - /** * Adds more items to the specified side * - * @param side Side to add items to - * @param newItem ItemStack to be added + * @param side Side to add items to + * @param newShopItem ShopItemStack to be added */ - public void addSideItem(ShopItemSide side, ItemStack newItem) { - if (utils.isIllegal(side, newItem.getType())) + public void addSideItem(ShopItemSide side, ShopItemStack newShopItem) { + if (utils.isIllegal(side, newShopItem.getItemStack().getType())) return; - ///* Added stacks are not separated and are added ontop of existing similar stacks - ShopItemStack toAddShopItemStack = new ShopItemStack(newItem); int toRemoveShopItemStack = -1; for (int i = 0; i < getSide(side).size(); i++) { - if (getSideList(side).get(i).getItemStack().getType().equals(newItem.getType()) && getSideList(side).get(i).isSimilar(newItem)) { + if (getSideList(side).get(i).getItemStack().getType().equals(newShopItem.getItemStack().getType()) && getSideList(side).get(i).isSimilar(newShopItem.getItemStack())) { toRemoveShopItemStack = i; - toAddShopItemStack = getSideList(side).get(i).clone(); - toAddShopItemStack.setAmount(getSideList(side).get(i).getAmount() + newItem.getAmount()); + newShopItem = getSideList(side).get(i).clone(); + newShopItem.setAmount(getSideList(side).get(i).getAmount() + newShopItem.getItemStack().getAmount()); break; } } @@ -1108,7 +1117,7 @@ public void addSideItem(ShopItemSide side, ItemStack newItem) { if (toRemoveShopItemStack > -1) getSide(side).remove(toRemoveShopItemStack); - getSide(side).add(toAddShopItemStack); + getSide(side).add(newShopItem); //*/ @@ -1119,11 +1128,21 @@ public void addSideItem(ShopItemSide side, ItemStack newItem) { updateSign(); } + /** + * Adds more items to the specified side + * + * @param side Side to add items to + * @param newItem ItemStack to be added + */ + public void addSideItem(ShopItemSide side, ItemStack newItem) { + addSideItem(side, new ShopItemStack(newItem)); + } + /** * Checks if the shop has sufficient stock to make a trade on specified side */ public boolean hasSideStock(ShopItemSide side) { - return !shopType.isITrade() && hasSide(side) && getChestAsSC() != null && getChestAsSC().hasStock(side, getSideList(side)); + return !shopType.isITrade() && hasSide(side) && getChestAsSC() != null && getChestAsSC().hasStock(getSideList(side)); } /** diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java index 6c727fca..45a8bed4 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java @@ -39,7 +39,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.persistence.PersistentDataType; import org.shanerx.tradeshop.TradeShop; -import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.shoplocation.IllegalWorldException; import org.shanerx.tradeshop.shoplocation.ShopLocation; @@ -209,13 +208,8 @@ public Inventory getInventory() { return null; } - public boolean hasStock(ShopItemSide side, List itemToCheck) { - List result = getItems(getInventory().getStorageContents(), itemToCheck, 1); - if (result.get(0) == null && result.size() == 1) { - getShop().fixSide(side); - } - - return itemToCheck.size() > 0 && result.get(0) != null; + public boolean hasStock(List itemToCheck) { + return itemToCheck.size() > 0 && getItems(getInventory().getStorageContents(), itemToCheck, 1).get(0) != null; } public void loadFromName() { diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java index 106f73be..00f6ab02 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java @@ -53,6 +53,7 @@ import org.shanerx.tradeshop.shop.ShopType; import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.debug.DebugLevels; import org.shanerx.tradeshop.utils.objects.Tuple; import java.util.Collections; @@ -159,6 +160,7 @@ public void onBlockInteract(PlayerInteractEvent e) { Tuple> canExchangeResult = canExchangeAll(shop, buyer.getInventory(), multiplier, e.getAction()); + PLUGIN.getDebugger().log("ExchangeResult " + canExchangeResult.getLeft(), DebugLevels.DATA_ERROR); switch (canExchangeResult.getLeft()) { case SHOP_NO_PRODUCT: Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, canExchangeResult.getRight())); @@ -188,6 +190,8 @@ public void onBlockInteract(PlayerInteractEvent e) { tradedItems.put(Variable.GIVEN_LINES, tradeReturn.getRight()); tradedItems.put(Variable.RECEIVED_LINES, tradeReturn.getLeft()); + PLUGIN.getDebugger().log("ShopTradeListener > tradedItems: " + tradedItems, DebugLevels.TRADE); + if (tradeReturn.getLeft().get(0) == null && tradeReturn.getRight().get(0) == null) { Message.FAILED_TRADE.sendMessage(buyer); @@ -227,6 +231,7 @@ private Tuple, List> tradeAllItems(Shop shop, int mul if (costItems.get(0) == null) { ItemStack item = costItems.get(1); Message.INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, costItems)); + PLUGIN.getDebugger().log("tradeAllItems", DebugLevels.DATA_ERROR); return new Tuple<>(productItems, costItems); } } else { @@ -253,30 +258,36 @@ private Tuple, List> tradeAllItems(Shop shop, int mul return new Tuple<>(productItems, costItems); // Failed Trade } + PLUGIN.getDebugger().log("ShopTradeListener > tradeAll > preMove-productItems: " + productItems, DebugLevels.TRADE); + PLUGIN.getDebugger().log("ShopTradeListener > tradeAll > preMove-costItems: " + costItems, DebugLevels.TRADE); + if (useCost) { //For loop to remove cost items from player inventory for (ItemStack item : costItems) { - playerInventory.removeItem(item); + playerInventory.removeItem(item.clone()); } } //For loop to remove product items from shop inventory for (ItemStack item : productItems) { - shopInventory.removeItem(item); + shopInventory.removeItem(item.clone()); } if (useCost) { //For loop to put cost items in shop inventory for (ItemStack item : costItems) { - shopInventory.addItem(item); + addItemToInventory(shopInventory, item.clone()); } } //For loop to put product items in player inventory for (ItemStack item : productItems) { - playerInventory.addItem(item); + addItemToInventory(playerInventory, item.clone()); } + PLUGIN.getDebugger().log("ShopTradeListener > tradeAll > end-productItems: " + productItems, DebugLevels.TRADE); + PLUGIN.getDebugger().log("ShopTradeListener > tradeAll > end-costItems: " + costItems, DebugLevels.TRADE); + Bukkit.getPluginManager().callEvent(new PlayerSuccessfulTradeEvent(buyer, costItems, productItems, shop, event.getClickedBlock(), event.getBlockFace())); PLUGIN.getMetricsManager().addTrade(); diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 4d937dfb..c9a3600c 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -415,7 +415,7 @@ public Tuple> canExchangeAll(Shop shop, Inventor if (costItems.size() > 0) { //For loop to put cost items in shop inventory for (ItemStack item : costItems) { - if (!shopInventory.addItem(item).isEmpty()) { + if (!addItemToInventory(shopInventory, item).isEmpty()) { return new Tuple<>(ExchangeStatus.SHOP_NO_SPACE, createBadList()); } } @@ -423,7 +423,7 @@ public Tuple> canExchangeAll(Shop shop, Inventor //For loop to put product items in player inventory for (ItemStack item : productItems) { - if (!playerInventory.addItem(item).isEmpty()) { + if (!addItemToInventory(playerInventory, item).isEmpty()) { return new Tuple<>(ExchangeStatus.PLAYER_NO_SPACE, createBadList()); } } @@ -591,16 +591,12 @@ public List getItems(ItemStack[] storageContents, List for (ItemStack storageItem : storage.keySet()) { if (item.isSimilar(storageItem)) { int taken; - try { - taken = megaMin(storage.get(storageItem), count, storageItem.getMaxStackSize()); + taken = megaMin(storage.get(storageItem), count); - if (found.putIfAbsent(item.getItemStack(), taken) != null) - found.put(item.getItemStack(), storage.get(storageItem) + taken); + if (found.putIfAbsent(item.getItemStack(), taken) != null) + found.put(item.getItemStack(), storage.get(storageItem) + taken); - storage.put(storageItem, storage.get(storageItem) - taken); - } catch (NullPointerException ignored) { - return createBadList(); - } + storage.put(storageItem, storage.get(storageItem) - taken); ItemStack goodItem = storageItem; goodItem.setAmount(taken); @@ -627,11 +623,25 @@ public List getItems(ItemStack[] storageContents, List return currentCount != totalCount ? bad : good; } + /** + * Attempts to add an ItemStack to an Inventory while splitting it with its max stack size as a maximum + * + * @param inv Inventory to attempt to add the ItemStack to + * @param item ItemStack to be added to the ivnentory + * @return smallest integer + */ + public Map addItemToInventory(Inventory inv, ItemStack item) { + int maxStack = inv.getMaxStackSize(); + inv.setMaxStackSize(item.getMaxStackSize()); + Map result = inv.addItem(item); + inv.setMaxStackSize(maxStack); + return result; + } + /** * Returns the smallest integer passed to it * * @param values list of integers to compare against each other - * * @return smallest integer */ public int megaMin(int... values) { diff --git a/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java index 95a01c69..cc695d02 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java @@ -25,8 +25,11 @@ package org.shanerx.tradeshop.utils.objects; +import com.google.gson.annotations.SerializedName; + public class ObjectHolder { + @SerializedName(value = "value", alternate = "obj") private final Type obj; public ObjectHolder(Type obj) { From 00073059218bf1015624790ba0c3584b8e4bb575 Mon Sep 17 00:00:00 2001 From: Sparkling Comet Date: Mon, 4 Jul 2022 00:21:04 +0200 Subject: [PATCH 24/53] Fix midding static handler method --- .../framework/events/HopperShopAccessEvent.java | 11 ++++++++++- .../framework/events/PlayerShopChangeEvent.java | 6 +++++- .../framework/events/PlayerShopCloseEvent.java | 6 +++++- .../framework/events/PlayerShopCreateEvent.java | 6 +++++- .../framework/events/PlayerShopDestroyEvent.java | 6 +++++- .../events/PlayerShopInventoryOpenEvent.java | 6 +++++- .../framework/events/PlayerShopOpenEvent.java | 6 +++++- .../framework/events/TradeShopReloadEvent.java | 6 +++--- 8 files changed, 43 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/HopperShopAccessEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/HopperShopAccessEvent.java index 713e67df..0c3f1c94 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/HopperShopAccessEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/HopperShopAccessEvent.java @@ -48,7 +48,16 @@ public enum HopperDirection { private Shop shop; private boolean isForbidden; private final HopperDirection dir; - + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + /** * Constructor for the object. * @param s The {@link Shop} object representing the Shop in question. diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java index 1b5ce695..e885e286 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java @@ -55,7 +55,11 @@ public PlayerShopChangeEvent(Player player, Shop s, ShopChange change, ObjectHol super(player); this.shop = s; } - + + public static HandlerList getHandlerList() { + return handlers; + } + @Override public HandlerList getHandlers() { return handlers; diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCloseEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCloseEvent.java index e9b8145d..26450ed3 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCloseEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCloseEvent.java @@ -50,7 +50,11 @@ public PlayerShopCloseEvent(Player buyer, Shop s) { super(buyer); this.shop = s; } - + + public static HandlerList getHandlerList() { + return handlers; + } + @Override public HandlerList getHandlers() { return handlers; diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCreateEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCreateEvent.java index 218f1199..af17b28b 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCreateEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopCreateEvent.java @@ -50,7 +50,11 @@ public PlayerShopCreateEvent(Player p, Shop shop) { super(p); this.shop = shop; } - + + public static HandlerList getHandlerList() { + return handlers; + } + @Override public HandlerList getHandlers() { return handlers; diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopDestroyEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopDestroyEvent.java index 0074fb5d..e94328aa 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopDestroyEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopDestroyEvent.java @@ -50,7 +50,11 @@ public PlayerShopDestroyEvent(Player p, Shop shop) { super(p); this.shop = shop; } - + + public static HandlerList getHandlerList() { + return handlers; + } + @Override public HandlerList getHandlers() { return handlers; diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopInventoryOpenEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopInventoryOpenEvent.java index edc90f9d..9ecaccef 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopInventoryOpenEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopInventoryOpenEvent.java @@ -58,7 +58,11 @@ public PlayerShopInventoryOpenEvent(Player p, Shop s, Action action, ItemStack i super(p, action, itm, chest, chestFace); this.shop = s; } - + + public static HandlerList getHandlerList() { + return handlers; + } + @Override public HandlerList getHandlers() { return handlers; diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopOpenEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopOpenEvent.java index 19fa9a5e..032ae3e4 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopOpenEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopOpenEvent.java @@ -50,7 +50,11 @@ public PlayerShopOpenEvent(Player buyer, Shop s) { super(buyer); this.shop = s; } - + + public static HandlerList getHandlerList() { + return handlers; + } + @Override public HandlerList getHandlers() { return handlers; diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/TradeShopReloadEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/TradeShopReloadEvent.java index 9d2ea57c..8e994004 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/TradeShopReloadEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/TradeShopReloadEvent.java @@ -39,13 +39,13 @@ public class TradeShopReloadEvent extends ServerEvent { private static final HandlerList handlers = new HandlerList(); + public TradeShop plugin; + public CommandSender sender; + public static HandlerList getHandlerList() { return handlers; } - public TradeShop plugin; - public CommandSender sender; - @Override public HandlerList getHandlers() { return handlers; From c3e9354b60d00f07c4026678085196466e50f617 Mon Sep 17 00:00:00 2001 From: Sparkling Comet Date: Mon, 4 Jul 2022 02:19:07 +0200 Subject: [PATCH 25/53] Add PlayerShopChangeEvent#getChange() --- .../framework/events/PlayerShopChangeEvent.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java index e885e286..49f38bea 100644 --- a/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java +++ b/src/main/java/org/shanerx/tradeshop/framework/events/PlayerShopChangeEvent.java @@ -42,6 +42,7 @@ public class PlayerShopChangeEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private final Shop shop; private ObjectHolder what; + private ShopChange change; private boolean cancelled; /** @@ -54,6 +55,8 @@ public class PlayerShopChangeEvent extends PlayerEvent implements Cancellable { public PlayerShopChangeEvent(Player player, Shop s, ShopChange change, ObjectHolder what) { super(player); this.shop = s; + this.what = what; + this.change = change; } public static HandlerList getHandlerList() { @@ -99,4 +102,13 @@ public void setCancelled(boolean cancelled) { public ObjectHolder getWhat() { return what; } + + /** + * Returns the {@link ShopChange} instance which wraps the object representing the data which is being changed. + * This is an enum type entry which represents which property or attribute was changed. + * @return the type of change. + */ + public ShopChange getChange() { + return change; + } } From c8ab1e6c2d7f4b4df2f91f7cd51c5ce30330e2b5 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Sun, 3 Jul 2022 17:24:40 -0700 Subject: [PATCH 26/53] Pom.xml and plugin.yml changes --- pom.xml | 1 + src/main/resources/plugin.yml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6a6930e6..9d1565e5 100644 --- a/pom.xml +++ b/pom.xml @@ -88,6 +88,7 @@ install ${project.artifactId}-${project.version}-${maven.build.timestamp} + src/main/java diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index e0ed8e79..743e6fef 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,4 +1,4 @@ -name: TradeShop +name: ${project.name} version: ${project.version} main: org.shanerx.tradeshop.TradeShop api-version: 1.14 From 0efd2cbadc72803e46865cdfa863bb5de37a0560 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 4 Jul 2022 14:33:18 -0700 Subject: [PATCH 27/53] Bug Fixes - Fix for Members displaying in shops and Member & Manager. - Fix for `/ts removeUser` not filling TabComplete for players. - Fix for double space in Message output between the Prefix and Message. --- .../tradeshop/commands/CommandTabCompleter.java | 3 ++- .../commands/commandrunners/AdminCommand.java | 2 +- .../org/shanerx/tradeshop/data/config/Message.java | 2 +- .../org/shanerx/tradeshop/data/config/Setting.java | 2 +- src/main/java/org/shanerx/tradeshop/shop/Shop.java | 13 +++++-------- 5 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCompleter.java b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCompleter.java index 88cbaee8..7e9e513f 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandTabCompleter.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandTabCompleter.java @@ -30,6 +30,7 @@ import org.bukkit.entity.Player; import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.data.config.Setting; +import org.shanerx.tradeshop.player.ShopRole; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shop.ShopType; import org.shanerx.tradeshop.utils.Utils; @@ -99,7 +100,7 @@ public List fillShopPlayer() { } Shop shop = Shop.loadShop(s); - return shop.getUserNames(); + return shop.getUserNames(ShopRole.MANAGER, ShopRole.MEMBER); } return Collections.EMPTY_LIST; diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java index c9c732fb..1d1f4314 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/AdminCommand.java @@ -66,7 +66,7 @@ public void reload() { return; } - command.sendMessage(Setting.MESSAGE_PREFIX.getString() + "&6The configuration files have been reloaded!"); + command.sendMessage(Setting.MESSAGE_PREFIX.getString().trim() + "&6The configuration files have been reloaded!"); Bukkit.getPluginManager().callEvent(new TradeShopReloadEvent(plugin, command.getSender())); } diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java index 83013b8e..44bbf55e 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -239,7 +239,7 @@ public String toString() { } public String getPrefixed() { - return PLUGIN.getMessageManager().colour(Setting.MESSAGE_PREFIX.getString() + " " + this); + return PLUGIN.getMessageManager().colour(Setting.MESSAGE_PREFIX.getString().trim() + " " + this); } diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 3b39c1c7..86a6086e 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -57,7 +57,7 @@ public enum Setting { UNLIMITED_ADMIN(SettingSection.SYSTEM_OPTIONS, "unlimited-admin", false), // Language Options - MESSAGE_PREFIX(SettingSection.LANGUAGE_OPTIONS, "message-prefix", "&a[&eTradeShop&a] "), + MESSAGE_PREFIX(SettingSection.LANGUAGE_OPTIONS, "message-prefix", "&a[&eTradeShop&a]"), SHOP_GOOD_COLOUR(SettingSection.LANGUAGE_OPTIONS, "shop-good-colour", "&2"), SHOP_INCOMPLETE_COLOUR(SettingSection.LANGUAGE_OPTIONS, "shop-incomplete-colour", "&7"), diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index bdc1c9e8..1d6150a0 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -831,21 +831,18 @@ public boolean addUser(UUID newUser, ShopRole role) { if (getUsers(ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt()) return false; - boolean ret = false; if (!getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(newUser)) { switch (role) { case MANAGER: - managers.add(newUser); - ret = true; + saveShop(managers.add(newUser)); + return true; case MEMBER: - members.add(newUser); - ret = true; + saveShop(members.add(newUser)); + return true; } } - saveShop(ret); - - return ret; + return false; } /** From 4fdb758bcd786460283d27011bca26a0e3ab670d Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 4 Jul 2022 15:57:43 -0700 Subject: [PATCH 28/53] Bug Fixes & POM Updates - Updated plugin versions in POM.xml - Fix for non DATA_ERROR debug output --- pom.xml | 6 +++--- .../shanerx/tradeshop/shop/listeners/ShopTradeListener.java | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 9d1565e5..6bce1282 100644 --- a/pom.xml +++ b/pom.xml @@ -111,7 +111,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.0 + 3.8.1 1.8 1.8 @@ -120,7 +120,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.1.0 + 3.3.0 false @@ -152,7 +152,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.3.1 + 3.4.0 false diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java index 00f6ab02..07f598bf 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopTradeListener.java @@ -160,7 +160,7 @@ public void onBlockInteract(PlayerInteractEvent e) { Tuple> canExchangeResult = canExchangeAll(shop, buyer.getInventory(), multiplier, e.getAction()); - PLUGIN.getDebugger().log("ExchangeResult " + canExchangeResult.getLeft(), DebugLevels.DATA_ERROR); + PLUGIN.getDebugger().log("ExchangeResult " + canExchangeResult.getLeft(), DebugLevels.TRADE); switch (canExchangeResult.getLeft()) { case SHOP_NO_PRODUCT: Message.SHOP_INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, canExchangeResult.getRight())); @@ -231,7 +231,7 @@ private Tuple, List> tradeAllItems(Shop shop, int mul if (costItems.get(0) == null) { ItemStack item = costItems.get(1); Message.INSUFFICIENT_ITEMS.sendItemMultiLineMessage(buyer, Collections.singletonMap(Variable.MISSING_ITEMS, costItems)); - PLUGIN.getDebugger().log("tradeAllItems", DebugLevels.DATA_ERROR); + PLUGIN.getDebugger().log("tradeAllItems", DebugLevels.TRADE); return new Tuple<>(productItems, costItems); } } else { From b72aa7989530029d2d911ad0380ca7fe05081e0d Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 4 Jul 2022 16:17:45 -0700 Subject: [PATCH 29/53] Bug Fixes & POM Updates - Moved inventoryGUI to a local directory instead of it's own to prevent potential conflicts - Fix for add Error during shop creation when adding users. --- pom.xml | 2 +- src/main/java/org/shanerx/tradeshop/shop/Shop.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 6bce1282..97415ce1 100644 --- a/pom.xml +++ b/pom.xml @@ -136,7 +136,7 @@ de.themoep - io.github.apfelcreme.Pipes.libs + org.shanerx.tradeshop.Pipes.libs diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 1d6150a0..fba5543e 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -97,8 +97,8 @@ public Shop(Tuple locations, ShopType shopType, ShopUser own this.shopType = shopType; - managers = players.getLeft() == null ? Collections.emptySet() : players.getLeft(); - members = players.getRight() == null ? Collections.emptySet() : players.getRight(); + managers = players.getLeft() == null ? new HashSet<>() : players.getLeft(); + members = players.getRight() == null ? new HashSet<>() : players.getRight(); product = new ArrayList<>(); cost = new ArrayList<>(); From af0f30fd39e6443c78a7fdb40f1a0b234ac6e0f2 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 4 Jul 2022 16:25:24 -0700 Subject: [PATCH 30/53] Additional Debug --- src/main/java/org/shanerx/tradeshop/utils/Utils.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index c9a3600c..27625025 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -506,9 +506,11 @@ public Shop createShop(Sign shopSign, Player creator, ShopType shopType, ItemSta PLUGIN.getDebugger().log(shop.toDebug(), DebugLevels.SHOP_CREATION); - PLUGIN.getDebugger().log("-----Post-Event-----", DebugLevels.SHOP_CREATION); PlayerShopCreateEvent shopCreateEvent = new PlayerShopCreateEvent(creator, shop); Bukkit.getPluginManager().callEvent(shopCreateEvent); + PLUGIN.getDebugger().log("-----Post-Event-----", DebugLevels.SHOP_CREATION); + PLUGIN.getDebugger().log(shop.toDebug(), DebugLevels.SHOP_CREATION); + if (shopCreateEvent.isCancelled()) { PLUGIN.getDebugger().log("Creation Failed!", DebugLevels.SHOP_CREATION); return null; From 53c16916e39f3d408151919344dff3fd8af90565 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Mon, 4 Jul 2022 16:45:52 -0700 Subject: [PATCH 31/53] Bug Fix & Command Improvement - RemoveSide commands now default to the only item if no index was specified and the shop only has one item on the side - Fix for members showing up as managers in the edit menu - Fix for managers not showing in edit menu --- .../org/shanerx/tradeshop/commands/Commands.java | 4 ++-- .../commands/commandrunners/ShopItemCommand.java | 4 +++- src/main/java/org/shanerx/tradeshop/shop/Shop.java | 12 +++++++----- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/Commands.java b/src/main/java/org/shanerx/tradeshop/commands/Commands.java index 1ba23831..67b78cb5 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/Commands.java +++ b/src/main/java/org/shanerx/tradeshop/commands/Commands.java @@ -63,8 +63,8 @@ public enum Commands { ADD_COST(Lists.newArrayList("addCost"), Permissions.NONE, 1, 3, true, "Add cost to shop", "/tradeshop $cmd$ [Amount] [Material]"), SET_PRODUCT(Lists.newArrayList("setProduct"), Permissions.NONE, 1, 3, true, "Set product of shop ", "/tradeshop $cmd$ [Amount] [Material]"), SET_COST(Lists.newArrayList("setCost"), Permissions.NONE, 1, 3, true, "Set cost of shop", "/tradeshop $cmd$ [Amount] [Material]"), - REMOVE_PRODUCT(Lists.newArrayList("removeProduct", "delProduct"), Permissions.NONE, 2, 2, true, "Removes a product from the shop", "/tradeshop $cmd$ "), - REMOVE_COST(Lists.newArrayList("removeCost", "delCost"), Permissions.NONE, 2, 2, true, "Removes a product from the shop", "/tradeshop $cmd$ "), + REMOVE_PRODUCT(Lists.newArrayList("removeProduct", "delProduct"), Permissions.NONE, 1, 2, true, "Removes a product from the shop", "/tradeshop $cmd$ "), + REMOVE_COST(Lists.newArrayList("removeCost", "delCost"), Permissions.NONE, 1, 2, true, "Removes a product from the shop", "/tradeshop $cmd$ "), LIST_PRODUCT(Lists.newArrayList("listProduct"), Permissions.NONE, 1, 1, true, "Lists the products in the shop", "/tradeshop $cmd$"), LIST_COST(Lists.newArrayList("listCost"), Permissions.NONE, 1, 1, true, "Lists the costs in a shop", "/tradeshop $cmd$"), diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java index 7281bfd7..c72933af 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopItemCommand.java @@ -81,10 +81,12 @@ public void removeSide() { if (shop == null) return; - int index = 0; + int index; if (isInt(command.getArgAt(1))) { index = Integer.parseInt(command.getArgAt(1)) - 1; + } else if (shop.getSideList(side).size() == 1) { + index = 0; } else { Message.INVALID_ARGUMENTS.sendMessage(pSender); return; diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index fba5543e..e25f10dc 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -725,14 +725,16 @@ public List getUsersExcluding(List excludedPlayers, ShopRole... switch (role) { case MEMBER: members.forEach(uuid -> { - if (!excludedPlayers.contains(uuid)) - users.add(new ShopUser(uuid, ShopRole.MEMBER)); + if (excludedPlayers.contains(uuid)) { + users.add(new ShopUser(uuid, role)); + } }); break; case MANAGER: - members.forEach(uuid -> { - if (!excludedPlayers.contains(uuid)) - users.add(new ShopUser(uuid, ShopRole.MANAGER)); + managers.forEach(uuid -> { + if (excludedPlayers.contains(uuid)) { + users.add(new ShopUser(uuid, role)); + } }); break; case OWNER: From dd87cdac11a4d2816c61190db3757dc4d4ef7875 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Tue, 5 Jul 2022 14:51:06 -0700 Subject: [PATCH 32/53] Bug Fix --- src/main/java/org/shanerx/tradeshop/shop/Shop.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index e25f10dc..556613a7 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -725,14 +725,14 @@ public List getUsersExcluding(List excludedPlayers, ShopRole... switch (role) { case MEMBER: members.forEach(uuid -> { - if (excludedPlayers.contains(uuid)) { + if (!excludedPlayers.contains(uuid)) { users.add(new ShopUser(uuid, role)); } }); break; case MANAGER: managers.forEach(uuid -> { - if (excludedPlayers.contains(uuid)) { + if (!excludedPlayers.contains(uuid)) { users.add(new ShopUser(uuid, role)); } }); From bad3fc6112c0af8a7a1f8626f2467fe892b1a64b Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 8 Jul 2022 20:46:34 -0700 Subject: [PATCH 33/53] Small reformat of lang file --- .../tradeshop/data/config/Language.java | 40 +- .../tradeshop/data/config/Message.java | 14 +- .../tradeshop/data/config/MessageSection.java | 6 +- .../tradeshop/data/config/Setting.java | 4 +- .../tradeshop/data/config/SettingSection.java | 6 +- .../shanerx/tradeshop/player/Permissions.java | 2 +- src/main/resources/Lang/en-us.yml | 638 +++++++++--------- 7 files changed, 362 insertions(+), 348 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Language.java b/src/main/java/org/shanerx/tradeshop/data/config/Language.java index de4f3c72..c92ad819 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Language.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Language.java @@ -105,29 +105,29 @@ public String getLang() { return lang; } - public String getHeader(LangSection section, String path) { - return getString(section, path, "header"); + public String getHeader(LangSection section, LangSubSection subSection, String path) { + return getString(section, subSection, path, "header"); } - public String getDefault(LangSection section, String path) { - return getStringOrDefault(section, path, "default"); + public String getDefault(LangSection section, LangSubSection subSection, String path) { + return getStringOrDefault(section, subSection, path, "default"); } - public String getPreComment(LangSection section, String path) { - return getString(section, path, "pre-comment"); + public String getPreComment(LangSection section, LangSubSection subSection, String path) { + return getString(section, subSection, path, "pre-comment"); } - public String getPostComment(LangSection section, String path) { - return getString(section, path, "post-comment"); + public String getPostComment(LangSection section, LangSubSection subSection, String path) { + return getString(section, subSection, path, "post-comment"); } - public String getString(LangSection section, String key, String field) { - String fullPath = section + "." + key + "." + field; + public String getString(LangSection section, LangSubSection subSection, String key, String field) { + String fullPath = section + "." + subSection + "." + key + "." + field; return langYAML.getString(fullPath, ""); } - public String getStringOrDefault(LangSection section, String key, String field) { - String fullPath = section + "." + key + "." + field, value = getString(section, key, field); + public String getStringOrDefault(LangSection section, LangSubSection subSection, String key, String field) { + String fullPath = section + "." + subSection + "." + key + "." + field, value = getString(section, subSection, key, field); return value != null ? value : getDefaultLangValue(fullPath).toString(); } @@ -137,9 +137,7 @@ public boolean isLoaded() { public enum LangSection { - MESSAGE_SECTION, MESSAGE, - SETTING_SECTION, SETTING, PERMISSION; @@ -152,4 +150,18 @@ public String toString() { } } + + public enum LangSubSection { + VALUES, + SECTIONS; + + LangSubSection() { + } + + @Override + public String toString() { + return name().toLowerCase().replace("_", "-"); + } + } + } diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Message.java b/src/main/java/org/shanerx/tradeshop/data/config/Message.java index 44bbf55e..82f46992 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Message.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Message.java @@ -126,7 +126,7 @@ static boolean upgrade() { //Changes if CONFIG_VERSION is below 1.1, then update to 1.1 if (checkVersion(version, 1.1)) { if (TOO_MANY_ITEMS.getString().equals("&cThis trade can not take any more %side%!")) { - TOO_MANY_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, TOO_MANY_ITEMS.getPath())); + TOO_MANY_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.SETTING, Language.LangSubSection.VALUES, TOO_MANY_ITEMS.getPath())); hasUpgraded.add(true); } version = 1.1; @@ -149,15 +149,15 @@ static boolean upgrade() { //Changes if CONFIG_VERSION is below 1.3, then update to 1.3 if (checkVersion(version, 1.3)) { if (INSUFFICIENT_ITEMS.getString().equals("&cYou do not have &e%AMOUNT% %ITEM%&c!")) { - INSUFFICIENT_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, INSUFFICIENT_ITEMS.getPath())); + INSUFFICIENT_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, Language.LangSubSection.VALUES, INSUFFICIENT_ITEMS.getPath())); hasUpgraded.add(true); } if (SHOP_INSUFFICIENT_ITEMS.getString().equals("&cThis shop does not have enough &e%AMOUNT% %ITEM%&c to trade!")) { - SHOP_INSUFFICIENT_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, SHOP_INSUFFICIENT_ITEMS.getPath())); + SHOP_INSUFFICIENT_ITEMS.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, Language.LangSubSection.VALUES, SHOP_INSUFFICIENT_ITEMS.getPath())); hasUpgraded.add(true); } if (ON_TRADE.getString().equals("&aYou have traded your &e%AMOUNT2% %ITEM2% &afor &e%AMOUNT1% %ITEM1% &awith %SELLER%")) { - ON_TRADE.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, ON_TRADE.getPath())); + ON_TRADE.setValue(PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, Language.LangSubSection.VALUES, ON_TRADE.getPath())); hasUpgraded.add(true); } @@ -183,15 +183,15 @@ public String getKey() { } public Object getDefaultValue() { - return PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, path); + return PLUGIN.getLanguage().getDefault(Language.LangSection.MESSAGE, Language.LangSubSection.VALUES, path); } public String getPostComment() { - return PLUGIN.getLanguage().getPostComment(Language.LangSection.MESSAGE, path); + return PLUGIN.getLanguage().getPostComment(Language.LangSection.MESSAGE, Language.LangSubSection.VALUES, path); } public String getPreComment() { - return PLUGIN.getLanguage().getPreComment(Language.LangSection.MESSAGE, path); + return PLUGIN.getLanguage().getPreComment(Language.LangSection.MESSAGE, Language.LangSubSection.VALUES, path); } public MessageSection getSection() { diff --git a/src/main/java/org/shanerx/tradeshop/data/config/MessageSection.java b/src/main/java/org/shanerx/tradeshop/data/config/MessageSection.java index 922017f8..e4b36fd1 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/MessageSection.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/MessageSection.java @@ -77,15 +77,15 @@ public boolean hasParent() { } public String getPostComment() { - return PLUGIN.getLanguage().getPostComment(Language.LangSection.MESSAGE_SECTION, name().toLowerCase().replace("_", "-")); + return PLUGIN.getLanguage().getPostComment(Language.LangSection.MESSAGE, Language.LangSubSection.SECTIONS, name().toLowerCase().replace("_", "-")); } public String getPreComment() { - return PLUGIN.getLanguage().getPreComment(Language.LangSection.MESSAGE_SECTION, name().toLowerCase().replace("_", "-")); + return PLUGIN.getLanguage().getPreComment(Language.LangSection.MESSAGE, Language.LangSubSection.SECTIONS, name().toLowerCase().replace("_", "-")); } public String getSectionHeader() { - return PLUGIN.getLanguage().getHeader(Language.LangSection.MESSAGE_SECTION, name().toLowerCase().replace("_", "-")); + return PLUGIN.getLanguage().getHeader(Language.LangSection.MESSAGE, Language.LangSubSection.SECTIONS, name().toLowerCase().replace("_", "-")); } public String getFileString() { diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 86a6086e..29b30459 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -291,11 +291,11 @@ public Object getMappedObject(String subKey) { } public String getPostComment() { - return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING, path); + return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING, Language.LangSubSection.VALUES, path); } public String getPreComment() { - return PLUGIN.getLanguage().getPreComment(Language.LangSection.SETTING, path); + return PLUGIN.getLanguage().getPreComment(Language.LangSection.SETTING, Language.LangSubSection.VALUES, path); } public SettingSection getSection() { diff --git a/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java index 43014fc8..15a2ef44 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/SettingSection.java @@ -95,15 +95,15 @@ public boolean hasParent() { } public String getPostComment() { - return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING_SECTION, key); + return PLUGIN.getLanguage().getPostComment(Language.LangSection.SETTING, Language.LangSubSection.SECTIONS, key); } public String getPreComment() { - return PLUGIN.getLanguage().getPreComment(Language.LangSection.SETTING_SECTION, key); + return PLUGIN.getLanguage().getPreComment(Language.LangSection.SETTING, Language.LangSubSection.SECTIONS, key); } public String getSectionHeader() { - return PLUGIN.getLanguage().getHeader(Language.LangSection.SETTING_SECTION, key); + return PLUGIN.getLanguage().getHeader(Language.LangSection.SETTING, Language.LangSubSection.SECTIONS, key); } public String getFileString() { diff --git a/src/main/java/org/shanerx/tradeshop/player/Permissions.java b/src/main/java/org/shanerx/tradeshop/player/Permissions.java index 15311b18..49519289 100644 --- a/src/main/java/org/shanerx/tradeshop/player/Permissions.java +++ b/src/main/java/org/shanerx/tradeshop/player/Permissions.java @@ -65,7 +65,7 @@ public enum Permissions { Permissions(String key, PermissionDefault defaultState) { this.key = key; this.defaultState = defaultState; - this.description = utils.PLUGIN.getLanguage().getString(Language.LangSection.PERMISSION, name().toLowerCase().replace("_", "-"), "description"); + this.description = utils.PLUGIN.getLanguage().getString(Language.LangSection.PERMISSION, Language.LangSubSection.VALUES, name().toLowerCase().replace("_", "-"), "description"); } @Override diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 8308fc1b..968c8dcc 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -1,328 +1,330 @@ -message-section: - none: - header: "" - unused: - header: "" -setting-section: - none: - header: "" - system-options: - header: "System Options" - language-options: - header: "Language Options" - global-options: - header: "Global Options" - global-multi-trade: - header: "" - shop-options: - header: "Shop Options" - shop-per-item-options: - header: "Shop Per Item Options" - shop-sign-options: - header: "Shop Sign Options" - trade-shop-options: - header: "Trade Shop Options" - itrade-shop-options: - header: "ITrade Shop Options" - bitrade-shop-options: - header: "BiTrade Shop Options" - illegal-item-options: - header: "Illegal Item Options" - pre-comment: "" - post-comment: "Valid Types: DISABLED, BLACKLIST, WHITELIST\n" - global-illegal-items: - header: "" - pre-comment: "List for illegal items for both Cost and Product" - post-comment: "" - cost-illegal-items: - header: "" - pre-comment: "List for illegal items for only Cost items" - post-comment: "" - product-illegal-items: - header: "" - pre-comment: "List for illegal items for only Product items" - post-comment: "" setting: - config-version: - pre-comment: "" - post-comment: "\n" - system-options: - data-storage-type: - pre-comment: "How would you like your servers data stored? (FLATFILE)" - enable-debug: - pre-comment: "What debug code should be run. This will add significant amounts of spam to the console/log, generally not used unless requested by Devs" - check-updates: - pre-comment: "Should we check for updates when the server starts" - allow-metrics: - pre-comment: "Allow us to connect anonymous metrics so we can see how our plugin is being used to better develop it" - unlimited-admin: - pre-comment: "We do not recommend enabling this setting since any editing an admin should need to do can be done without this.\n Should players with Admin permission be able to use any commands on any shops?" - language-options: - message-prefix: - pre-comment: "The prefix the displays before all plugin messages" - post-comment: "\n" - shop-good-colour: - pre-comment: "Header Colours, if the codes are showing in the header, set to \"\"\n Color for successfully created and stocked signs" - shop-incomplete-colour: - pre-comment: "Color for shops that are missing data to make trades" - shop-bad-colour: - pre-comment: "Color for shops that were not successfully created" - post-comment: "\n" - shop-open-status: - pre-comment: "Status Text, What will be shown in the bottom line of shop sign for each status\n Open" - shop-closed-status: - pre-comment: "Closed" - shop-incomplete-status: - pre-comment: "Incomplete" - shop-outofstock-status: - pre-comment: "Out of Stock" - post-comment: "\n" - global-options: - allowed-directions: - pre-comment: "Directions an allowed shop can be from a sign. Allowed directions are:\n Up, Down, North, East, South, West" - allowed-shops: - pre-comment: "Inventories to allow for shops. Allowed blocks are:\n Chest, Trapped_Chest, Dropper, Hopper, Dispenser, Shulker, ..." - max-edit-distance: - pre-comment: "Max distance a player can be from a shop to edit it" - allow-toggle-status: - pre-comment: "Can players toggle view of involved shops?" - allow-sign-break: - pre-comment: "Should we allow anyone to destroy a shops sign?" - allow-chest-break: - pre-comment: "Should we allow anyone to destroy a shops storage?" - post-comment: "\n" - multi-trade: - enable: - pre-comment: "Should we allow multi trades with shift + click (true/false)" - default-multi: - pre-comment: "Default multiplier for trades using shift + click" - max-multi: - pre-comment: "Maximum amount a player can set their multiplier to. Not recommended to set any higher than 6 as this can cause bugs with iTrade Shops" - post-comment: "\n" - illegal-item-options: + sections: + none: + header: "" + system-options: + header: "System Options" + language-options: + header: "Language Options" + global-options: + header: "Global Options" + global-multi-trade: + header: "" + shop-options: + header: "Shop Options" + shop-per-item-options: + header: "Shop Per Item Options" + shop-sign-options: + header: "Shop Sign Options" + trade-shop-options: + header: "Trade Shop Options" + itrade-shop-options: + header: "ITrade Shop Options" + bitrade-shop-options: + header: "BiTrade Shop Options" + illegal-item-options: + header: "Illegal Item Options" + pre-comment: "" + post-comment: "Valid Types: DISABLED, BLACKLIST, WHITELIST\n" global-illegal-items: - type: - pre-comment: "" - list: - pre-comment: "" + header: "" + pre-comment: "List for illegal items for both Cost and Product" + post-comment: "" cost-illegal-items: - type: - pre-comment: "" - list: - pre-comment: "" + header: "" + pre-comment: "List for illegal items for only Cost items" + post-comment: "" product-illegal-items: - type: - pre-comment: "" - list: - pre-comment: "" - shop-options: - max-shop-users: - pre-comment: "Maximum users(Managers/Members) a shop can have" - max-shops-per-chunk: - pre-comment: "Maximum shops that can exist in a single chunk" - max-items-per-trade-side: - pre-comment: "Maximum amount of item stacks per side of trade" - allow-user-purchasing: - pre-comment: "Can players purchase from a shop in which they are a user of (true/false)" - multiple-items-on-sign: - pre-comment: "Text that shows on trade signs that contain more than 1 item\n Available variables are: %AMOUNT%" - no-cost-text: - pre-comment: "What text should be used for successful trades when no cost is present" - no-cost-amount: - pre-comment: "What amount should be used for successful trades when no cost is present(must be greater than 0)" + header: "" + pre-comment: "List for illegal items for only Product items" + post-comment: "" + values: + config-version: + pre-comment: "" post-comment: "\n" - shop-per-item-options: - shop-per-item-settings: + system-options: + data-storage-type: + pre-comment: "How would you like your servers data stored? (FLATFILE, SQLITE)" + enable-debug: + pre-comment: "What debug code should be run. This will add significant amounts of spam to the console/log, generally not used unless requested by Devs" + check-updates: + pre-comment: "Should we check for updates when the server starts" + allow-metrics: + pre-comment: "Allow us to connect anonymous metrics so we can see how our plugin is being used to better develop it" + unlimited-admin: + pre-comment: "We do not recommend enabling this setting since any editing an admin should need to do can be done without this.\n Should players with Admin permission be able to use any commands on any shops?" + language-options: + message-prefix: + pre-comment: "The prefix the displays before all plugin messages" + post-comment: "\n" + shop-good-colour: + pre-comment: "Header Colours, if the codes are showing in the header, set to \"\"\n Color for successfully created and stocked signs" + shop-incomplete-colour: + pre-comment: "Color for shops that are missing data to make trades" + shop-bad-colour: + pre-comment: "Color for shops that were not successfully created" + post-comment: "\n" + shop-open-status: + pre-comment: "Status Text, What will be shown in the bottom line of shop sign for each status\n Open" + shop-closed-status: + pre-comment: "Closed" + shop-incomplete-status: + pre-comment: "Incomplete" + shop-outofstock-status: + pre-comment: "Out of Stock" + post-comment: "\n" + global-options: + allowed-directions: + pre-comment: "Directions an allowed shop can be from a sign. Allowed directions are:\n Up, Down, North, East, South, West" + allowed-shops: + pre-comment: "Inventories to allow for shops. Allowed blocks are:\n Chest, Trapped_Chest, Dropper, Hopper, Dispenser, Shulker, ..." + max-edit-distance: + pre-comment: "Max distance a player can be from a shop to edit it" + allow-toggle-status: + pre-comment: "Can players toggle view of involved shops?" + allow-sign-break: + pre-comment: "Should we allow anyone to destroy a shops sign?" + allow-chest-break: + pre-comment: "Should we allow anyone to destroy a shops storage?" + post-comment: "\n" + multi-trade: + enable: + pre-comment: "Should we allow multi trades with shift + click (true/false)" + default-multi: + pre-comment: "Default multiplier for trades using shift + click" + max-multi: + pre-comment: "Maximum amount a player can set their multiplier to. Not recommended to set any higher than 6 as this can cause bugs with iTrade Shops" + post-comment: "\n" + illegal-item-options: + global-illegal-items: + type: + pre-comment: "" + list: + pre-comment: "" + cost-illegal-items: + type: + pre-comment: "" + list: + pre-comment: "" + product-illegal-items: + type: + pre-comment: "" + list: + pre-comment: "" + shop-options: + max-shop-users: + pre-comment: "Maximum users(Managers/Members) a shop can have" + max-shops-per-chunk: + pre-comment: "Maximum shops that can exist in a single chunk" + max-items-per-trade-side: + pre-comment: "Maximum amount of item stacks per side of trade" + allow-user-purchasing: + pre-comment: "Can players purchase from a shop in which they are a user of (true/false)" + multiple-items-on-sign: + pre-comment: "Text that shows on trade signs that contain more than 1 item\n Available variables are: %AMOUNT%" + no-cost-text: + pre-comment: "What text should be used for successful trades when no cost is present" + no-cost-amount: + pre-comment: "What amount should be used for successful trades when no cost is present(must be greater than 0)" + post-comment: "\n" + shop-per-item-options: + shop-per-item-settings: + post-comment: "\n" + shop-sign-options: + sign-default-colours: + pre-comment: "What colour should be used for line 2/3 on shop signs per each material type." + post-comment: "\n" + trade-shop-options: + header: + pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" + allow-explode: + pre-comment: "Can explosions damage the shop sign/storage (true/false)" + allow-hopper-export: + pre-comment: "Can hoppers pull items from the shop storage (true/false)" + allow-hopper-import: + pre-comment: "Can hoppers push items into the shop storage (true/false)" + post-comment: "\n" + itrade-shop-options: + owner: + pre-comment: "Name to put on the bottom of iTrade signs" + header: + pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" + allow-explode: + pre-comment: "Can explosions damage the shop sign (true/false)" + bitrade-shop-options: + header: + pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" + allow-explode: + pre-comment: "Can explosions damage the shop sign/storage (true/false)" + allow-hopper-export: + pre-comment: "Can hoppers pull items from the shop storage (true/false)" + allow-hopper-import: + pre-comment: "Can hoppers push items into the shop storage (true/false)" post-comment: "\n" - shop-sign-options: - sign-default-colours: - pre-comment: "What colour should be used for line 2/3 on shop signs per each material type." - post-comment: "\n" - trade-shop-options: - header: - pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" - allow-explode: - pre-comment: "Can explosions damage the shop sign/storage (true/false)" - allow-hopper-export: - pre-comment: "Can hoppers pull items from the shop storage (true/false)" - allow-hopper-import: - pre-comment: "Can hoppers push items into the shop storage (true/false)" - post-comment: "\n" - itrade-shop-options: - owner: - pre-comment: "Name to put on the bottom of iTrade signs" - header: - pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" - allow-explode: - pre-comment: "Can explosions damage the shop sign (true/false)" - bitrade-shop-options: - header: - pre-comment: "The header that appears at the top of the shop signs, this is also what the player types to create the sign" - allow-explode: - pre-comment: "Can explosions damage the shop sign/storage (true/false)" - allow-hopper-export: - pre-comment: "Can hoppers pull items from the shop storage (true/false)" - allow-hopper-import: - pre-comment: "Can hoppers push items into the shop storage (true/false)" - post-comment: "\n" message: - message-version: - default: 0.0 - pre-comment: "Version of the current config file.\n Do not change!" - language: - default: "en-us" - pre-comment: "This currently does not change anything in the message files, but is used in metrics so that we can see what languages we should try to provide built in support for in the future.\n Please use codes as listed at: https://www.andiamo.co.uk/resources/iso-language-codes/" - post-comment: "\n" - change-closed: - default: "&cThe shop is now &l&bCLOSED&r&a." - change-open: - default: "&aThe shop is now &l&bOPEN&r&a." - empty-ts-on-setup: - default: "&cTradeShop empty, please remember to fill it!" - pre-comment: "Text to display when a player places a TradeSign above an empty chest:" - existing-shop: - default: "&cThis storage or sign is already linked to a shop." - feature-disabled: - default: "&cThis feature has been disabled on this server!" - held-empty: - default: "&eYou are currently holding nothing." - pre-comment: "Text to display when the player is not holding anything" - illegal-item: - default: "&cYou cannot use one or more of those items in shops." - pre-comment: "Text to display when a shop failed creation due to an illegal item" - no-shulker-item: - default: "&cYou cannot add a Shulker Box when the shop uses it for storage." - pre-comment: "Text to display when a shop failed creation due to using a shulker box when the shop uses it for storage: " - insufficient-items: - default: "&cYou are missing the below items for the trade! \n{%MISSINGITEMS%= &e%AMOUNT% %ITEM%}" - pre-comment: "Text to display when the player does not have enough items:" - shop-insufficient-items: - default: "&cThis shop is missing the below items for the trade! \n{%MISSINGITEMS%= &e%AMOUNT% %ITEM%}" - pre-comment: "Text to display when the shop does not have enough items:" - invalid-arguments: - default: "&eTry &6/tradeshop help &eto display help!" - pre-comment: "Text to display when invalid arguments are submitted through the \"/tradeshop\" command:" - item-added: - default: "&aItem successfully added to shop." - item-not-removed: - default: "&cItem could not be removed from shop." - item-removed: - default: "&aItem successfully removed to shop." - missing-chest: - default: "&cYour shop is missing a chest." - missing-item: - default: "&cYour sign is missing an item for trade." - pre-comment: "Text to display when a shop sign failed creation due to missing an item" - multi-amount: - default: "&aYour trade multiplier is %AMOUNT%." - multi-update: - default: "&aTrade multiplier has been updated to %AMOUNT%." - no-chest: - default: "&cYou need to put a chest under the sign!" - pre-comment: "Text to display when a player attempts to place a sign without placing the chest first:" - no-command-permission: - default: "&cYou do not have permission to execute this command" - pre-comment: "Text to display when a player attempts to run administrator commands:" - no-shop-permission: - default: "&cYou do not have permission to edit that shop." - no-trade-permission: - default: "&cYou do not have permission to trade with TradeShops" - pre-comment: "Text to display when a player attempts to trade while not having the `Trade` permission:" - no-sighted-shop: - default: "&cNo shop in range!" - pre-comment: "Text to display when a player is too far from a shop" - no-ts-create-permission: - default: "&cYou don't have permission to create this type of TradeShop!" - pre-comment: "Text to display when a player attempts to setup a shoptype they are not allowed to create:" - no-ts-destroy: - default: "&cYou may not destroy that TradeShop" - pre-comment: "Text to display when a player attempts to destroy a shop they do not own:" - destroy-shop-sign-first: - default: "&cYou must destroy the shops sign first." - pre-comment: "Text to display when a player attempts to destroy a block with a shop sign attached to it:" - no-ts-open: - default: "&cThat TradeShop does not belong to you" - pre-comment: "Text to display when a player attempts to open a shop they do not own nor have been granted access to:" - on-trade: - default: "&aYou have traded with %SELLER% receiving: \n{%RECEIVEDLINES%= &e%AMOUNT% %ITEM%} \n&aIn exchange for: \n{%GIVENLINES%= &e%AMOUNT% %ITEM%}" - pre-comment: "Text to display upon a successful trade:" - player-full: - default: "&cYour inventory is full, please make room before trading items!" - pre-comment: "Text to display when the players inventory is too full to recieve the trade:" - player-not-found: - default: "&cThat player could not be found." - player-only-command: - default: "&eThis command is only available to players." - pre-comment: "Text to display when console tries to use a player only command" - plugin-behind: - default: "&cThe server is running an old version of TradeShop, please update the plugin." - self-owned: - default: "&cYou cannot buy from a shop in which you are a user." - pre-comment: "Text to display when a player tries to buy form a shop in which they are a user" - setup-help: - default: "\n&2Setting up a TradeShop is easy! Just make sure to follow these steps:\n \nStep 1: &ePlace down a chest.\n&2Step 2: &ePlace a sign on top of or around the chest.\n&2Step 3: &eWrite the following on the sign\n&6 [%HEADER%]\n&6&o-- Leave Blank --\n&6&o-- Leave Blank --\n&6&o-- Leave Blank --\n&2Step 4: &eUse the addCost and addProduct commands to add items to your shop" - pre-comment: "Text to display on \"/tradeshop setup\":" - shop-closed: - default: "&cThis shop is currently closed." - shop-empty: - default: "&cThis TradeShop is currently missing items to complete the trade!" - pre-comment: "Text to display when the shop does not have enough stock:" - shop-full: - default: "&cThis TradeShop is full, please contact the owner to get it emptied!" - pre-comment: "Text to display when the shop storage is full:" - shop-item-list: - default: "&aThe shops %TYPE%:\n%LIST%" - shop-type-switched: - default: "&aShop type has been switched to %NEWTYPE%." - pre-comment: "Text to display when a player uses '/ts toggle'\n Available variables are: %TYPE% %NEWTYPE%" - successful-setup: - default: "&aYou have successfully setup a TradeShop!" - pre-comment: "Text to display when a player successfully creates a TradeShop:" - too-many-chests: - default: "&cThere are too many shops in this chunk, you can not add another one." - too-many-items: - default: "&cThis shop cannot take any more %SIDE% items!" - updated-shop-users: - default: "&aShop users have tried to update for the below shops! \n{%UPDATEDSHOPS%= %SHOP% -|- %STATUS%}" - pre-comment: "Text to display when shop users have been updated." - updated-shop-users-successful: - default: "&aSuccessful" - pre-comment: "Text to display when shop users have been updated successfully." - updated-shop-users-failed: - default: "&cFailed" - pre-comment: "Text to display when shop users could not be added for an unknown reason." - updated-shop-users-failed-capacity: - default: "&cMax Capacity" - pre-comment: "Text to display when shop users could not be added due to the shop having max user capacity." - updated-shop-users-failed-existing: - default: "&ePlayer Exists" - pre-comment: "Text to display when shop users could not be added because they are already a user on the shop." - updated-shop-users-failed-missing: - default: "&ePlayer Missing" - pre-comment: "Text to display when shop users could not be removed because the user was not on the shop." - who-message: - default: "&6Shop users are:\n&2Owner: &e%OWNER%\n&2Managers: &e%MANAGERS%\n&2Members: &e%MEMBERS%" - pre-comment: "Text to display when players use the who command" - view-player-level: - default: "&e%PLAYER% has a level of %LEVEL%." - pre-comment: "Text to display when viewing a players level with /ts PlayerLevel" - set-player-level: - default: "&aYou have set the level of %PLAYER% to %LEVEL%!" - pre-comment: "Text to display after setting a players level" - various-item-type: - default: "Various" - pre-comment: "Text to display when a message uses an Item Type and the Type varies" - toggled-status: - default: "Toggled status: &c%STATUS%" - no-sign-found: - default: "&cNo sign in range!" - pre-comment: "Text to display when a player is too far from a sign" - admin-toggled: - default: "&aYour Admin mode is currently &e%STATE%&a." - pre-comment: "Text to display when an admin toggles or views their Admin abilities. \n# \"%STATE%\" will be replaced by the state that the player is in after the command." - failed-trade: - default: "&cThe Trade has failed for unknown reasons, please notify an Admin or submit a bug report using '/ts bug'!" - pre-comment: "Text to display when a player is too far from a sign" + sections: + none: + header: "" + unused: + header: "" + values: + message-version: + default: 0.0 + pre-comment: "Version of the current config file.\n Do not change!" + language: + default: "en-us" + pre-comment: "This currently does not change anything in the message files, but is used in metrics so that we can see what languages we should try to provide built in support for in the future.\n Please use codes as listed at: https://www.andiamo.co.uk/resources/iso-language-codes/" + post-comment: "\n" + change-closed: + default: "&cThe shop is now &l&bCLOSED&r&a." + change-open: + default: "&aThe shop is now &l&bOPEN&r&a." + empty-ts-on-setup: + default: "&cTradeShop empty, please remember to fill it!" + pre-comment: "Text to display when a player places a TradeSign above an empty chest:" + existing-shop: + default: "&cThis storage or sign is already linked to a shop." + feature-disabled: + default: "&cThis feature has been disabled on this server!" + held-empty: + default: "&eYou are currently holding nothing." + pre-comment: "Text to display when the player is not holding anything" + illegal-item: + default: "&cYou cannot use one or more of those items in shops." + pre-comment: "Text to display when a shop failed creation due to an illegal item" + no-shulker-item: + default: "&cYou cannot add a Shulker Box when the shop uses it for storage." + pre-comment: "Text to display when a shop failed creation due to using a shulker box when the shop uses it for storage: " + insufficient-items: + default: "&cYou are missing the below items for the trade! \n{%MISSINGITEMS%= &e%AMOUNT% %ITEM%}" + pre-comment: "Text to display when the player does not have enough items:" + shop-insufficient-items: + default: "&cThis shop is missing the below items for the trade! \n{%MISSINGITEMS%= &e%AMOUNT% %ITEM%}" + pre-comment: "Text to display when the shop does not have enough items:" + invalid-arguments: + default: "&eTry &6/tradeshop help &eto display help!" + pre-comment: "Text to display when invalid arguments are submitted through the \"/tradeshop\" command:" + item-added: + default: "&aItem successfully added to shop." + item-not-removed: + default: "&cItem could not be removed from shop." + item-removed: + default: "&aItem successfully removed to shop." + missing-chest: + default: "&cYour shop is missing a chest." + missing-item: + default: "&cYour sign is missing an item for trade." + pre-comment: "Text to display when a shop sign failed creation due to missing an item" + multi-amount: + default: "&aYour trade multiplier is %AMOUNT%." + multi-update: + default: "&aTrade multiplier has been updated to %AMOUNT%." + no-chest: + default: "&cYou need to put a chest under the sign!" + pre-comment: "Text to display when a player attempts to place a sign without placing the chest first:" + no-command-permission: + default: "&cYou do not have permission to execute this command" + pre-comment: "Text to display when a player attempts to run administrator commands:" + no-shop-permission: + default: "&cYou do not have permission to edit that shop." + no-trade-permission: + default: "&cYou do not have permission to trade with TradeShops" + pre-comment: "Text to display when a player attempts to trade while not having the `Trade` permission:" + no-sighted-shop: + default: "&cNo shop in range!" + pre-comment: "Text to display when a player is too far from a shop" + no-ts-create-permission: + default: "&cYou don't have permission to create this type of TradeShop!" + pre-comment: "Text to display when a player attempts to setup a shoptype they are not allowed to create:" + no-ts-destroy: + default: "&cYou may not destroy that TradeShop" + pre-comment: "Text to display when a player attempts to destroy a shop they do not own:" + destroy-shop-sign-first: + default: "&cYou must destroy the shops sign first." + pre-comment: "Text to display when a player attempts to destroy a block with a shop sign attached to it:" + no-ts-open: + default: "&cThat TradeShop does not belong to you" + pre-comment: "Text to display when a player attempts to open a shop they do not own nor have been granted access to:" + on-trade: + default: "&aYou have traded with %SELLER% receiving: \n{%RECEIVEDLINES%= &e%AMOUNT% %ITEM%} \n&aIn exchange for: \n{%GIVENLINES%= &e%AMOUNT% %ITEM%}" + pre-comment: "Text to display upon a successful trade:" + player-full: + default: "&cYour inventory is full, please make room before trading items!" + pre-comment: "Text to display when the players inventory is too full to recieve the trade:" + player-not-found: + default: "&cThat player could not be found." + player-only-command: + default: "&eThis command is only available to players." + pre-comment: "Text to display when console tries to use a player only command" + plugin-behind: + default: "&cThe server is running an old version of TradeShop, please update the plugin." + self-owned: + default: "&cYou cannot buy from a shop in which you are a user." + pre-comment: "Text to display when a player tries to buy form a shop in which they are a user" + setup-help: + default: "\n&2Setting up a TradeShop is easy! Just make sure to follow these steps:\n \nStep 1: &ePlace down a chest.\n&2Step 2: &ePlace a sign on top of or around the chest.\n&2Step 3: &eWrite the following on the sign\n&6 [%HEADER%]\n&6&o-- Leave Blank --\n&6&o-- Leave Blank --\n&6&o-- Leave Blank --\n&2Step 4: &eUse the addCost and addProduct commands to add items to your shop" + pre-comment: "Text to display on \"/tradeshop setup\":" + shop-closed: + default: "&cThis shop is currently closed." + shop-empty: + default: "&cThis TradeShop is currently missing items to complete the trade!" + pre-comment: "Text to display when the shop does not have enough stock:" + shop-full: + default: "&cThis TradeShop is full, please contact the owner to get it emptied!" + pre-comment: "Text to display when the shop storage is full:" + shop-item-list: + default: "&aThe shops %TYPE%:\n%LIST%" + shop-type-switched: + default: "&aShop type has been switched to %NEWTYPE%." + pre-comment: "Text to display when a player uses '/ts toggle'\n Available variables are: %TYPE% %NEWTYPE%" + successful-setup: + default: "&aYou have successfully setup a TradeShop!" + pre-comment: "Text to display when a player successfully creates a TradeShop:" + too-many-chests: + default: "&cThere are too many shops in this chunk, you can not add another one." + too-many-items: + default: "&cThis shop cannot take any more %SIDE% items!" + updated-shop-users: + default: "&aShop users have tried to update for the below shops! \n{%UPDATEDSHOPS%= %SHOP% -|- %STATUS%}" + pre-comment: "Text to display when shop users have been updated." + updated-shop-users-successful: + default: "&aSuccessful" + pre-comment: "Text to display when shop users have been updated successfully." + updated-shop-users-failed: + default: "&cFailed" + pre-comment: "Text to display when shop users could not be added for an unknown reason." + updated-shop-users-failed-capacity: + default: "&cMax Capacity" + pre-comment: "Text to display when shop users could not be added due to the shop having max user capacity." + updated-shop-users-failed-existing: + default: "&ePlayer Exists" + pre-comment: "Text to display when shop users could not be added because they are already a user on the shop." + updated-shop-users-failed-missing: + default: "&ePlayer Missing" + pre-comment: "Text to display when shop users could not be removed because the user was not on the shop." + who-message: + default: "&6Shop users are:\n&2Owner: &e%OWNER%\n&2Managers: &e%MANAGERS%\n&2Members: &e%MEMBERS%" + pre-comment: "Text to display when players use the who command" + view-player-level: + default: "&e%PLAYER% has a level of %LEVEL%." + pre-comment: "Text to display when viewing a players level with /ts PlayerLevel" + set-player-level: + default: "&aYou have set the level of %PLAYER% to %LEVEL%!" + pre-comment: "Text to display after setting a players level" + various-item-type: + default: "Various" + pre-comment: "Text to display when a message uses an Item Type and the Type varies" + toggled-status: + default: "Toggled status: &c%STATUS%" + no-sign-found: + default: "&cNo sign in range!" + pre-comment: "Text to display when a player is too far from a sign" + admin-toggled: + default: "&aYour Admin mode is currently &e%STATE%&a." + pre-comment: "Text to display when an admin toggles or views their Admin abilities. \n# \"%STATE%\" will be replaced by the state that the player is in after the command." + failed-trade: + default: "&cThe Trade has failed for unknown reasons, please notify an Admin or submit a bug report using '/ts bug'!" + pre-comment: "Text to display when a player is too far from a sign" permission: help: description: 'Allows players to view the help menu containing only commands they have permission to use.' From fa9eb1834a402e5a09f6d2b20a5c50bbd11a6422 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 3 Aug 2022 20:01:41 -0700 Subject: [PATCH 34/53] Implement Relative Directions for Chest checking - Minor Testing done seems Okay - Adds support for checking all 26 spots around a sign - Checks for Chests/Signs based on the direction for the block - Directions in the config should be formatted as `dir1+dir1+dir3` i.e `BACK` | `BACK+DOWN` | `LEFT+DOWN+BACK` - There is no limit to the amount of directions(other than not being able to repeat a direction) but only 3 are needed to check specif the surrounding 26 blocks --- .../tradeshop/data/config/Setting.java | 2 +- .../shanerx/tradeshop/utils/ListManager.java | 24 ++--- .../tradeshop/utils/MetricsManager.java | 4 +- .../org/shanerx/tradeshop/utils/Utils.java | 64 +++++++++---- .../relativedirection/LocationOffset.java | 62 +++++++++++++ .../relativedirection/RelativeCardinals.java | 75 +++++++++++++++ .../relativedirection/RelativeDirection.java | 92 +++++++++++++++++++ 7 files changed, 289 insertions(+), 34 deletions(-) create mode 100644 src/main/java/org/shanerx/tradeshop/utils/relativedirection/LocationOffset.java create mode 100644 src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeCardinals.java create mode 100644 src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeDirection.java diff --git a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java index 29b30459..7178328d 100644 --- a/src/main/java/org/shanerx/tradeshop/data/config/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/data/config/Setting.java @@ -69,7 +69,7 @@ public enum Setting { SHOP_OUTOFSTOCK_STATUS(SettingSection.LANGUAGE_OPTIONS, "shop-outofstock-status", "&c"), // Global Options - ALLOWED_DIRECTIONS(SettingSection.GLOBAL_OPTIONS, "allowed-directions", new String[]{"DOWN", "WEST", "SOUTH", "EAST", "NORTH", "UP"}), + CHEST_DIRECTIONS(SettingSection.GLOBAL_OPTIONS, "chest-directions", new String[]{"BACK", "DOWN", "LEFT", "RIGHT", "UP", "FRONT"}), ALLOWED_SHOPS(SettingSection.GLOBAL_OPTIONS, "allowed-shops", new String[]{"CHEST", "TRAPPED_CHEST", "SHULKER"}), MAX_EDIT_DISTANCE(SettingSection.GLOBAL_OPTIONS, "max-edit-distance", 4), ALLOW_TOGGLE_STATUS(SettingSection.GLOBAL_OPTIONS, "allow-toggle-status", true), diff --git a/src/main/java/org/shanerx/tradeshop/utils/ListManager.java b/src/main/java/org/shanerx/tradeshop/utils/ListManager.java index fe052930..f4706e29 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/ListManager.java +++ b/src/main/java/org/shanerx/tradeshop/utils/ListManager.java @@ -30,16 +30,15 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.item.IllegalItemList; import org.shanerx.tradeshop.item.NonObtainableMaterials; import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.shop.ShopStorage; import org.shanerx.tradeshop.utils.debug.DebugLevels; +import org.shanerx.tradeshop.utils.relativedirection.RelativeDirection; import java.util.ArrayList; -import java.util.Arrays; import java.util.concurrent.TimeUnit; @SuppressWarnings("unused") @@ -49,7 +48,7 @@ public class ListManager extends Utils { private final IllegalItemList costList = new IllegalItemList(IllegalItemList.ListType.DISABLED, new ArrayList<>()); private final IllegalItemList productList = new IllegalItemList(IllegalItemList.ListType.DISABLED, new ArrayList<>()); - private final ArrayList directions = new ArrayList<>(); + private final ArrayList directions = new ArrayList<>(); private final ArrayList inventories = new ArrayList<>(); private final ArrayList gameMats = new ArrayList<>(); private final ArrayList addOnMats = new ArrayList<>(); @@ -103,7 +102,7 @@ public void removeSkippableShop(Location location) { } - public ArrayList getDirections() { + public ArrayList getDirections() { return directions; } @@ -134,10 +133,6 @@ public boolean isIllegal(ShopItemSide side, Material mat) { return side.equals(ShopItemSide.COST) ? costList.isIllegal(mat) : productList.isIllegal(mat); } - public boolean isDirection(BlockFace face) { - return directions.contains(face); - } - public boolean isInventory(Block block) { //Get blocks Material and strip all non-alpha chars Material blockMaterial = block.getType(); @@ -228,22 +223,23 @@ private void setGameMatList() { } } - // Remove all non obtainable materials that we have found + // Remove all non-obtainable materials that we have found for (NonObtainableMaterials mat : NonObtainableMaterials.values()) { gameMats.remove(mat.toString()); } - //Adds any strings that have been added the the AddOnMats list to the autocomplete list + //Adds any strings that have been added the AddOnMats list to the autocomplete list gameMats.addAll(addOnMats); } private void updateDirections() { directions.clear(); - ArrayList allowed = new ArrayList<>(Arrays.asList(BlockFace.DOWN, BlockFace.WEST, BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.UP)); - for (String str : Setting.ALLOWED_DIRECTIONS.getStringList()) { - if (allowed.contains(BlockFace.valueOf(str))) - directions.add(BlockFace.valueOf(str)); + for (String str : Setting.CHEST_DIRECTIONS.getStringList()) { + try { + directions.add(RelativeDirection.valueOf(str)); + } catch (IllegalArgumentException | NullPointerException ignored) { + } } } diff --git a/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java b/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java index 630c8f69..04e73bfc 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java +++ b/src/main/java/org/shanerx/tradeshop/utils/MetricsManager.java @@ -175,7 +175,7 @@ public Map call() throws Exception { } private void addSettingStringListMetrics() { - List settingList = Arrays.asList(Setting.ALLOWED_DIRECTIONS, + List settingList = Arrays.asList(Setting.CHEST_DIRECTIONS, Setting.ALLOWED_SHOPS); for (Setting setting : settingList) { @@ -237,7 +237,7 @@ private void addFeaturePieMetrics() { } private void addSettingStringListAdvancedPieMetrics() { - List settingList = Arrays.asList(Setting.ALLOWED_DIRECTIONS, + List settingList = Arrays.asList(Setting.CHEST_DIRECTIONS, Setting.ALLOWED_SHOPS); for (Setting setting : settingList) { diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 27625025..3a8b5686 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -54,6 +54,8 @@ import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.debug.DebugLevels; import org.shanerx.tradeshop.utils.objects.Tuple; +import org.shanerx.tradeshop.utils.relativedirection.LocationOffset; +import org.shanerx.tradeshop.utils.relativedirection.RelativeDirection; import java.util.ArrayList; import java.util.Arrays; @@ -266,29 +268,51 @@ public String colorize(String msg) { * @return the sign. */ public Sign findShopSign(Block chest) { + //region Linked Sign Check - Load and Check Chest Linkage first, if it is a shop then return Linked Shop ShopLocation potentialLocation = PLUGIN.getDataStorage().getChestLinkage(new ShopLocation(chest.getLocation())); if (potentialLocation != null && ShopType.isShop(potentialLocation.getLocation().getBlock())) return (Sign) potentialLocation.getLocation().getBlock().getState(); + //endregion - ArrayList faces = PLUGIN.getListManager().getDirections(), - flatFaces = new ArrayList<>(Arrays.asList(BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST)); + // Directions to check for Sign(Reversed later as the list is built to check from Sign->Chest and this method checks from Chest->Sign) + ArrayList directions = PLUGIN.getListManager().getDirections(); + // Directions to check for other half of a DoubleChest + ArrayList flatFaces = new ArrayList<>(Arrays.asList(BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST)); - for (BlockFace face : faces) { - face = face.getOppositeFace(); // Check in the opposite direction that a sign would check - Block relative = chest.getRelative(face); + Block otherHalf = null; + + for (RelativeDirection direction : directions) { + // Translate Relative Direction and get the Block + LocationOffset relativeOffset = direction.getTranslatedDirection(RelativeDirection.getDirection(chest.getBlockData()).getOppositeFace()); + Block relative = chest.getRelative(relativeOffset.getXOffset(), relativeOffset.getYOffset(), relativeOffset.getZOffset()); + + // Check if it is a shop and return. Add the chest and shop to ChestLinkage, If it is a DoubleChest also add the other half if (ShopType.isShop(relative)) { + PLUGIN.getDataStorage().addChestLinkage(new ShopLocation(chest.getLocation()), new ShopLocation(relative.getLocation())); if (ShopChest.isDoubleChest(chest)) { PLUGIN.getDataStorage().addChestLinkage(new ShopLocation(ShopChest.getOtherHalfOfDoubleChest(chest).getLocation()), new ShopLocation(relative.getLocation())); } return (Sign) relative.getState(); - } else if (flatFaces.contains(face) && (chest.getType().equals(Material.CHEST) || chest.getType().equals(Material.TRAPPED_CHEST))) { + // If the relative block wasn't the ShopSign and we are checking a FlatFace, Then check if it is the other half of this Chest + } else if (flatFaces.stream().anyMatch((face) -> relativeOffset.getXOffset() == face.getModX() || + relativeOffset.getYOffset() == face.getModY() || + relativeOffset.getZOffset() == face.getModZ()) && (chest.getType().equals(Material.CHEST) || chest.getType().equals(Material.TRAPPED_CHEST))) { if (relative.getType().equals(chest.getType()) && ShopChest.isDoubleChest(chest)) { - for (BlockFace face2 : faces) { - Block relative2 = chest.getRelative(face).getRelative(face2.getOppositeFace()); - if (ShopType.isShop(relative2)) { - PLUGIN.getDataStorage().addChestLinkage(new ShopLocation(chest.getLocation()), new ShopLocation(relative2.getLocation())); - return (Sign) relative2.getState(); - } + // Set Aside for later, We want to check the relative directions on one chest at a time + otherHalf = relative; + } + } + } + + // Check the relative Directions for the other half of the chest + if (otherHalf != null) { + for (RelativeDirection direction2 : directions) { + LocationOffset relativeOffset2 = direction2.getTranslatedDirection(RelativeDirection.getDirection(otherHalf.getBlockData()).getOppositeFace()); + Block relative2 = chest.getRelative(relativeOffset2.getXOffset(), relativeOffset2.getYOffset(), relativeOffset2.getZOffset()); + if (ShopType.isShop(relative2)) { + if (ShopType.isShop(relative2)) { + PLUGIN.getDataStorage().addChestLinkage(new ShopLocation(chest.getLocation()), new ShopLocation(relative2.getLocation())); + return (Sign) relative2.getState(); } } } @@ -304,13 +328,19 @@ public Sign findShopSign(Block chest) { * @return the shop's inventory holder block. */ public Block findShopChest(Block sign) { - for (BlockFace face : PLUGIN.getListManager().getDirections()) { - Block relative = sign.getRelative(face); - if (PLUGIN.getListManager().isInventory(relative)) { - return relative; + // For each Relative Direction listed in the config in order + for (RelativeDirection direction : PLUGIN.getListManager().getDirections()) { + // Get the direction the block we want to check is Facing + BlockFace facing = RelativeDirection.getDirection(sign.getBlockData()); + // Translate the Relative Direction from the Direction the Block is Facing and get the Block on that BlockFace + LocationOffset relativeOffset = direction.getTranslatedDirection(facing); + Block relativeBlock = sign.getRelative(relativeOffset.getXOffset(), relativeOffset.getYOffset(), relativeOffset.getZOffset()); + + // Check if relativeBlock is an inventory block and return if true + if (PLUGIN.getListManager().isInventory(relativeBlock)) { + return relativeBlock; } } - return null; } diff --git a/src/main/java/org/shanerx/tradeshop/utils/relativedirection/LocationOffset.java b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/LocationOffset.java new file mode 100644 index 00000000..68f947f6 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/LocationOffset.java @@ -0,0 +1,62 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.utils.relativedirection; + +public class LocationOffset { + + private final int xOffset, yOffset, zOffset; + private final transient int max = 1, min = -1; + + public LocationOffset(int xOffset, int yOffset, int zOffset) { + this.xOffset = xOffset; + this.yOffset = yOffset; + this.zOffset = zOffset; + } + + public LocationOffset add(LocationOffset toAdd) { + return new LocationOffset(getXOffset() + toAdd.getXOffset(), getYOffset() + toAdd.getYOffset(), getZOffset() + toAdd.getZOffset()).normalize(); + } + + public LocationOffset normalize() { + return new LocationOffset(bringWithinRange(getXOffset()), bringWithinRange(getYOffset()), bringWithinRange(getZOffset())); + } + + private int bringWithinRange(int i) { + return Math.max(Math.min(i, max), min); + } + + public int getZOffset() { + return zOffset; + } + + public int getYOffset() { + return yOffset; + } + + public int getXOffset() { + return xOffset; + } +} diff --git a/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeCardinals.java b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeCardinals.java new file mode 100644 index 00000000..ea7de535 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeCardinals.java @@ -0,0 +1,75 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.utils.relativedirection; + +import org.bukkit.block.BlockFace; + +public enum RelativeCardinals { + + SELF("0", "0", "0"), + DOWN("0", "-1", "0"), + UP("0", "1", "0"), + RIGHT("z", "0", "-x"), + LEFT("-z", "0", "x"), + BACK("-x", "0", "-z"), + FRONT("x", "0", "z"); + + private final transient String xTranslation; + private final transient String yTranslation; + private final transient String zTranslation; + + RelativeCardinals(String xTranslation, String yTranslation, String zTranslation) { + this.xTranslation = xTranslation; + this.yTranslation = yTranslation; + this.zTranslation = zTranslation; + } + + public LocationOffset getTranslation(BlockFace facing) { + return new LocationOffset(processTranslation(xTranslation, facing), processTranslation(yTranslation, facing), processTranslation(zTranslation, facing)); + } + + private int processTranslation(String translation, BlockFace facing) { + int temp = 0; + + try { + temp = Integer.parseInt(translation); + return temp; + } catch (NumberFormatException ignored) { + } + + if (translation.toLowerCase().contains("x")) + temp = facing.getModX(); + else if (translation.toLowerCase().contains("y")) + temp = facing.getModY(); + else if (translation.toLowerCase().contains("z")) + temp = facing.getModZ(); + + if (translation.contains("-")) + return Math.negateExact(temp); + + return temp; + } +} diff --git a/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeDirection.java b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeDirection.java new file mode 100644 index 00000000..a1ef0a72 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeDirection.java @@ -0,0 +1,92 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.utils.relativedirection; + +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.Directional; +import org.bukkit.block.data.Rotatable; + +import java.util.ArrayList; +import java.util.List; + +public class RelativeDirection { + + private final List cardinals = new ArrayList<>(); + + public RelativeDirection(RelativeCardinals... cardinals) { + for (RelativeCardinals cardinal : cardinals) { + if (cardinal == null) + cardinal = RelativeCardinals.SELF; + + if (!this.cardinals.contains(cardinal)) { + this.cardinals.add(cardinal); + } + } + } + + public static RelativeDirection valueOf(String str) { + String[] cardinals = str.split("[+]"); + + if (cardinals.length == 0) return new RelativeDirection(RelativeCardinals.SELF); + + RelativeCardinals[] processedCardinals = new RelativeCardinals[cardinals.length]; + + for (int i = 0; i < cardinals.length; i++) { + processedCardinals[i] = RelativeCardinals.valueOf(cardinals[i]); + } + + return new RelativeDirection(processedCardinals); + } + + public static BlockFace getDirection(BlockData blockData) { + if (blockData instanceof Rotatable) return ((Rotatable) blockData).getRotation(); + else if (blockData instanceof Directional) return ((Directional) blockData).getFacing(); + else return BlockFace.SELF; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + for (RelativeCardinals cardinal : cardinals) { + sb.append(cardinal.name()).append("+"); + } + + return sb.substring(0, sb.length() - 1); + } + + public LocationOffset getTranslatedDirection(BlockFace directionFacing) { + LocationOffset sum = new LocationOffset(0, 0, 0); + + for (RelativeCardinals cardinal : cardinals) { + sum = sum.add(cardinal.getTranslation(directionFacing)); + } + + return sum; + } + +} From 5097fe50c9e074956b0ba592cf4c939afcd2aaa6 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 5 Aug 2022 10:40:43 -0700 Subject: [PATCH 35/53] Requested Changes + missed lang update - Moved RelativeCardinals to be nested in RelativeDirection - Change allowed-directions in lang to chest-directions - Updated comment for above to be more descriptive of usage and options --- .../relativedirection/RelativeCardinals.java | 75 ------------------- .../relativedirection/RelativeDirection.java | 46 ++++++++++++ src/main/resources/Lang/en-us.yml | 4 +- 3 files changed, 48 insertions(+), 77 deletions(-) delete mode 100644 src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeCardinals.java diff --git a/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeCardinals.java b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeCardinals.java deleted file mode 100644 index ea7de535..00000000 --- a/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeCardinals.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * - * Copyright (c) 2016-2019 - * SparklingComet @ http://shanerx.org - * KillerOfPie @ http://killerofpie.github.io - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * NOTICE: All modifications made by others to the source code belong - * to the respective contributor. No contributor should be held liable for - * any damages of any kind, whether be material or moral, which were - * caused by their contribution(s) to the project. See the full License for more information. - * - */ - -package org.shanerx.tradeshop.utils.relativedirection; - -import org.bukkit.block.BlockFace; - -public enum RelativeCardinals { - - SELF("0", "0", "0"), - DOWN("0", "-1", "0"), - UP("0", "1", "0"), - RIGHT("z", "0", "-x"), - LEFT("-z", "0", "x"), - BACK("-x", "0", "-z"), - FRONT("x", "0", "z"); - - private final transient String xTranslation; - private final transient String yTranslation; - private final transient String zTranslation; - - RelativeCardinals(String xTranslation, String yTranslation, String zTranslation) { - this.xTranslation = xTranslation; - this.yTranslation = yTranslation; - this.zTranslation = zTranslation; - } - - public LocationOffset getTranslation(BlockFace facing) { - return new LocationOffset(processTranslation(xTranslation, facing), processTranslation(yTranslation, facing), processTranslation(zTranslation, facing)); - } - - private int processTranslation(String translation, BlockFace facing) { - int temp = 0; - - try { - temp = Integer.parseInt(translation); - return temp; - } catch (NumberFormatException ignored) { - } - - if (translation.toLowerCase().contains("x")) - temp = facing.getModX(); - else if (translation.toLowerCase().contains("y")) - temp = facing.getModY(); - else if (translation.toLowerCase().contains("z")) - temp = facing.getModZ(); - - if (translation.contains("-")) - return Math.negateExact(temp); - - return temp; - } -} diff --git a/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeDirection.java b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeDirection.java index a1ef0a72..e7d0a914 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeDirection.java +++ b/src/main/java/org/shanerx/tradeshop/utils/relativedirection/RelativeDirection.java @@ -89,4 +89,50 @@ public LocationOffset getTranslatedDirection(BlockFace directionFacing) { return sum; } + public enum RelativeCardinals { + + SELF("0", "0", "0"), + DOWN("0", "-1", "0"), + UP("0", "1", "0"), + RIGHT("z", "0", "-x"), + LEFT("-z", "0", "x"), + BACK("-x", "0", "-z"), + FRONT("x", "0", "z"); + + private final transient String xTranslation; + private final transient String yTranslation; + private final transient String zTranslation; + + RelativeCardinals(String xTranslation, String yTranslation, String zTranslation) { + this.xTranslation = xTranslation; + this.yTranslation = yTranslation; + this.zTranslation = zTranslation; + } + + public LocationOffset getTranslation(BlockFace facing) { + return new LocationOffset(processTranslation(xTranslation, facing), processTranslation(yTranslation, facing), processTranslation(zTranslation, facing)); + } + + private int processTranslation(String translation, BlockFace facing) { + int temp = 0; + + try { + temp = Integer.parseInt(translation); + return temp; + } catch (NumberFormatException ignored) { + } + + if (translation.toLowerCase().contains("x")) + temp = facing.getModX(); + else if (translation.toLowerCase().contains("y")) + temp = facing.getModY(); + else if (translation.toLowerCase().contains("z")) + temp = facing.getModZ(); + + if (translation.contains("-")) + return Math.negateExact(temp); + + return temp; + } + } } diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 968c8dcc..0107aa3f 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -74,8 +74,8 @@ setting: pre-comment: "Out of Stock" post-comment: "\n" global-options: - allowed-directions: - pre-comment: "Directions an allowed shop can be from a sign. Allowed directions are:\n Up, Down, North, East, South, West" + chest-directions: + pre-comment: "Directions an allowed shop can be from a sign. Multiple directions can be chained together allowing all 26 blocks surrounding a block to be checked. \nTo Chain directions just add a `+` between each one. i.e `Back+Left` or `Back+Left+Up` \nAllowed directions are:\n Up, Down, Left, Right, Back, Front" allowed-shops: pre-comment: "Inventories to allow for shops. Allowed blocks are:\n Chest, Trapped_Chest, Dropper, Hopper, Dispenser, Shulker, ..." max-edit-distance: From ac6f56367b1ba337de11fb3ea520c14c7bd5ef8f Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 24 Nov 2022 19:15:38 -0800 Subject: [PATCH 36/53] Catching up non SQL code from SQL branch 1/? --- src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java index dbb19973..98f3e00f 100644 --- a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java +++ b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java @@ -51,11 +51,11 @@ public class PlayerSetting implements Serializable { private transient UUID uuid; private final String uuidString; private final Set ownedShops; - + private final Set staffShops; private boolean showInvolvedStatus, adminEnabled = true; private int multi = Setting.MULTI_TRADE_DEFAULT.getInt(); - private final Set staffShops; + private transient Utils utils = new Utils(); public PlayerSetting(UUID playerUUID, Map data) { From 98b7d883130a5a634bf53f6dd5d022622ffa5817 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 24 Nov 2022 19:17:29 -0800 Subject: [PATCH 37/53] Catching up non SQL code from SQL branch 1/? --- .../tradeshop/data/storage/DataStorage.java | 130 +++++++----------- .../Json/JsonLinkageConfiguration.java | 63 +++++++++ ...tion.java => JsonPlayerConfiguration.java} | 8 +- ...ration.java => JsonShopConfiguration.java} | 49 +------ .../{Json => }/LinkageConfiguration.java | 63 +++------ .../data/storage/PlayerConfiguration.java | 37 +++++ .../data/storage/ShopConfiguration.java | 83 +++++++++++ 7 files changed, 265 insertions(+), 168 deletions(-) create mode 100644 src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonLinkageConfiguration.java rename src/main/java/org/shanerx/tradeshop/data/storage/Json/{PlayerConfiguration.java => JsonPlayerConfiguration.java} (89%) rename src/main/java/org/shanerx/tradeshop/data/storage/Json/{ShopConfiguration.java => JsonShopConfiguration.java} (75%) rename src/main/java/org/shanerx/tradeshop/data/storage/{Json => }/LinkageConfiguration.java (53%) create mode 100644 src/main/java/org/shanerx/tradeshop/data/storage/PlayerConfiguration.java create mode 100644 src/main/java/org/shanerx/tradeshop/data/storage/ShopConfiguration.java diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java index 23afbc86..1649ddca 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java @@ -25,11 +25,15 @@ package org.shanerx.tradeshop.data.storage; +import org.apache.commons.lang.NotImplementedException; import org.bukkit.Chunk; import org.bukkit.World; -import org.shanerx.tradeshop.data.storage.Json.LinkageConfiguration; -import org.shanerx.tradeshop.data.storage.Json.PlayerConfiguration; -import org.shanerx.tradeshop.data.storage.Json.ShopConfiguration; +import org.shanerx.tradeshop.data.storage.Json.JsonLinkageConfiguration; +import org.shanerx.tradeshop.data.storage.Json.JsonPlayerConfiguration; +import org.shanerx.tradeshop.data.storage.Json.JsonShopConfiguration; +import org.shanerx.tradeshop.data.storage.sqlite.SQLiteLinkageConfiguration; +import org.shanerx.tradeshop.data.storage.sqlite.SQLitePlayerConfiguration; +import org.shanerx.tradeshop.data.storage.sqlite.SQLiteShopConfiguration; import org.shanerx.tradeshop.player.PlayerSetting; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shoplocation.ShopChunk; @@ -54,56 +58,24 @@ public void reload(DataType dataType) { } public Shop loadShopFromSign(ShopLocation sign) { - switch (dataType) { - case FLATFILE: - return new ShopConfiguration(new ShopChunk(sign.getChunk())).load(sign); - case SQLITE: - return null; //TODO add SQLITE support - } - return null; + return getShopConfiguration(sign.getChunk()).load(sign); } public Shop loadShopFromStorage(ShopLocation chest) { - switch (dataType) { - case FLATFILE: - return loadShopFromSign(new LinkageConfiguration(chest.getWorld()).getLinkedShop(chest)); - case SQLITE: - return null; //TODO add SQLITE support - } - return null; + return loadShopFromSign(getLinkageConfiguration(chest.getWorld()).getLinkedShop(chest)); } public void saveShop(Shop shop) { - switch (dataType) { - case FLATFILE: - new ShopConfiguration(new ShopChunk(shop.getShopLocation().getChunk())).save(shop); - break; - case SQLITE: - //TODO add SQLITE support - break; - } + getShopConfiguration(shop.getShopLocation().getChunk()).save(shop); } public void removeShop(Shop shop) { - switch (dataType) { - case FLATFILE: - new ShopConfiguration(new ShopChunk(shop.getShopLocation().getChunk())).remove(shop.getShopLocationAsSL()); - new LinkageConfiguration(shop.getShopLocationAsSL().getWorld()).removeShop(shop.getShopLocationAsSL()); - break; - case SQLITE: - //TODO add SQLITE support - break; - } + getShopConfiguration(shop.getShopLocation().getChunk()).remove(shop.getShopLocationAsSL()); + getLinkageConfiguration(shop.getShopLocationAsSL().getWorld()).removeShop(shop.getShopLocationAsSL()); } public int getShopCountInChunk(Chunk chunk) { - switch (dataType) { - case FLATFILE: - return new ShopConfiguration(new ShopChunk(chunk)).size(); - case SQLITE: - return 0; //TODO add SQLITE support - } - return 0; + return getShopConfiguration(chunk).size(); } public int getShopCountInWorld(World world) { @@ -114,83 +86,79 @@ public int getShopCountInWorld(World world) { if (folder.exists() && folder.listFiles() != null) { for (File file : folder.listFiles()) { if (file.getName().contains(world.getName())) - count += new ShopConfiguration(ShopChunk.deserialize(file.getName().replace(".json", ""))).size(); + count += new JsonShopConfiguration(ShopChunk.deserialize(file.getName().replace(".json", ""))).size(); } } break; case SQLITE: //TODO add SQLITE support - break; + throw new NotImplementedException("SQLITE for getShopCountInWorld has not been implemented yet."); } return count; } public PlayerSetting loadPlayer(UUID uuid) { - PlayerSetting playerSetting = null; - switch (dataType) { - case FLATFILE: - playerSetting = new PlayerConfiguration(uuid).load(); - break; - case SQLITE: - //TODO add SQLITE support - break; - } + PlayerSetting playerSetting = getPlayerConfiguration(uuid).load(); //If playerSetting data not find create new and return return playerSetting != null ? playerSetting : new PlayerSetting(uuid); } public void savePlayer(PlayerSetting playerSetting) { - switch (dataType) { - case FLATFILE: - new PlayerConfiguration(playerSetting.getUuid()).save(playerSetting); - break; - case SQLITE: - //TODO add SQLITE support - break; - } + getPlayerConfiguration(playerSetting.getUuid()).save(playerSetting); } public void removePlayer(PlayerSetting playerSetting) { - switch (dataType) { - case FLATFILE: - new PlayerConfiguration(playerSetting.getUuid()).remove(); - break; - case SQLITE: - //TODO add SQLITE support - break; - } + getPlayerConfiguration(playerSetting.getUuid()).remove(); } public ShopLocation getChestLinkage(ShopLocation chestLocation) { + return getLinkageConfiguration(chestLocation.getWorld()).getLinkedShop(chestLocation); + } + + public void addChestLinkage(ShopLocation chestLocation, ShopLocation shopLocation) { + getLinkageConfiguration(chestLocation.getWorld()).add(chestLocation, shopLocation); + } + + public void removeChestLinkage(ShopLocation chestLocation) { + getLinkageConfiguration(chestLocation.getWorld()).removeChest(chestLocation); + } + + protected PlayerConfiguration getPlayerConfiguration(UUID uuid) { switch (dataType) { case FLATFILE: - return new LinkageConfiguration(chestLocation.getWorld()).getLinkedShop(chestLocation); + return new JsonPlayerConfiguration(uuid); case SQLITE: - //TODO add SQLITE support - break; + return new SQLitePlayerConfiguration(uuid); + default: + throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); } + } - return null; + protected ShopConfiguration getShopConfiguration(Chunk chunk) { + return getShopConfiguration(new ShopChunk(chunk)); } - public void addChestLinkage(ShopLocation chestLocation, ShopLocation shopLocation) { + protected ShopConfiguration getShopConfiguration(ShopChunk chunk) { switch (dataType) { case FLATFILE: - new LinkageConfiguration(chestLocation.getWorld()).add(chestLocation, shopLocation); + return new JsonShopConfiguration(chunk); case SQLITE: - //TODO add SQLITE support - break; + return new SQLiteShopConfiguration(chunk); + default: + throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); } } - public void removeChestLinkage(ShopLocation chestLocation) { + protected LinkageConfiguration getLinkageConfiguration(World w) { switch (dataType) { case FLATFILE: - new LinkageConfiguration(chestLocation.getWorld()).removeChest(chestLocation); + return new JsonLinkageConfiguration(w); case SQLITE: - //TODO add SQLITE support - break; + return new SQLiteLinkageConfiguration(w); + default: + throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); } } -} \ No newline at end of file +} + diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonLinkageConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonLinkageConfiguration.java new file mode 100644 index 00000000..8cfb0eb7 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonLinkageConfiguration.java @@ -0,0 +1,63 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.data.storage.Json; + +import com.google.gson.reflect.TypeToken; +import org.bukkit.World; +import org.shanerx.tradeshop.data.storage.LinkageConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class JsonLinkageConfiguration extends JsonConfiguration implements LinkageConfiguration { + + Map linkageData; + + public JsonLinkageConfiguration(World world) { + super(world.getName(), "chest_linkage"); + load(); + } + + @Override + public void load() { + linkageData = gson.fromJson(jsonObj.get("linkage_data"), new TypeToken>() { + }.getType()); + if (linkageData == null) + linkageData = new HashMap<>(); + } + + @Override + public Map getLinkageData() { + return linkageData; + } + + @Override + public void save() { + jsonObj.add("linkage_data", gson.toJsonTree(linkageData)); + + saveFile(); + } +} diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/PlayerConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonPlayerConfiguration.java similarity index 89% rename from src/main/java/org/shanerx/tradeshop/data/storage/Json/PlayerConfiguration.java rename to src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonPlayerConfiguration.java index b67f9987..8bd4a946 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/PlayerConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonPlayerConfiguration.java @@ -26,22 +26,24 @@ package org.shanerx.tradeshop.data.storage.Json; import com.google.gson.reflect.TypeToken; +import org.shanerx.tradeshop.data.storage.PlayerConfiguration; import org.shanerx.tradeshop.player.PlayerSetting; import java.util.Map; import java.util.UUID; -public class PlayerConfiguration extends JsonConfiguration { +public class JsonPlayerConfiguration extends JsonConfiguration implements PlayerConfiguration { private final transient UUID playerUUID; private transient PlayerSetting playerSetting; - public PlayerConfiguration(UUID uuid) { + public JsonPlayerConfiguration(UUID uuid) { super("Players", uuid.toString()); playerUUID = uuid; } + @Override public void save(PlayerSetting playerSetting) { this.playerSetting = playerSetting; jsonObj.add(playerSetting.getUuid().toString(), gson.toJsonTree(playerSetting)); @@ -49,6 +51,7 @@ public void save(PlayerSetting playerSetting) { saveFile(); } + @Override public PlayerSetting load() { if (jsonObj.has("data")) { playerSetting = new PlayerSetting(playerUUID, gson.fromJson(jsonObj.get("data"), new TypeToken>() { @@ -65,6 +68,7 @@ public PlayerSetting load() { return playerSetting; } + @Override public void remove() { file.delete(); } diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java similarity index 75% rename from src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java rename to src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java index 26232c78..486cf7f0 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/ShopConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java @@ -25,10 +25,9 @@ package org.shanerx.tradeshop.data.storage.Json; -import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gson.JsonElement; -import org.bukkit.inventory.ItemStack; +import org.shanerx.tradeshop.data.storage.ShopConfiguration; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shoplocation.ShopChunk; @@ -39,11 +38,11 @@ import java.util.List; import java.util.Map; -public class ShopConfiguration extends JsonConfiguration { +public class JsonShopConfiguration extends JsonConfiguration implements ShopConfiguration { private final ShopChunk chunk; - public ShopConfiguration(ShopChunk chunk) { + public JsonShopConfiguration(ShopChunk chunk) { super(chunk.getWorld().getName(), chunk.serialize()); this.chunk = chunk; } @@ -67,12 +66,14 @@ public void loadFile() { } } + @Override public void save(Shop shop) { jsonObj.add(shop.getShopLocationAsSL().serialize(), gson.toJsonTree(shop)); saveFile(); } + @Override public void remove(ShopLocation loc) { if (jsonObj.has(loc.serialize())) jsonObj.remove(loc.serialize()); @@ -80,6 +81,7 @@ public void remove(ShopLocation loc) { saveFile(); } + @Override public Shop load(ShopLocation loc) { Shop shop; @@ -122,45 +124,8 @@ public Shop load(ShopLocation loc) { return shop; } + @Override public int size() { return jsonObj.size(); } - - - /** - * Turns old overstacked itemstacks into individual stacks in a list - * - * @param oldB64 old B64 string to check/fix - * @return new list of ItemStacks - * @deprecated - */ - private List b64OverstackFixer(String oldB64) { - ShopItemStack oldStack = new ShopItemStack(oldB64); - - if (oldStack.hasBase64()) - return null; - - if (!(oldStack.getItemStack().getAmount() > oldStack.getItemStack().getMaxStackSize())) { - return Lists.newArrayList(oldStack); - } else { - List newStacks = new ArrayList<>(); - int amount = oldStack.getItemStack().getAmount(); - - while (amount > 0) { - if (oldStack.getItemStack().getMaxStackSize() < amount) { - ItemStack itm = oldStack.getItemStack().clone(); - itm.setAmount(oldStack.getItemStack().getMaxStackSize()); - newStacks.add(new ShopItemStack(itm)); - amount -= oldStack.getItemStack().getMaxStackSize(); - } else { - ItemStack itm = oldStack.getItemStack().clone(); - itm.setAmount(amount); - newStacks.add(new ShopItemStack(itm)); - amount -= amount; - } - } - - return newStacks; - } - } } diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/LinkageConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java similarity index 53% rename from src/main/java/org/shanerx/tradeshop/data/storage/Json/LinkageConfiguration.java rename to src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java index ce465e11..2b2eedeb 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/LinkageConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java @@ -23,55 +23,40 @@ * */ -package org.shanerx.tradeshop.data.storage.Json; +package org.shanerx.tradeshop.data.storage; -import com.google.gson.reflect.TypeToken; -import org.bukkit.World; import org.shanerx.tradeshop.shop.ShopChest; import org.shanerx.tradeshop.shoplocation.ShopLocation; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; -public class LinkageConfiguration extends JsonConfiguration { +public interface LinkageConfiguration { - Map linkageData; + void save(); - public LinkageConfiguration(World world) { - super(world.getName(), "chest_linkage"); - load(); - } - - public void load() { - linkageData = gson.fromJson(jsonObj.get("linkage_data"), new TypeToken>() { - }.getType()); - if (linkageData == null) - linkageData = new HashMap<>(); - } + void load(); - public Map getLinkageData() { - return linkageData; - } + Map getLinkageData(); - public ShopLocation getLinkedShop(ShopLocation chestLocation) { + default ShopLocation getLinkedShop(ShopLocation chestLocation) { String loc = chestLocation.serialize(); - - return linkageData.containsKey(loc) ? ShopLocation.deserialize(linkageData.get(chestLocation.serialize())) : null; + return getLinkageData().containsKey(loc) ? ShopLocation.deserialize(getLinkageData().get(chestLocation.serialize())) : null; } - public void save() { - jsonObj.add("linkage_data", gson.toJsonTree(linkageData)); - - saveFile(); + default int size() { + return getLinkageData().size(); } - public int size() { - return linkageData.size(); + default void addLinkage(ShopLocation chestLocation, ShopLocation shopLocation) { + if (getLinkageData().containsKey(chestLocation.serialize())) + getLinkageData().replace(chestLocation.serialize(), shopLocation.serialize()); + else + getLinkageData().put(chestLocation.serialize(), shopLocation.serialize()); } - public void add(ShopLocation chestLocation, ShopLocation shopLocation) { + default void add(ShopLocation chestLocation, ShopLocation shopLocation) { if (ShopChest.isDoubleChest(chestLocation.getLocation().getBlock())) { ShopLocation otherSideLocation = new ShopLocation(ShopChest.getOtherHalfOfDoubleChest(chestLocation.getLocation().getBlock()).getLocation()); addLinkage(otherSideLocation, shopLocation); @@ -81,28 +66,20 @@ public void add(ShopLocation chestLocation, ShopLocation shopLocation) { save(); } - public void removeChest(ShopLocation chestLocation) { - linkageData.remove(chestLocation); + default void removeChest(ShopLocation chestLocation) { + getLinkageData().remove(chestLocation); save(); } - public void removeShop(ShopLocation shopLocation) { + default void removeShop(ShopLocation shopLocation) { List removeChests = new ArrayList<>(); String shopLoc = shopLocation.serialize(); - linkageData.forEach((key, value) -> { + getLinkageData().forEach((key, value) -> { if (value.equals(shopLoc)) removeChests.add(key); }); - removeChests.forEach((k) -> linkageData.remove(k)); + removeChests.forEach((k) -> getLinkageData().remove(k)); } - - private void addLinkage(ShopLocation chestLocation, ShopLocation shopLocation) { - if (linkageData.containsKey(chestLocation.serialize())) - linkageData.replace(chestLocation.serialize(), shopLocation.serialize()); - else - linkageData.put(chestLocation.serialize(), shopLocation.serialize()); - } - } diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/PlayerConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/PlayerConfiguration.java new file mode 100644 index 00000000..7bcb4092 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/data/storage/PlayerConfiguration.java @@ -0,0 +1,37 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.data.storage; + +import org.shanerx.tradeshop.player.PlayerSetting; + +public interface PlayerConfiguration { + + void save(PlayerSetting playerSetting); + + PlayerSetting load(); + + void remove(); +} diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/ShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/ShopConfiguration.java new file mode 100644 index 00000000..f3fef8da --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/data/storage/ShopConfiguration.java @@ -0,0 +1,83 @@ +/* + * + * Copyright (c) 2016-2019 + * SparklingComet @ http://shanerx.org + * KillerOfPie @ http://killerofpie.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NOTICE: All modifications made by others to the source code belong + * to the respective contributor. No contributor should be held liable for + * any damages of any kind, whether be material or moral, which were + * caused by their contribution(s) to the project. See the full License for more information. + * + */ + +package org.shanerx.tradeshop.data.storage; + +import com.google.common.collect.Lists; +import org.bukkit.inventory.ItemStack; +import org.shanerx.tradeshop.item.ShopItemStack; +import org.shanerx.tradeshop.shop.Shop; +import org.shanerx.tradeshop.shoplocation.ShopLocation; + +import java.util.ArrayList; +import java.util.List; + +public interface ShopConfiguration { + + void save(Shop shop); + + void remove(ShopLocation loc); + + Shop load(ShopLocation loc); + + int size(); + + /** + * Turns old overstacked itemstacks into individual stacks in a list + * + * @param oldB64 old B64 string to check/fix + * @return new list of ItemStacks + * @deprecated + */ + default List b64OverstackFixer(String oldB64) { + ShopItemStack oldStack = new ShopItemStack(oldB64); + + if (oldStack.hasBase64()) + return null; + + if (!(oldStack.getItemStack().getAmount() > oldStack.getItemStack().getMaxStackSize())) { + return Lists.newArrayList(oldStack); + } else { + List newStacks = new ArrayList<>(); + int amount = oldStack.getItemStack().getAmount(); + + while (amount > 0) { + if (oldStack.getItemStack().getMaxStackSize() < amount) { + ItemStack itm = oldStack.getItemStack().clone(); + itm.setAmount(oldStack.getItemStack().getMaxStackSize()); + newStacks.add(new ShopItemStack(itm)); + amount -= oldStack.getItemStack().getMaxStackSize(); + } else { + ItemStack itm = oldStack.getItemStack().clone(); + itm.setAmount(amount); + newStacks.add(new ShopItemStack(itm)); + amount -= amount; + } + } + + return newStacks; + } + } +} From 2e74d3afd530bb58f51c1a59d4073633ac01dbd3 Mon Sep 17 00:00:00 2001 From: Sparkling Comet Date: Tue, 5 Jul 2022 21:40:08 +0200 Subject: [PATCH 38/53] trivial optimization/refactoring of JsonShopConfiguration --- .../storage/Json/JsonShopConfiguration.java | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java index 486cf7f0..de0f9de0 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java @@ -84,38 +84,39 @@ public void remove(ShopLocation loc) { @Override public Shop load(ShopLocation loc) { Shop shop; + String locStr = loc.serialize(); - if (jsonObj.has(loc.serialize())) { - if (jsonObj.getAsJsonObject(loc.serialize()).getAsJsonPrimitive("productB64") != null) { - String str = jsonObj.getAsJsonObject(loc.serialize()).get("productB64").getAsString(); - jsonObj.getAsJsonObject(loc.serialize()).remove("productB64"); - jsonObj.getAsJsonObject(loc.serialize()).add("product", gson.toJsonTree(b64OverstackFixer(str))); + if (jsonObj.has(locStr)) { + if (jsonObj.getAsJsonObject(locStr).getAsJsonPrimitive("productB64") != null) { + String str = jsonObj.getAsJsonObject(locStr).get("productB64").getAsString(); + jsonObj.getAsJsonObject(locStr).remove("productB64"); + jsonObj.getAsJsonObject(locStr).add("product", gson.toJsonTree(b64OverstackFixer(str))); saveFile(); } - if (jsonObj.getAsJsonObject(loc.serialize()).getAsJsonPrimitive("costB64") != null) { - String str = jsonObj.getAsJsonObject(loc.serialize()).get("costB64").getAsString(); - jsonObj.getAsJsonObject(loc.serialize()).remove("costB64"); - jsonObj.getAsJsonObject(loc.serialize()).add("cost", gson.toJsonTree(b64OverstackFixer(str))); + if (jsonObj.getAsJsonObject(locStr).getAsJsonPrimitive("costB64") != null) { + String str = jsonObj.getAsJsonObject(locStr).get("costB64").getAsString(); + jsonObj.getAsJsonObject(locStr).remove("costB64"); + jsonObj.getAsJsonObject(locStr).add("cost", gson.toJsonTree(b64OverstackFixer(str))); saveFile(); } - if (jsonObj.getAsJsonObject(loc.serialize()).has("productListB64")) { + if (jsonObj.getAsJsonObject(locStr).has("productListB64")) { List productList = new ArrayList<>(); - gson.fromJson(jsonObj.getAsJsonObject(loc.serialize()).get("productListB64"), List.class).forEach(item -> productList.add(new ShopItemStack(item.toString()))); - jsonObj.getAsJsonObject(loc.serialize()).remove("productListB64"); - jsonObj.getAsJsonObject(loc.serialize()).add("product", gson.toJsonTree(productList)); + gson.fromJson(jsonObj.getAsJsonObject(locStr).get("productListB64"), List.class).forEach(item -> productList.add(new ShopItemStack(item.toString()))); + jsonObj.getAsJsonObject(locStr).remove("productListB64"); + jsonObj.getAsJsonObject(locStr).add("product", gson.toJsonTree(productList)); } - if (jsonObj.getAsJsonObject(loc.serialize()).has("costListB64")) { + if (jsonObj.getAsJsonObject(locStr).has("costListB64")) { List costList = new ArrayList<>(); - gson.fromJson(jsonObj.getAsJsonObject(loc.serialize()).get("costListB64"), List.class).forEach(item -> costList.add(new ShopItemStack(item.toString()))); - jsonObj.getAsJsonObject(loc.serialize()).remove("costListB64"); - jsonObj.getAsJsonObject(loc.serialize()).add("cost", gson.toJsonTree(costList)); + gson.fromJson(jsonObj.getAsJsonObject(locStr).get("costListB64"), List.class).forEach(item -> costList.add(new ShopItemStack(item.toString()))); + jsonObj.getAsJsonObject(locStr).remove("costListB64"); + jsonObj.getAsJsonObject(locStr).add("cost", gson.toJsonTree(costList)); } - shop = gson.fromJson(jsonObj.get(loc.serialize()), Shop.class); + shop = gson.fromJson(jsonObj.get(locStr), Shop.class); } else { return null; } From 5b6669743ee0de1668c63041ea4c59405ca8f95d Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Tue, 5 Jul 2022 16:40:57 -0700 Subject: [PATCH 39/53] Catching up non SQL code from SQL branch 1/? --- .../storage/Json/JsonShopConfiguration.java | 58 +++++++------- .../shanerx/tradeshop/item/ShopItemStack.java | 75 +++++++++---------- 2 files changed, 66 insertions(+), 67 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java index de0f9de0..5a11aab7 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java @@ -86,41 +86,43 @@ public Shop load(ShopLocation loc) { Shop shop; String locStr = loc.serialize(); - if (jsonObj.has(locStr)) { - if (jsonObj.getAsJsonObject(locStr).getAsJsonPrimitive("productB64") != null) { - String str = jsonObj.getAsJsonObject(locStr).get("productB64").getAsString(); - jsonObj.getAsJsonObject(locStr).remove("productB64"); - jsonObj.getAsJsonObject(locStr).add("product", gson.toJsonTree(b64OverstackFixer(str))); - saveFile(); - } + if (!jsonObj.has(locStr)) { + return null; + } - if (jsonObj.getAsJsonObject(locStr).getAsJsonPrimitive("costB64") != null) { - String str = jsonObj.getAsJsonObject(locStr).get("costB64").getAsString(); - jsonObj.getAsJsonObject(locStr).remove("costB64"); - jsonObj.getAsJsonObject(locStr).add("cost", gson.toJsonTree(b64OverstackFixer(str))); - saveFile(); - } + boolean save2Correct = false; + if (jsonObj.getAsJsonObject(locStr).getAsJsonPrimitive("productB64") != null) { + String str = jsonObj.getAsJsonObject(locStr).get("productB64").getAsString(); + jsonObj.getAsJsonObject(locStr).remove("productB64"); + jsonObj.getAsJsonObject(locStr).add("product", gson.toJsonTree(b64OverstackFixer(str))); + save2Correct = true; + } - if (jsonObj.getAsJsonObject(locStr).has("productListB64")) { - List productList = new ArrayList<>(); - gson.fromJson(jsonObj.getAsJsonObject(locStr).get("productListB64"), List.class).forEach(item -> productList.add(new ShopItemStack(item.toString()))); - jsonObj.getAsJsonObject(locStr).remove("productListB64"); - jsonObj.getAsJsonObject(locStr).add("product", gson.toJsonTree(productList)); - } + if (jsonObj.getAsJsonObject(locStr).getAsJsonPrimitive("costB64") != null) { + String str = jsonObj.getAsJsonObject(locStr).get("costB64").getAsString(); + jsonObj.getAsJsonObject(locStr).remove("costB64"); + jsonObj.getAsJsonObject(locStr).add("cost", gson.toJsonTree(b64OverstackFixer(str))); + save2Correct = true; + } - if (jsonObj.getAsJsonObject(locStr).has("costListB64")) { - List costList = new ArrayList<>(); - gson.fromJson(jsonObj.getAsJsonObject(locStr).get("costListB64"), List.class).forEach(item -> costList.add(new ShopItemStack(item.toString()))); - jsonObj.getAsJsonObject(locStr).remove("costListB64"); - jsonObj.getAsJsonObject(locStr).add("cost", gson.toJsonTree(costList)); - } + if (save2Correct) saveFile(); + if (jsonObj.getAsJsonObject(locStr).has("productListB64")) { + List productList = new ArrayList<>(); + gson.fromJson(jsonObj.getAsJsonObject(locStr).get("productListB64"), List.class).forEach(item -> productList.add(new ShopItemStack(item.toString()))); + jsonObj.getAsJsonObject(locStr).remove("productListB64"); + jsonObj.getAsJsonObject(locStr).add("product", gson.toJsonTree(productList)); + } - shop = gson.fromJson(jsonObj.get(locStr), Shop.class); - } else { - return null; + if (jsonObj.getAsJsonObject(locStr).has("costListB64")) { + List costList = new ArrayList<>(); + gson.fromJson(jsonObj.getAsJsonObject(locStr).get("costListB64"), List.class).forEach(item -> costList.add(new ShopItemStack(item.toString()))); + jsonObj.getAsJsonObject(locStr).remove("costListB64"); + jsonObj.getAsJsonObject(locStr).add("cost", gson.toJsonTree(costList)); } + shop = gson.fromJson(jsonObj.get(locStr), Shop.class); + shop.fixAfterLoad(); return shop; } diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index c8e9b38f..d5f3cae4 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -28,6 +28,7 @@ import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import net.md_5.bungee.api.ChatColor; import org.apache.commons.lang.WordUtils; @@ -35,15 +36,8 @@ import org.bukkit.Material; import org.bukkit.block.ShulkerBox; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BlockStateMeta; -import org.bukkit.inventory.meta.BookMeta; -import org.bukkit.inventory.meta.BundleMeta; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.bukkit.inventory.meta.FireworkMeta; -import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.*; import org.bukkit.util.io.BukkitObjectInputStream; -import org.bukkit.util.io.BukkitObjectOutputStream; import org.shanerx.tradeshop.utils.Utils; import org.shanerx.tradeshop.utils.debug.Debug; import org.shanerx.tradeshop.utils.debug.DebugLevels; @@ -51,7 +45,6 @@ import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; @@ -64,8 +57,13 @@ public class ShopItemStack implements Serializable, Cloneable { private transient ItemStack itemStack; private transient Debug debugger; + @Expose(serialize = false) private String itemStackB64; + @Expose + private Map serialItemStack; + + @Expose @SerializedName(value = "itemSettings", alternate = "shopSettings") private Map> itemSettings; @@ -77,7 +75,6 @@ public ShopItemStack(ItemStack itemStack, HashMap> itemS itemSettings.forEach((key, value) -> this.itemSettings.put(ShopItemStackSettingKeys.match(key), value)); buildMap(); - fromBase64(); + loadData(); } //Re-added for backwards compatibility @@ -117,7 +114,7 @@ public ShopItemStack(String itemStackB64, int compareDurability, boolean compare itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS, new ObjectHolder<>(compareEnchantments)); buildMap(); - fromBase64(); + loadData(); } public Map> getItemSettings() { @@ -130,7 +127,7 @@ public String serialize() { public static ShopItemStack deserialize(String serialized) { ShopItemStack item = new Gson().fromJson(serialized, ShopItemStack.class); - item.fromBase64(); + item.loadData(); item.buildMap(); return item; } @@ -198,7 +195,7 @@ public int getAmount() { public void setAmount(int amount) { itemStack.setAmount(amount); - toBase64(); + unloadData(); } public String getItemStackB64() { @@ -494,7 +491,7 @@ public boolean isSimilar(ItemStack toCompare) { public ItemStack getItemStack() { if (itemStack == null) - fromBase64(); + loadData(); return itemStack; } @@ -561,7 +558,7 @@ public String getStateString(ObjectHolder stateSetting) { @Override public String toString() { return "ShopItemStack{" + - "itemStack=" + getItemStack() + + "itemStack=" + getItemStack().serialize() + ", shopSettings=" + itemSettings + '}'; } @@ -576,39 +573,39 @@ public String toString() { /** * Sets the objects Base64 from its {@link ItemStack} */ - private void toBase64() { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - - // Save every element in the list - dataOutput.writeObject(itemStack); - - // Serialize that array - dataOutput.close(); - itemStackB64 = Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (IOException e) { - itemStackB64 = null; - } + private void unloadData() { + itemStackB64 = null; + serialItemStack = itemStack.serialize(); } /** * Sets the objects {@link ItemStack} from its Base64. */ - private void fromBase64() { - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(itemStackB64)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + private void loadData() { + if (serialItemStack != null && !serialItemStack.isEmpty()) { + itemStack = ItemStack.deserialize(serialItemStack); + } + + if (hasBase64()) { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(itemStackB64)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - // Read the serialized inventory - itemStack = new ItemStack((ItemStack) dataInput.readObject()); + // Read the serialized inventory + itemStack = new ItemStack((ItemStack) dataInput.readObject()); - dataInput.close(); - } catch (ClassNotFoundException | IOException e) { - itemStack = null; + dataInput.close(); + } catch (ClassNotFoundException | IOException e) { + itemStack = null; + } } } + public int getItemSize() { + unloadData(); + return serialItemStack.toString().length(); + } + public String toConsoleText() { return new GsonBuilder().setPrettyPrinting().create().toJson(this); } From 33dd8ba9a104c2496206813bedd6806555d546cb Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Wed, 6 Jul 2022 20:12:21 -0700 Subject: [PATCH 40/53] Minor Changes - Add SQLITE option to data-storage-type pre-comment - POM Version updates - POM Improvements - Added `Clean` and `skipDocs` profiles for maven builds - Moved `original` and JavaDocs output to `target/output-Files` sub folders - Updated JavaDoc exclusions - Excluded `META-INF/maven` files from builds --- pom.xml | 70 +++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 51 insertions(+), 19 deletions(-) diff --git a/pom.xml b/pom.xml index 97415ce1..ee82c084 100644 --- a/pom.xml +++ b/pom.xml @@ -73,37 +73,60 @@ UTF-8 yyyy-MM-dd'T'HH.mm.ss ${maven.build.timestamp} - + org/shanerx/tradeshop + src/main/resources + + + + + + + + target/output-files + + expiration - builddate.yml + builddate.yml + + + + clean + + clean + + + + skipDocs + + true - install - ${project.artifactId}-${project.version}-${maven.build.timestamp} + ${doClean} install + ${project.name}-${project.version}-${maven.build.timestamp} src/main/java . true - ${basedir}/src/main/resources/ + ${basedir}/${resourceDir} plugin.yml - ${builddate} + ${expirationFile} ./Lang false - ${basedir}/src/main/resources/Lang + ${basedir}/${resourceDir}/Lang @@ -122,23 +145,32 @@ maven-shade-plugin 3.3.0 + ${outputDir}/PreShade false org.bstats:* - de.themoep:* + de.themoep:* org.bstats - org.shanerx.tradeshop + ${project.groupId}.${project.artifactId}.bstats de.themoep - org.shanerx.tradeshop.Pipes.libs + ${project.groupId}.${project.artifactId} + + + *:* + + META-INF/maven/** + + + @@ -155,14 +187,15 @@ 3.4.0 false + ${outputDir}/JavaDocs - ${skip_docs} + ${skipDocs} - org/shanerx/tradeshop/TradeShop.java - org/shanerx/tradeshop/commands/** - org/shanerx/tradeshop/listeners/** - org/shanerx/tradeshop/utils/Updater.java - org/shanerx/tradeshop/utils/BukkitVersion.java + ${pluginDir}/TradeShop.java + ${pluginDir}/commands/** + ${pluginDir}/shop/listeners/** + ${pluginDir}/utils/versionmanagement/** + ${pluginDir}/player/JoinEventListener.java @@ -212,15 +245,14 @@ de.themoep inventorygui - - 1.4.2-SNAPSHOT + 1.5-SNAPSHOT compile org.apache.maven.plugins maven-javadoc-plugin - 3.3.2 + 3.4.0 maven-plugin From adac565d612e90968e5df0e0a75e8d7f1dd52667 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 7 Jul 2022 13:26:53 -0700 Subject: [PATCH 41/53] Removal of un-needed legacy data fixes --- .../storage/Json/JsonShopConfiguration.java | 34 --------------- .../data/storage/ShopConfiguration.java | 43 ------------------- 2 files changed, 77 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java index 5a11aab7..1baaad6c 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java @@ -28,14 +28,11 @@ import com.google.common.collect.Sets; import com.google.gson.JsonElement; import org.shanerx.tradeshop.data.storage.ShopConfiguration; -import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shoplocation.ShopChunk; import org.shanerx.tradeshop.shoplocation.ShopLocation; import java.io.File; -import java.util.ArrayList; -import java.util.List; import java.util.Map; public class JsonShopConfiguration extends JsonConfiguration implements ShopConfiguration { @@ -90,37 +87,6 @@ public Shop load(ShopLocation loc) { return null; } - boolean save2Correct = false; - if (jsonObj.getAsJsonObject(locStr).getAsJsonPrimitive("productB64") != null) { - String str = jsonObj.getAsJsonObject(locStr).get("productB64").getAsString(); - jsonObj.getAsJsonObject(locStr).remove("productB64"); - jsonObj.getAsJsonObject(locStr).add("product", gson.toJsonTree(b64OverstackFixer(str))); - save2Correct = true; - } - - if (jsonObj.getAsJsonObject(locStr).getAsJsonPrimitive("costB64") != null) { - String str = jsonObj.getAsJsonObject(locStr).get("costB64").getAsString(); - jsonObj.getAsJsonObject(locStr).remove("costB64"); - jsonObj.getAsJsonObject(locStr).add("cost", gson.toJsonTree(b64OverstackFixer(str))); - save2Correct = true; - } - - if (save2Correct) saveFile(); - - if (jsonObj.getAsJsonObject(locStr).has("productListB64")) { - List productList = new ArrayList<>(); - gson.fromJson(jsonObj.getAsJsonObject(locStr).get("productListB64"), List.class).forEach(item -> productList.add(new ShopItemStack(item.toString()))); - jsonObj.getAsJsonObject(locStr).remove("productListB64"); - jsonObj.getAsJsonObject(locStr).add("product", gson.toJsonTree(productList)); - } - - if (jsonObj.getAsJsonObject(locStr).has("costListB64")) { - List costList = new ArrayList<>(); - gson.fromJson(jsonObj.getAsJsonObject(locStr).get("costListB64"), List.class).forEach(item -> costList.add(new ShopItemStack(item.toString()))); - jsonObj.getAsJsonObject(locStr).remove("costListB64"); - jsonObj.getAsJsonObject(locStr).add("cost", gson.toJsonTree(costList)); - } - shop = gson.fromJson(jsonObj.get(locStr), Shop.class); shop.fixAfterLoad(); diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/ShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/ShopConfiguration.java index f3fef8da..ccff0eda 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/ShopConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/ShopConfiguration.java @@ -25,15 +25,9 @@ package org.shanerx.tradeshop.data.storage; -import com.google.common.collect.Lists; -import org.bukkit.inventory.ItemStack; -import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shoplocation.ShopLocation; -import java.util.ArrayList; -import java.util.List; - public interface ShopConfiguration { void save(Shop shop); @@ -43,41 +37,4 @@ public interface ShopConfiguration { Shop load(ShopLocation loc); int size(); - - /** - * Turns old overstacked itemstacks into individual stacks in a list - * - * @param oldB64 old B64 string to check/fix - * @return new list of ItemStacks - * @deprecated - */ - default List b64OverstackFixer(String oldB64) { - ShopItemStack oldStack = new ShopItemStack(oldB64); - - if (oldStack.hasBase64()) - return null; - - if (!(oldStack.getItemStack().getAmount() > oldStack.getItemStack().getMaxStackSize())) { - return Lists.newArrayList(oldStack); - } else { - List newStacks = new ArrayList<>(); - int amount = oldStack.getItemStack().getAmount(); - - while (amount > 0) { - if (oldStack.getItemStack().getMaxStackSize() < amount) { - ItemStack itm = oldStack.getItemStack().clone(); - itm.setAmount(oldStack.getItemStack().getMaxStackSize()); - newStacks.add(new ShopItemStack(itm)); - amount -= oldStack.getItemStack().getMaxStackSize(); - } else { - ItemStack itm = oldStack.getItemStack().clone(); - itm.setAmount(amount); - newStacks.add(new ShopItemStack(itm)); - amount -= amount; - } - } - - return newStacks; - } - } } From e5fe3d2c7bb7eaf93442eeb499f64d560df2c9dc Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 7 Jul 2022 18:42:49 -0700 Subject: [PATCH 42/53] Catching up non SQL code from SQL branch 1/? --- src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index d5f3cae4..ebe4f10d 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -574,8 +574,10 @@ public String toString() { * Sets the objects Base64 from its {@link ItemStack} */ private void unloadData() { - itemStackB64 = null; - serialItemStack = itemStack.serialize(); + if (itemStack != null) { + itemStackB64 = null; + serialItemStack = itemStack.serialize(); + } } /** From 15d88bc3bf2203b34f75a9b79c5ebdac857783de Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 24 Nov 2022 19:26:58 -0800 Subject: [PATCH 43/53] Catching up non SQL code from SQL branch 1/? --- .../data/storage/LinkageConfiguration.java | 2 + .../java/org/shanerx/tradeshop/shop/Shop.java | 45 +++++++++++-------- .../tradeshop/utils/debug/DebugLevels.java | 4 +- 3 files changed, 30 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java index 2b2eedeb..b82435e5 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java @@ -54,6 +54,7 @@ default void addLinkage(ShopLocation chestLocation, ShopLocation shopLocation) { getLinkageData().replace(chestLocation.serialize(), shopLocation.serialize()); else getLinkageData().put(chestLocation.serialize(), shopLocation.serialize()); + save(); } default void add(ShopLocation chestLocation, ShopLocation shopLocation) { @@ -81,5 +82,6 @@ default void removeShop(ShopLocation shopLocation) { }); removeChests.forEach((k) -> getLinkageData().remove(k)); + save(); } } diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 556613a7..48e72ead 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -51,14 +51,7 @@ import org.shanerx.tradeshop.utils.objects.Tuple; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.stream.Collectors; public class Shop implements Serializable { @@ -80,13 +73,14 @@ public class Shop implements Serializable { /** * Creates a Shop object * - * @param locations Location of shop sign and chest as Tuple, left = Sign location, right = inventory location - * @param owner Owner of the shop as a ShopUser - * @param shopType Type of the shop as ShopType - * @param items Items to go into the shop as Tuple, left = Product, right = Cost - * @param players Users to be added to the shop as Tuple, left = Managers, right = Members - */ - public Shop(Tuple locations, ShopType shopType, ShopUser owner, Tuple, Set> players, Tuple items) { + * @param locations Location of shop sign and chest as Tuple, left = Sign location, right = inventory location + * @param owner Owner of the shop as a ShopUser + * @param shopType Type of the shop as ShopType + * @param productItems Product items to go into the shop + * @param costItems Cost items to go into the shop + * @param players Users to be added to the shop as Tuple, left = Managers, right = Members + */ + public Shop(Tuple locations, ShopType shopType, ShopUser owner, Tuple, Set> players, List productItems, List costItems) { shopLoc = new ShopLocation(locations.getLeft()); this.owner = owner; @@ -100,15 +94,28 @@ public Shop(Tuple locations, ShopType shopType, ShopUser own managers = players.getLeft() == null ? new HashSet<>() : players.getLeft(); members = players.getRight() == null ? new HashSet<>() : players.getRight(); - product = new ArrayList<>(); - cost = new ArrayList<>(); + product = productItems != null ? new ArrayList<>(productItems) : new ArrayList<>(); + cost = costItems != null ? new ArrayList<>(costItems) : new ArrayList<>(); - if (items.getLeft() != null) product.add(new ShopItemStack(items.getLeft())); - if (items.getRight() != null) cost.add(new ShopItemStack(items.getRight())); + product.removeIf(shopItemStack -> shopItemStack.getItemStack() == null); + cost.removeIf(shopItemStack -> shopItemStack.getItemStack() == null); fixAfterLoad(); } + /** + * Creates a Shop object + * + * @param locations Location of shop sign and chest as Tuple, left = Sign location, right = inventory location + * @param owner Owner of the shop as a ShopUser + * @param shopType Type of the shop as ShopType + * @param items Items to go into the shop as Tuple, left = Product, right = Cost + * @param players Users to be added to the shop as Tuple, left = Managers, right = Members + */ + public Shop(Tuple locations, ShopType shopType, ShopUser owner, Tuple, Set> players, Tuple items) { + this(locations, shopType, owner, players, Collections.singletonList(new ShopItemStack(items.getLeft())), Collections.singletonList(new ShopItemStack(items.getRight()))); + } + /** * Creates a Shop object * diff --git a/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java b/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java index db44c016..a4239e06 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java +++ b/src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java @@ -42,8 +42,8 @@ public enum DebugLevels { SHULKERS_SUCK(8, Level.WARNING), // 128 ENCHANT_CHECKS(9, Level.WARNING), // 256 OUTPUT(10, Level.WARNING), // 512 - SHOP_CREATION(11, Level.INFO) // 1024 - ; + SHOP_CREATION(11, Level.INFO), // 1024 + SQLITE(12, Level.INFO); //position is what value to check for this level in the binary string -1. // From d828ca9748a9b88d1c75fd877af42e3ad0a24996 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 24 Nov 2022 19:29:16 -0800 Subject: [PATCH 44/53] Catching up non SQL code from SQL branch 1/? --- .../tradeshop/data/storage/DataStorage.java | 33 +++++-------------- 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java index 1649ddca..6fe71971 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java @@ -31,9 +31,6 @@ import org.shanerx.tradeshop.data.storage.Json.JsonLinkageConfiguration; import org.shanerx.tradeshop.data.storage.Json.JsonPlayerConfiguration; import org.shanerx.tradeshop.data.storage.Json.JsonShopConfiguration; -import org.shanerx.tradeshop.data.storage.sqlite.SQLiteLinkageConfiguration; -import org.shanerx.tradeshop.data.storage.sqlite.SQLitePlayerConfiguration; -import org.shanerx.tradeshop.data.storage.sqlite.SQLiteShopConfiguration; import org.shanerx.tradeshop.player.PlayerSetting; import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.shoplocation.ShopChunk; @@ -125,14 +122,10 @@ public void removeChestLinkage(ShopLocation chestLocation) { } protected PlayerConfiguration getPlayerConfiguration(UUID uuid) { - switch (dataType) { - case FLATFILE: - return new JsonPlayerConfiguration(uuid); - case SQLITE: - return new SQLitePlayerConfiguration(uuid); - default: - throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); + if (dataType == DataType.FLATFILE) { + return new JsonPlayerConfiguration(uuid); } + throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); } protected ShopConfiguration getShopConfiguration(Chunk chunk) { @@ -140,25 +133,17 @@ protected ShopConfiguration getShopConfiguration(Chunk chunk) { } protected ShopConfiguration getShopConfiguration(ShopChunk chunk) { - switch (dataType) { - case FLATFILE: - return new JsonShopConfiguration(chunk); - case SQLITE: - return new SQLiteShopConfiguration(chunk); - default: - throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); + if (dataType == DataType.FLATFILE) { + return new JsonShopConfiguration(chunk); } + throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); } protected LinkageConfiguration getLinkageConfiguration(World w) { - switch (dataType) { - case FLATFILE: - return new JsonLinkageConfiguration(w); - case SQLITE: - return new SQLiteLinkageConfiguration(w); - default: - throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); + if (dataType == DataType.FLATFILE) { + return new JsonLinkageConfiguration(w); } + throw new NotImplementedException("Data storage type " + dataType + " has not been implemented yet."); } } From 1086eacef6139c9adcb75fa3af1a65d30aa5760f Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 24 Nov 2022 19:51:34 -0800 Subject: [PATCH 45/53] Fix for iTrades showing as full --- src/main/java/org/shanerx/tradeshop/utils/Utils.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 3a8b5686..56d47bc9 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -57,13 +57,7 @@ import org.shanerx.tradeshop.utils.relativedirection.LocationOffset; import org.shanerx.tradeshop.utils.relativedirection.RelativeDirection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; +import java.util.*; /** @@ -398,7 +392,7 @@ public Tuple> canExchangeAll(Shop shop, Inventor Inventory shopInventory = null; if (shop.getShopType().equals(ShopType.ITRADE)) { - shopInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getSideList(ShopItemSide.PRODUCT).size() / 9.0) * 9) * multiplier, 54)); + shopInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil((shop.getSideList(ShopItemSide.PRODUCT).size() + shop.getSideList(ShopItemSide.COST).size()) / 9.0) * 9) * multiplier, 54)); while (shopInventory.firstEmpty() != -1) { for (ItemStack item : shop.getSideItemStacks(ShopItemSide.PRODUCT)) { item.setAmount(item.getMaxStackSize()); From 1dbc79cd1fe3772822a8100b0f7c139aa673eb41 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 25 Nov 2022 11:56:48 -0800 Subject: [PATCH 46/53] Fixes for #145 --- src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java | 3 ++- .../org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java | 2 +- src/main/java/org/shanerx/tradeshop/shop/Shop.java | 2 +- src/main/resources/Lang/en-us.yml | 4 ++-- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index ebe4f10d..b45a63ac 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -122,6 +122,7 @@ public Map> getItemSettings() { } public String serialize() { + unloadData(); return new Gson().toJson(this); } @@ -588,7 +589,7 @@ private void loadData() { itemStack = ItemStack.deserialize(serialItemStack); } - if (hasBase64()) { + if (itemStack == null && hasBase64()) { try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(itemStackB64)); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java index fb8fb88a..f592b57b 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java @@ -55,7 +55,7 @@ public enum ShopItemStackSettingKeys { private final ItemStack displayItem; private final Object preConfigDefault; - private static final String defaultKey = "default", userEditableKey = "userEditable"; + private static final String defaultKey = "default", userEditableKey = "user-editable"; ShopItemStackSettingKeys(ItemStack displayItem, Object preConfigDefault) { this.displayItem = displayItem; diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index 48e72ead..be9b69e1 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -961,7 +961,7 @@ private void purgeFromUserFiles() { //------------------------------------------------------------------------------------------------------------------ /** - * Checks if shop has a bade side and fixes if necessary + * Checks if shop has a bad side and fixes if necessary */ public void fixSide(ShopItemSide side) { List ogItems = (side.equals(ShopItemSide.PRODUCT) ? product : cost); diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 0107aa3f..1bd54e80 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -75,9 +75,9 @@ setting: post-comment: "\n" global-options: chest-directions: - pre-comment: "Directions an allowed shop can be from a sign. Multiple directions can be chained together allowing all 26 blocks surrounding a block to be checked. \nTo Chain directions just add a `+` between each one. i.e `Back+Left` or `Back+Left+Up` \nAllowed directions are:\n Up, Down, Left, Right, Back, Front" + pre-comment: "Directions a valid shop chest can be from a sign. Multiple directions can be chained together allowing all 26 blocks surrounding a block to be checked.\n To Chain directions just add a `+` between each one. i.e `Back+Left` or `Back+Left+Up`\n Allowed directions are:\n Up, Down, Left, Right, Back, Front" allowed-shops: - pre-comment: "Inventories to allow for shops. Allowed blocks are:\n Chest, Trapped_Chest, Dropper, Hopper, Dispenser, Shulker, ..." + pre-comment: "Inventories to allow for shops. Allowed blocks are:\n Chest, Trapped_Chest, Dropper, Hopper, Dispenser, Shulker, ..." max-edit-distance: pre-comment: "Max distance a player can be from a shop to edit it" allow-toggle-status: From 450676f48f2c965fad7cd5476b985463513d0069 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 25 Nov 2022 12:45:06 -0800 Subject: [PATCH 47/53] Fixes for #145 --- .../org/shanerx/tradeshop/item/ShopItemStack.java | 11 ++++++----- .../org/shanerx/tradeshop/shop/ShopSettingKeys.java | 8 ++------ 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index b45a63ac..16e93002 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -75,6 +75,7 @@ public ShopItemStack(ItemStack itemStack, HashMap> getItemSettings() { } public String serialize() { - unloadData(); + packData(); return new Gson().toJson(this); } @@ -196,7 +197,7 @@ public int getAmount() { public void setAmount(int amount) { itemStack.setAmount(amount); - unloadData(); + packData(); } public String getItemStackB64() { @@ -572,9 +573,9 @@ public String toString() { */ /** - * Sets the objects Base64 from its {@link ItemStack} + * Converts the {@link ItemStack} to a store-able object */ - private void unloadData() { + private void packData() { if (itemStack != null) { itemStackB64 = null; serialItemStack = itemStack.serialize(); @@ -605,7 +606,7 @@ private void loadData() { } public int getItemSize() { - unloadData(); + packData(); return serialItemStack.toString().length(); } diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopSettingKeys.java b/src/main/java/org/shanerx/tradeshop/shop/ShopSettingKeys.java index 8a8fa69c..0c9d7b8d 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopSettingKeys.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopSettingKeys.java @@ -31,11 +31,7 @@ import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.utils.objects.ObjectHolder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; public enum ShopSettingKeys { @@ -45,7 +41,7 @@ public enum ShopSettingKeys { HOPPER_EXPORT(new ItemStack(Material.DISPENSER), false, false, null), NO_COST(new ItemStack(Material.GOLD_INGOT), false, null, false); - public static final String defaultKey = "default", userEditableKey = "userEditable"; + public static final String defaultKey = "default", userEditableKey = "user-editable"; private final ItemStack displayItem; private final Map defaults; From af98af847b76017c13929039b25c356a2007a7c8 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 25 Nov 2022 14:12:15 -0800 Subject: [PATCH 48/53] Dependency updates --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ee82c084..b2fa5930 100644 --- a/pom.xml +++ b/pom.xml @@ -231,7 +231,7 @@ org.spigotmc spigot-api - 1.18.1-R0.1-SNAPSHOT + 1.19.2-R0.1-SNAPSHOT provided @@ -252,7 +252,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.4.0 + 3.4.1 maven-plugin From 3929ffca05483cca6aa5623b67622efe83ead822 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 25 Nov 2022 14:16:32 -0800 Subject: [PATCH 49/53] Dependency updates --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b2fa5930..3f47a24a 100644 --- a/pom.xml +++ b/pom.xml @@ -245,7 +245,7 @@ de.themoep inventorygui - 1.5-SNAPSHOT + 1.6-SNAPSHOT compile From e4480d2c3056407a5f32f00010f91940b4091f4e Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 25 Nov 2022 15:21:20 -0800 Subject: [PATCH 50/53] Fix for iTrade shops claiming to be full during trades + Spelling --- src/main/java/org/shanerx/tradeshop/utils/Utils.java | 4 ++-- src/main/resources/Lang/en-us.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 56d47bc9..d430b532 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -392,7 +392,7 @@ public Tuple> canExchangeAll(Shop shop, Inventor Inventory shopInventory = null; if (shop.getShopType().equals(ShopType.ITRADE)) { - shopInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil((shop.getSideList(ShopItemSide.PRODUCT).size() + shop.getSideList(ShopItemSide.COST).size()) / 9.0) * 9) * multiplier, 54)); + shopInventory = Bukkit.createInventory(null, Math.min((int) (Math.ceil(shop.getSideList(ShopItemSide.PRODUCT).size() / 9.0) * 9) * multiplier, 54)); while (shopInventory.firstEmpty() != -1) { for (ItemStack item : shop.getSideItemStacks(ShopItemSide.PRODUCT)) { item.setAmount(item.getMaxStackSize()); @@ -436,7 +436,7 @@ public Tuple> canExchangeAll(Shop shop, Inventor shopInventory.removeItem(item); } - if (costItems.size() > 0) { + if (!shop.getShopType().isITrade() && costItems.size() > 0) { //For loop to put cost items in shop inventory for (ItemStack item : costItems) { if (!addItemToInventory(shopInventory, item).isEmpty()) { diff --git a/src/main/resources/Lang/en-us.yml b/src/main/resources/Lang/en-us.yml index 1bd54e80..898e72fc 100644 --- a/src/main/resources/Lang/en-us.yml +++ b/src/main/resources/Lang/en-us.yml @@ -250,7 +250,7 @@ message: pre-comment: "Text to display upon a successful trade:" player-full: default: "&cYour inventory is full, please make room before trading items!" - pre-comment: "Text to display when the players inventory is too full to recieve the trade:" + pre-comment: "Text to display when the players inventory is too full to receive the trade:" player-not-found: default: "&cThat player could not be found." player-only-command: From f194ea52f0c764976d6da2321bf53bfce15e3388 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 25 Nov 2022 16:19:19 -0800 Subject: [PATCH 51/53] Fix for #143 --- .../tradeshop/commands/commandrunners/EditCommand.java | 8 +++----- .../java/org/shanerx/tradeshop/item/ShopItemStack.java | 1 + .../shanerx/tradeshop/item/ShopItemStackSettingKeys.java | 2 +- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java index 002d3f2d..598badcb 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java @@ -25,11 +25,7 @@ package org.shanerx.tradeshop.commands.commandrunners; -import de.themoep.inventorygui.GuiElement; -import de.themoep.inventorygui.GuiElementGroup; -import de.themoep.inventorygui.GuiStateElement; -import de.themoep.inventorygui.InventoryGui; -import de.themoep.inventorygui.StaticGuiElement; +import de.themoep.inventorygui.*; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.TradeShop; @@ -271,6 +267,7 @@ private GuiElement editCostMenu(char slotChar) { costItems.remove(i); } shop.updateSide(ShopItemSide.COST, costItems); + shop.saveShop(); InventoryGui.goBack(pSender); return true; }, "Save Changes")); @@ -314,6 +311,7 @@ private GuiElement editProductMenu(char slotChar) { productItems.remove(i); } shop.updateSide(ShopItemSide.PRODUCT, productItems); + shop.saveShop(); InventoryGui.goBack(pSender); return true; }, "Save Changes")); diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index 16e93002..a11d987b 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -142,6 +142,7 @@ public boolean getShopSettingAsBoolean(ShopItemStackSettingKeys key) { } catch (ClassCastException | NullPointerException ignored) { } } + return (Boolean) key.getDefaultValue().getObject(); } diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java index f592b57b..a4f8fd69 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStackSettingKeys.java @@ -38,7 +38,7 @@ public enum ShopItemStackSettingKeys { //New per shop settings and their default value should be added below and will be added to the shops - COMPARE_DURABILITY(new ItemStack(Material.DAMAGED_ANVIL), 1), // -1 == 'off', 0 == '<=', 1 == '==', 2 == '>=' + COMPARE_DURABILITY(new ItemStack(Material.DAMAGED_ANVIL), 1), // -1 = 'off', 0 = '<=', 1 = '==', 2 = '>=' COMPARE_ENCHANTMENTS(new ItemStack(Material.ENCHANTED_BOOK), true), COMPARE_NAME(new ItemStack(Material.NAME_TAG), true), COMPARE_LORE(new ItemStack(Material.BOOK), true), From c14d12a23ee7815f79264a24e56886caea8c8368 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Fri, 25 Nov 2022 16:58:36 -0800 Subject: [PATCH 52/53] Fix for #143 --- .../tradeshop/commands/commandrunners/GUICommand.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java index 62a346ae..74567967 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java @@ -25,12 +25,7 @@ package org.shanerx.tradeshop.commands.commandrunners; -import de.themoep.inventorygui.GuiElement; -import de.themoep.inventorygui.GuiElementGroup; -import de.themoep.inventorygui.GuiPageElement; -import de.themoep.inventorygui.GuiStateElement; -import de.themoep.inventorygui.InventoryGui; -import de.themoep.inventorygui.StaticGuiElement; +import de.themoep.inventorygui.*; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; @@ -81,7 +76,7 @@ public GUICommand(TradeShop instance, CommandPass command) { //------------------------------------------------------------------------------------------------------------------ protected StaticGuiElement itemSettingMenu(int index, ShopItemSide side, boolean editable) { - ShopItemStack item = (side.equals(ShopItemSide.COST) ? costItems : productItems).get(index).clone(); + ShopItemStack item = (side.equals(ShopItemSide.COST) ? costItems : productItems).get(index); ItemStack tempStack = item.getItemStack(); ItemMeta tempMeta = tempStack.getItemMeta(); List newLore = new ArrayList<>(); From 6d32b2bf8ebc2b406efb7e3e85c5cf62d5040511 Mon Sep 17 00:00:00 2001 From: BoyStijn <34859097+BoyStijn@users.noreply.github.com> Date: Sat, 26 Nov 2022 10:05:08 +0100 Subject: [PATCH 53/53] Removed unused (de)serialization methodes removed java.io.Serializable interface from classes removed serialization method from classes (or changed to `toString` if the method was used) removed deserialization method from classes (or changed to `fromString` if the method was used) --- .../commands/commandrunners/EditCommand.java | 2 +- .../commandrunners/ShopUserCommand.java | 14 ++++----- .../tradeshop/data/storage/DataStorage.java | 2 +- .../storage/Json/JsonShopConfiguration.java | 14 ++++----- .../data/storage/LinkageConfiguration.java | 12 +++---- .../shanerx/tradeshop/item/ShopItemStack.java | 15 ++------- .../tradeshop/player/PlayerSetting.java | 28 +++++++---------- .../shanerx/tradeshop/player/ShopUser.java | 12 +------ .../java/org/shanerx/tradeshop/shop/Shop.java | 31 +++---------------- .../org/shanerx/tradeshop/shop/ShopChest.java | 4 +-- .../org/shanerx/tradeshop/shop/ShopType.java | 10 +----- .../listeners/ShopProtectionListener.java | 4 +-- .../tradeshop/shoplocation/ShopChunk.java | 7 +++-- .../tradeshop/shoplocation/ShopLocation.java | 7 +++-- .../tradeshop/utils/objects/Tuple.java | 8 ++--- 15 files changed, 55 insertions(+), 115 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java index 598badcb..0a6f8233 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/EditCommand.java @@ -79,7 +79,7 @@ public void edit() { return; } - mainMenu = new InventoryGui(plugin, "Edit Menu-" + shop.getShopLocationAsSL().serialize(), MENU_LAYOUT); + mainMenu = new InventoryGui(plugin, "Edit Menu-" + shop.getShopLocationAsSL().toString(), MENU_LAYOUT); mainMenu.setFiller(new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1)); diff --git a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java index 40c19697..86cb6e2f 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/ShopUserCommand.java @@ -149,7 +149,7 @@ public void editUser(ShopRole role, ShopChange change) { if (applyAllOwned) { for (String location : plugin.getDataStorage().loadPlayer(pSender.getUniqueId()).getOwnedShops()) { - ownedShops.add(plugin.getDataStorage().loadShopFromSign(ShopLocation.deserialize(location))); + ownedShops.add(plugin.getDataStorage().loadShopFromSign(ShopLocation.fromString(location))); } } else { ownedShops.add(tempShop); @@ -161,24 +161,24 @@ public void editUser(ShopRole role, ShopChange change) { switch (change) { case REMOVE_USER: if (!shop.getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(target.getUniqueId())) { - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_MISSING.toString()); + updateStatuses.put(shop.getShopLocationAsSL().toString(), UserOperationStatus.FAILED_MISSING.toString()); break eachOwnedShop; } break; case ADD_MANAGER: case ADD_MEMBER: if (shop.getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(target.getUniqueId())) { - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_EXISTING.toString()); + updateStatuses.put(shop.getShopLocationAsSL().toString(), UserOperationStatus.FAILED_EXISTING.toString()); break eachOwnedShop; } else if (shop.getUsers(ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt()) { - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_CAPACITY.toString()); + updateStatuses.put(shop.getShopLocationAsSL().toString(), UserOperationStatus.FAILED_CAPACITY.toString()); break eachOwnedShop; } break; case SET_MANAGER: case SET_MEMBER: if (shop.getUsersExcluding(Collections.singletonList(target.getUniqueId()), ShopRole.MANAGER, ShopRole.MEMBER).size() >= Setting.MAX_SHOP_USERS.getInt()) { - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_CAPACITY.toString()); + updateStatuses.put(shop.getShopLocationAsSL().toString(), UserOperationStatus.FAILED_CAPACITY.toString()); break eachOwnedShop; } break; @@ -205,9 +205,9 @@ public void editUser(ShopRole role, ShopChange change) { } if (success) - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.SUCCESSFUL.toString()); + updateStatuses.put(shop.getShopLocationAsSL().toString(), UserOperationStatus.SUCCESSFUL.toString()); else - updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED.toString()); + updateStatuses.put(shop.getShopLocationAsSL().toString(), UserOperationStatus.FAILED.toString()); } } diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java index 6fe71971..06ccf458 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/DataStorage.java @@ -83,7 +83,7 @@ public int getShopCountInWorld(World world) { if (folder.exists() && folder.listFiles() != null) { for (File file : folder.listFiles()) { if (file.getName().contains(world.getName())) - count += new JsonShopConfiguration(ShopChunk.deserialize(file.getName().replace(".json", ""))).size(); + count += new JsonShopConfiguration(ShopChunk.fromString(file.getName().replace(".json", ""))).size(); } } break; diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java index 1baaad6c..3b45aea0 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonShopConfiguration.java @@ -40,7 +40,7 @@ public class JsonShopConfiguration extends JsonConfiguration implements ShopConf private final ShopChunk chunk; public JsonShopConfiguration(ShopChunk chunk) { - super(chunk.getWorld().getName(), chunk.serialize()); + super(chunk.getWorld().getName(), chunk.toString()); this.chunk = chunk; } @@ -48,7 +48,7 @@ public JsonShopConfiguration(ShopChunk chunk) { public void loadFile() { if (!this.file.exists()) { // If could not find file try with old separators - String oldFile = path + File.separator + chunk.serialize().replace(";;", "_") + ".json"; + String oldFile = path + File.separator + chunk.toString().replace(";;", "_") + ".json"; if (new File(oldFile).exists()) new File(oldFile).renameTo(file); } @@ -57,7 +57,7 @@ public void loadFile() { for (Map.Entry entry : Sets.newHashSet(jsonObj.entrySet())) { if (entry.getKey().contains("l_")) { - jsonObj.add(ShopLocation.deserialize(entry.getKey()).serialize(), entry.getValue()); + jsonObj.add(ShopLocation.fromString(entry.getKey()).toString(), entry.getValue()); jsonObj.remove(entry.getKey()); } } @@ -65,15 +65,15 @@ public void loadFile() { @Override public void save(Shop shop) { - jsonObj.add(shop.getShopLocationAsSL().serialize(), gson.toJsonTree(shop)); + jsonObj.add(shop.getShopLocationAsSL().toString(), gson.toJsonTree(shop)); saveFile(); } @Override public void remove(ShopLocation loc) { - if (jsonObj.has(loc.serialize())) - jsonObj.remove(loc.serialize()); + if (jsonObj.has(loc.toString())) + jsonObj.remove(loc.toString()); saveFile(); } @@ -81,7 +81,7 @@ public void remove(ShopLocation loc) { @Override public Shop load(ShopLocation loc) { Shop shop; - String locStr = loc.serialize(); + String locStr = loc.toString(); if (!jsonObj.has(locStr)) { return null; diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java index b82435e5..53d9a330 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/LinkageConfiguration.java @@ -41,8 +41,8 @@ public interface LinkageConfiguration { Map getLinkageData(); default ShopLocation getLinkedShop(ShopLocation chestLocation) { - String loc = chestLocation.serialize(); - return getLinkageData().containsKey(loc) ? ShopLocation.deserialize(getLinkageData().get(chestLocation.serialize())) : null; + String loc = chestLocation.toString(); + return getLinkageData().containsKey(loc) ? ShopLocation.fromString(getLinkageData().get(chestLocation.toString())) : null; } default int size() { @@ -50,10 +50,10 @@ default int size() { } default void addLinkage(ShopLocation chestLocation, ShopLocation shopLocation) { - if (getLinkageData().containsKey(chestLocation.serialize())) - getLinkageData().replace(chestLocation.serialize(), shopLocation.serialize()); + if (getLinkageData().containsKey(chestLocation.toString())) + getLinkageData().replace(chestLocation.toString(), shopLocation.toString()); else - getLinkageData().put(chestLocation.serialize(), shopLocation.serialize()); + getLinkageData().put(chestLocation.toString(), shopLocation.toString()); save(); } @@ -74,7 +74,7 @@ default void removeChest(ShopLocation chestLocation) { default void removeShop(ShopLocation shopLocation) { List removeChests = new ArrayList<>(); - String shopLoc = shopLocation.serialize(); + String shopLoc = shopLocation.toString(); getLinkageData().forEach((key, value) -> { if (value.equals(shopLoc)) diff --git a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java index a11d987b..9899b48b 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -32,6 +32,7 @@ import com.google.gson.annotations.SerializedName; import net.md_5.bungee.api.ChatColor; import org.apache.commons.lang.WordUtils; +import org.bukkit.Bukkit; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.block.ShulkerBox; @@ -46,13 +47,12 @@ import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Objects; -public class ShopItemStack implements Serializable, Cloneable { +public class ShopItemStack implements Cloneable { private transient ItemStack itemStack; private transient Debug debugger; @@ -122,17 +122,6 @@ public Map> getItemSettings() { return itemSettings; } - public String serialize() { - packData(); - return new Gson().toJson(this); - } - - public static ShopItemStack deserialize(String serialized) { - ShopItemStack item = new Gson().fromJson(serialized, ShopItemStack.class); - item.loadData(); - item.buildMap(); - return item; - } public boolean getShopSettingAsBoolean(ShopItemStackSettingKeys key) { if (key.isUserEditable()) { diff --git a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java index 98f3e00f..c7d3252a 100644 --- a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java +++ b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java @@ -46,7 +46,7 @@ import java.util.Set; import java.util.UUID; -public class PlayerSetting implements Serializable { +public class PlayerSetting { private transient UUID uuid; private final String uuidString; @@ -80,12 +80,6 @@ public PlayerSetting(UUID playerUUID) { load(); } - public static PlayerSetting deserialize(String serialized) { - PlayerSetting playerSetting = new Gson().fromJson(serialized, PlayerSetting.class); - playerSetting.load(); - return playerSetting; - } - public boolean isAdminEnabled() { return adminEnabled; } @@ -108,16 +102,16 @@ public Set getOwnedShops() { public void addShop(Shop shop) { if (shop.getOwner().getUUID().equals(uuid) && - !ownedShops.contains(shop.getShopLocationAsSL().serialize())) - ownedShops.add(shop.getShopLocationAsSL().serialize()); + !ownedShops.contains(shop.getShopLocationAsSL().toString())) + ownedShops.add(shop.getShopLocationAsSL().toString()); else if (shop.getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(uuid) && - !ownedShops.contains(shop.getShopLocationAsSL().serialize())) - staffShops.add(shop.getShopLocationAsSL().serialize()); + !ownedShops.contains(shop.getShopLocationAsSL().toString())) + staffShops.add(shop.getShopLocationAsSL().toString()); } public void removeShop(Shop shop) { - ownedShops.remove(shop.getShopLocationAsSL().serialize()); - staffShops.remove(shop.getShopLocationAsSL().serialize()); + ownedShops.remove(shop.getShopLocationAsSL().toString()); + staffShops.remove(shop.getShopLocationAsSL().toString()); } public void removeShop(String shop) { @@ -159,7 +153,7 @@ public String getInvolvedStatusesString() { if (getOwnedShops().size() > 0) { getOwnedShops().forEach(s -> { try { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.fromString(s)); if (shop == null) { nullShops.add(s); } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { @@ -177,7 +171,7 @@ public String getInvolvedStatusesString() { if (getStaffShops().size() > 0) { getStaffShops().forEach(s -> { try { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.fromString(s)); if (shop == null) { nullShops.add(s); } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { @@ -206,7 +200,7 @@ public InventoryGui getInvolvedStatusesInventory() { if (getOwnedShops().size() > 0) { getOwnedShops().forEach(s -> { try { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.fromString(s)); if (shop == null) { nullShops.add(s); } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { @@ -232,7 +226,7 @@ public InventoryGui getInvolvedStatusesInventory() { if (getStaffShops().size() > 0) { getStaffShops().forEach(s -> { try { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.fromString(s)); if (shop == null) { nullShops.add(s); } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { diff --git a/src/main/java/org/shanerx/tradeshop/player/ShopUser.java b/src/main/java/org/shanerx/tradeshop/player/ShopUser.java index d1b02eb3..ae775dcc 100644 --- a/src/main/java/org/shanerx/tradeshop/player/ShopUser.java +++ b/src/main/java/org/shanerx/tradeshop/player/ShopUser.java @@ -37,7 +37,7 @@ import java.util.UUID; @SuppressWarnings("unused") -public class ShopUser implements Serializable { +public class ShopUser { private transient OfflinePlayer player; @SerializedName("player") @@ -56,12 +56,6 @@ public ShopUser(UUID pUUID, ShopRole role) { this.role = role; } - public static ShopUser deserialize(String serialized) { - ShopUser shopUser = new Gson().fromJson(serialized, ShopUser.class); - shopUser.player = Bukkit.getOfflinePlayer(UUID.fromString(shopUser.playerUUID)); - return shopUser; - } - public OfflinePlayer getPlayer() { fix(); return player; @@ -85,10 +79,6 @@ private void fix() { } } - public String serialize() { - return new Gson().toJson(this); - } - public ItemStack getHead() { ItemStack userHead = new ItemStack(Material.PLAYER_HEAD); SkullMeta userMeta = (SkullMeta) userHead.getItemMeta(); diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index be9b69e1..df6171c0 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -54,7 +54,7 @@ import java.util.*; import java.util.stream.Collectors; -public class Shop implements Serializable { +public class Shop { private ShopUser owner; private Set managers, members; @@ -138,20 +138,6 @@ public Shop(Location location, ShopType shopType, ShopUser owner) { this(new Tuple<>(location, null), shopType, owner, new Tuple<>(null, null), new Tuple<>(null, null)); } - /** - * Deserializes the object to Json using Gson - * - * @param serialized Shop GSON to be deserialized - * - * @return Shop object from file - */ - public static Shop deserialize(String serialized) { - Shop shop = new Gson().fromJson(serialized, Shop.class); - shop.fixAfterLoad(); - - return shop; - } - /** * Loads a shop from file and returns the Shop object * @@ -253,15 +239,6 @@ public int getAvailableTrades() { return availableTrades; } - /** - * Serializes the object to Json using Gson - * - * @return serialized string - */ - public String serialize() { - return new Gson().toJson(this); - } - /** * Returns the shop signs location as a ShopLocation * @@ -311,11 +288,11 @@ public void fixAfterLoad() { public String toDebug() { StringBuilder sb = new StringBuilder(); sb.append("Shop Debug: \n"); - sb.append("Shop Chunk: ").append(new ShopChunk(shopLoc.getChunk()).serialize()).append("\n"); - sb.append("Sign Location: ").append(shopLoc.serialize()).append("\n"); + sb.append("Shop Chunk: ").append(new ShopChunk(shopLoc.getChunk()).toString()).append("\n"); + sb.append("Sign Location: ").append(shopLoc).append("\n"); sb.append("Shop Type: ").append((isMissingItems() ? Setting.SHOP_INCOMPLETE_COLOUR : Setting.SHOP_GOOD_COLOUR).getString() + shopType.toHeader()).append("\n"); sb.append("Shop Status: ").append(status.getLine()).append("\n"); - sb.append("Storage Location: ").append(hasStorage() ? getInventoryLocationAsSL().serialize() : "N/A").append("\n"); + sb.append("Storage Location: ").append(hasStorage() ? getInventoryLocationAsSL().toString() : "N/A").append("\n"); sb.append("Storage Type: ").append(hasStorage() ? getStorage().getType().toString() : "N/A").append("\n"); sb.append("Owner: ").append(owner.getName()).append(" | ").append(owner.getUUID()).append("\n"); sb.append("Managers: ").append(managers.isEmpty() ? "N/A" : managers.size()).append("\n"); diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java index 45a8bed4..9731c885 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java @@ -224,7 +224,7 @@ public void loadFromName() { chestData.forEach((k, v) -> plugin.getDebugger().log(k + " = " + v, DebugLevels.PROTECTION)); try { - shopSign = ShopLocation.deserialize(chestData.get("Sign")); + shopSign = ShopLocation.fromString(chestData.get("Sign")); } catch (IllegalWorldException e) { shopSign = new ShopLocation(e.getLoc().getLocation(chest.getWorld())); } @@ -252,7 +252,7 @@ public String getName() { StringBuilder sb = new StringBuilder(); sb.append("$ ^Sign"); sb.append(titleSeparator); - sb.append(shopSign.serialize()); + sb.append(shopSign.toString()); sb.append("$ ^Owner"); sb.append(titleSeparator); sb.append(owner.toString()); diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopType.java b/src/main/java/org/shanerx/tradeshop/shop/ShopType.java index 3b54008e..4ea28947 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopType.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopType.java @@ -38,7 +38,7 @@ import java.io.Serializable; -public enum ShopType implements Serializable { +public enum ShopType { TRADE(Permissions.CREATE), @@ -82,10 +82,6 @@ public static ShopType getType(Sign s) { return null; } - public static ShopType deserialize(String serialized) { - return new Gson().fromJson(serialized, ShopType.class); - } - @Override public String toString() { return getKey().getString(); @@ -105,10 +101,6 @@ public boolean checkPerm(Player pl) { return Permissions.hasPermission(pl, perm); } - public String serialize() { - return new Gson().toJson(this); - } - public boolean isTrade() { return this.equals(TRADE); } diff --git a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java index 17669242..352a6dc3 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java +++ b/src/main/java/org/shanerx/tradeshop/shop/listeners/ShopProtectionListener.java @@ -129,7 +129,7 @@ public void onInventoryMoveItem(InventoryMoveItemEvent event) { } plugin.getDebugger().log("ShopProtectionListener: Triggered > " + (fromHopper ? "FROM_HOPPER" : "TO_HOPPER"), DebugLevels.PROTECTION); - plugin.getDebugger().log("ShopProtectionListener: Shop Location as SL > " + shop.getInventoryLocationAsSL().serialize(), DebugLevels.PROTECTION); + plugin.getDebugger().log("ShopProtectionListener: Shop Location as SL > " + shop.getInventoryLocationAsSL().toString(), DebugLevels.PROTECTION); plugin.getDebugger().log("ShopProtectionListener: checked hopper setting > " + shop.getShopType().name() + "SHOP_HOPPER_EXPORT", DebugLevels.PROTECTION); HopperShopAccessEvent hopperEvent = new HopperShopAccessEvent( shop, @@ -367,7 +367,7 @@ public void onBlockPlace(BlockPlaceEvent event) { } private void scheduleShopDelayUpdate(Shop shop, Long delay) { - plugin.getDebugger().log("Shop Being updated from ProtectionListener...\n " + shop.getShopLocationAsSL().serialize(), DebugLevels.PROTECTION); + plugin.getDebugger().log("Shop Being updated from ProtectionListener...\n " + shop.getShopLocationAsSL().toString(), DebugLevels.PROTECTION); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { diff --git a/src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java index dfc3c8a2..266d40c6 100644 --- a/src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java @@ -31,7 +31,7 @@ import java.io.Serializable; -public class ShopChunk implements Serializable { +public class ShopChunk { final private String div = ";;"; private final World world; @@ -53,7 +53,7 @@ public ShopChunk(Chunk c) { chunk = c; } - public static ShopChunk deserialize(String loc) { + public static ShopChunk fromString(String loc) { if (loc.startsWith("c")) { String[] locA = loc.contains(";;") ? loc.split(";;") : loc.split("_"); //Keep same as div World world = Bukkit.getWorld(locA[1]); @@ -67,7 +67,8 @@ public static ShopChunk deserialize(String loc) { return null; } - public String serialize() { + @Override + public String toString() { return "c" + div + world.getName() + div + x + div + z; } diff --git a/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java index f7fe073e..b73b4a7c 100644 --- a/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java @@ -32,7 +32,7 @@ import java.io.Serializable; -public class ShopLocation implements Serializable { +public class ShopLocation { final private String div = "::"; private transient World world; @@ -57,7 +57,7 @@ public ShopLocation(Location loc) { this.z = loc.getZ(); } - public static ShopLocation deserialize(String loc) { + public static ShopLocation fromString(String loc) { if (loc.startsWith("l")) { String[] locA = loc.contains("::") ? loc.split("::") : loc.split("_"); //Keep same as div double x = Double.parseDouble(locA[2]), y = Double.parseDouble(locA[3]), z = Double.parseDouble(locA[4]); @@ -77,7 +77,8 @@ public static ShopLocation deserialize(String loc) { return null; } - public String serialize() { + @Override + public String toString() { return "l" + div + world.getName() + div + x + div + y + div + z; } diff --git a/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java b/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java index 181e9c3a..aa5e9686 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java @@ -30,7 +30,7 @@ import java.io.Serializable; -public class Tuple implements Serializable { +public class Tuple { @SerializedName("right") private R r; @@ -58,12 +58,8 @@ public L getLeft() { return l; } - public String serialize() { - return new Gson().toJson(this); - } - @Override public String toString() { - return serialize(); + return new Gson().toJson(this); } } \ No newline at end of file