From 72d8d0c4def27601345a278f031065986ea1bb03 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Thu, 24 Sep 2020 18:45:17 -0700 Subject: [PATCH 1/4] Creation of and switch to using generic DataStorage object for managing data --- pom.xml | 2 +- .../java/org/shanerx/tradeshop/TradeShop.java | 10 +- .../tradeshop/commands/CommandRunner.java | 16 +- .../shanerx/tradeshop/enumys/DebugLevels.java | 2 +- .../shanerx/tradeshop/enumys/PlayerData.java | 47 +++++ .../org/shanerx/tradeshop/enumys/Setting.java | 1 + .../shanerx/tradeshop/enumys/ShopSign.java | 188 +++++++++--------- .../listeners/JoinEventListener.java | 18 +- .../listeners/ShopCreateListener.java | 5 +- .../listeners/ShopTradeListener.java | 12 +- .../org/shanerx/tradeshop/objects/Debug.java | 4 +- .../tradeshop/objects/PlayerSetting.java | 69 +++++++ .../org/shanerx/tradeshop/objects/Shop.java | 9 +- .../tradeshop/objects/ShopItemStack.java | 4 + .../tradeshop/objects/ShopLocation.java | 5 + .../tradeshop/utils/ItemSerializer.java | 93 --------- .../org/shanerx/tradeshop/utils/Utils.java | 2 +- .../tradeshop/utils/data/DataStorage.java | 150 ++++++++++++++ .../tradeshop/utils/data/DataType.java | 31 +++ .../utils/{ => data}/JsonConfiguration.java | 46 ++--- 20 files changed, 450 insertions(+), 264 deletions(-) create mode 100644 src/main/java/org/shanerx/tradeshop/enumys/PlayerData.java create mode 100644 src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java delete mode 100644 src/main/java/org/shanerx/tradeshop/utils/ItemSerializer.java create mode 100644 src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java create mode 100644 src/main/java/org/shanerx/tradeshop/utils/data/DataType.java rename src/main/java/org/shanerx/tradeshop/utils/{ => data}/JsonConfiguration.java (85%) diff --git a/pom.xml b/pom.xml index fb3e3189..e72804c0 100644 --- a/pom.xml +++ b/pom.xml @@ -31,7 +31,7 @@ org.shanerx tradeshop - 2.2.2-STABLE + 2.3.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 2d71e89c..19dd42d8 100644 --- a/src/main/java/org/shanerx/tradeshop/TradeShop.java +++ b/src/main/java/org/shanerx/tradeshop/TradeShop.java @@ -40,6 +40,8 @@ import org.shanerx.tradeshop.objects.ListManager; import org.shanerx.tradeshop.utils.BukkitVersion; import org.shanerx.tradeshop.utils.Updater; +import org.shanerx.tradeshop.utils.data.DataStorage; +import org.shanerx.tradeshop.utils.data.DataType; public class TradeShop extends JavaPlugin { @@ -49,9 +51,10 @@ public class TradeShop extends JavaPlugin { private final int bStatsPluginID = 1690; private ListManager lists; + private DataStorage dataStorage; + private BukkitVersion version; private ShopSign signs; - private ShopStorage storages; private Metrics metrics; @@ -81,6 +84,7 @@ public void onEnable() { signs = new ShopSign(); storages = new ShopStorage(); lists = new ListManager(); + dataStorage = new DataStorage(DataType.valueOf(Setting.DATA_STORAGE_TYPE.getString().toUpperCase())); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new JoinEventListener(this), this); @@ -137,4 +141,8 @@ public Updater getUpdater() { public Debug getDebugger() { return debugger; } + + public DataStorage getDataStorage() { + return dataStorage; + } } diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java index 2393a35c..3d2bd48a 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java @@ -40,17 +40,12 @@ import org.shanerx.tradeshop.framework.events.PlayerShopChangeEvent; import org.shanerx.tradeshop.framework.events.PlayerShopCloseEvent; import org.shanerx.tradeshop.framework.events.PlayerShopOpenEvent; -import org.shanerx.tradeshop.objects.Shop; -import org.shanerx.tradeshop.objects.ShopChest; -import org.shanerx.tradeshop.objects.ShopItemStack; -import org.shanerx.tradeshop.objects.ShopUser; -import org.shanerx.tradeshop.utils.JsonConfiguration; +import org.shanerx.tradeshop.objects.*; import org.shanerx.tradeshop.utils.ObjectHolder; import org.shanerx.tradeshop.utils.Utils; import java.util.ArrayList; import java.util.List; -import java.util.Map; public class CommandRunner extends Utils { @@ -826,11 +821,10 @@ public void multi() { return; } - JsonConfiguration json = new JsonConfiguration(pSender.getUniqueId()); - Map data = json.loadPlayer(); + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); if (command.argsSize() == 1) { - sendMessage(Message.MULTI_AMOUNT.getPrefixed().replaceAll("%amount%", String.valueOf(data.get("multi")))); + sendMessage(Message.MULTI_AMOUNT.getPrefixed().replaceAll("%amount%", String.valueOf(playerSetting.getObject(PlayerData.MULTI)))); } else { int amount = Setting.MULTI_TRADE_DEFAULT.getInt(); @@ -842,8 +836,8 @@ public void multi() { else if (amount > Setting.MULTI_TRADE_MAX.getInt()) amount = Setting.MULTI_TRADE_MAX.getInt(); - data.put("multi", amount); - json.savePlayer(data); + playerSetting.setObject(PlayerData.MULTI, amount); + plugin.getDataStorage().savePlayer(playerSetting); sendMessage(Message.MULTI_UPDATE.getPrefixed().replaceAll("%amount%", String.valueOf(amount))); } diff --git a/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java b/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java index 950e9f03..6c4633bf 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java +++ b/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java @@ -57,7 +57,7 @@ public Level getLogLevel() { } public static int levels() { - return values().length - 1 > 32 ? 32 : values().length - 1; + return Math.min(values().length - 1, 32); } public static int maxValue() { diff --git a/src/main/java/org/shanerx/tradeshop/enumys/PlayerData.java b/src/main/java/org/shanerx/tradeshop/enumys/PlayerData.java new file mode 100644 index 00000000..6de19b6c --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/enumys/PlayerData.java @@ -0,0 +1,47 @@ +/* + * + * 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.enumys; + +public enum PlayerData { + TYPE("type", 0), + MULTI("multi", Setting.MULTI_TRADE_DEFAULT.getInt()); + + String path; + int defaultValue; + + PlayerData(String path, int defaultValue) { + this.path = path; + this.defaultValue = defaultValue; + } + + public String getPath() { + return path; + } + + public int getDefaultValue() { + return defaultValue; + } +} diff --git a/src/main/java/org/shanerx/tradeshop/enumys/Setting.java b/src/main/java/org/shanerx/tradeshop/enumys/Setting.java index b77fd5a9..d512be64 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/Setting.java +++ b/src/main/java/org/shanerx/tradeshop/enumys/Setting.java @@ -46,6 +46,7 @@ public enum Setting { CONFIG_VERSION(SettingSectionKeys.NONE, "config-version", 1.1, "", "\n"), // System Options + DATA_STORAGE_TYPE(SettingSectionKeys.SYSTEM_OPTIONS, "data-storage-type", "FLATFILE", "How would you like your servers data stored? (FLATFILE, SQLITE)"), ENABLE_DEBUG(SettingSectionKeys.SYSTEM_OPTIONS, "enable-debug", 0, "What debug code should be run. this will add significant amounts of spam to the console/log, generally not used unless requested by Devs (must be a whole number)"), CHECK_UPDATES(SettingSectionKeys.SYSTEM_OPTIONS, "check-updates", true, "Should we check for updates when the server starts"), ALLOW_METRICS(SettingSectionKeys.SYSTEM_OPTIONS, "allow-metrics", true, "Allow us to connect anonymous metrics so we can see how our plugin is being used to better develop it", "\n"), diff --git a/src/main/java/org/shanerx/tradeshop/enumys/ShopSign.java b/src/main/java/org/shanerx/tradeshop/enumys/ShopSign.java index 48159497..b21f1a56 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/ShopSign.java +++ b/src/main/java/org/shanerx/tradeshop/enumys/ShopSign.java @@ -33,103 +33,105 @@ import java.util.Arrays; import java.util.List; +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", ""); + + private List minVer = Arrays.asList(new Integer[3]), maxVer = Arrays.asList(new Integer[3]); + private boolean hasMin = true, hasMax = true; + + Signs(String minVersion, String maxVersion) { + if (minVersion.equalsIgnoreCase("")) + hasMin = false; + + if (maxVersion.equalsIgnoreCase("")) + hasMax = false; + + if (hasMin) { + String[] minVerArray = minVersion.split("[.]"); + for (int i = 0; i < minVerArray.length; i++) { + minVer.set(i, Integer.parseInt(minVerArray[i])); + } + } + + if (hasMax) { + String[] maxVerArray = maxVersion.split("[.]"); + for (int i = 0; i < maxVerArray.length; i++) { + maxVer.set(i, Integer.parseInt(maxVerArray[i])); + } + } + } + + public boolean hasMinVersion() { + return hasMin; + } + + public boolean hasMaxVersion() { + return hasMax; + } + + public List getMinVer() { + return minVer; + } + + public List getMaxVer() { + return maxVer; + } + + public String getMinVersionAsString() { + return hasMinVersion() ? getMinVer().get(0) + "." + getMinVer().get(1) + "." + getMinVer().get(2) : "None"; + } + + public String getMaxVersionAsString() { + return hasMaxVersion() ? getMaxVer().get(0) + "." + getMaxVer().get(1) + "." + getMaxVer().get(2) : "None"; + } + +} + public class ShopSign extends Utils { - private BukkitVersion version = new BukkitVersion(); - private ArrayList signTypes = new ArrayList<>(); + private BukkitVersion version = new BukkitVersion(); + private ArrayList signTypes = new ArrayList<>(); - public ShopSign() { - for (Signs type : Signs.values()) { - boolean pass = true; + 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); - if (type.hasMinVersion() && version.isBelow(type.getMinVer().get(0), type.getMinVer().get(1), type.getMinVer().get(2))) { - pass = false; - } else if (type.hasMaxVersion() && version.isAbove(type.getMaxVer().get(0), type.getMaxVer().get(1), type.getMaxVer().get(2))) { - pass = false; - } - - if (pass) - signTypes.add(Material.matchMaterial(type.toString())); - } - - - } - - public List getSignTypes() { - return signTypes; - } - - 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", ""); - - private List minVer = Arrays.asList(new Integer[3]), maxVer = Arrays.asList(new Integer[3]); - private boolean hasMin = true, hasMax = true; - - Signs(String minVersion, String maxVersion) { - if (minVersion.equalsIgnoreCase("")) - hasMin = false; - - if (maxVersion.equalsIgnoreCase("")) - hasMax = false; - - if (hasMin) { - String[] minVerArray = minVersion.split("[.]"); - for (int i = 0; i < minVerArray.length; i++) { - minVer.set(i, Integer.parseInt(minVerArray[i])); - } - } - - if (hasMax) { - String[] maxVerArray = maxVersion.split("[.]"); - for (int i = 0; i < maxVerArray.length; i++) { - maxVer.set(i, Integer.parseInt(maxVerArray[i])); - } - } - } - - public boolean hasMinVersion() { - return hasMin; - } - - public boolean hasMaxVersion() { - return hasMax; - } - - public List getMinVer() { - return minVer; - } - - public List getMaxVer() { - return maxVer; - } - - public String getMinVersionAsString() { - return hasMinVersion() ? getMinVer().get(0) + "." + getMinVer().get(1) + "." + getMinVer().get(2) : "None"; - } - - public String getMaxVersionAsString() { - return hasMaxVersion() ? getMaxVer().get(0) + "." + getMaxVer().get(1) + "." + getMaxVer().get(2) : "None"; - } - - } -} + if (type.hasMinVersion() && version.isBelow(type.getMinVer().get(0), type.getMinVer().get(1), type.getMinVer().get(2))) { + pass = false; + } else if (type.hasMaxVersion() && version.isAbove(type.getMaxVer().get(0), type.getMaxVer().get(1), type.getMaxVer().get(2))) { + pass = false; + } + + if (pass) + signTypes.add(Material.matchMaterial(type.toString())); + } + + + } + + public List getSignTypes() { + return signTypes; + } + + +} \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java b/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java index d1b22342..60f2e770 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java +++ b/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java @@ -33,15 +33,10 @@ import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.enumys.Message; import org.shanerx.tradeshop.enumys.Permissions; -import org.shanerx.tradeshop.enumys.Setting; import org.shanerx.tradeshop.utils.BukkitVersion; -import org.shanerx.tradeshop.utils.JsonConfiguration; import org.shanerx.tradeshop.utils.Updater; import org.shanerx.tradeshop.utils.Utils; -import java.util.HashMap; -import java.util.Map; - public class JoinEventListener extends Utils implements Listener { private TradeShop plugin; @@ -54,18 +49,7 @@ public JoinEventListener(TradeShop instance) { public void onJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); - JsonConfiguration json = new JsonConfiguration(player.getUniqueId()); - Map data = json.loadPlayer(); - - if (data == null) - data = new HashMap<>(); - - if (!data.containsKey("type")) - data.put("type", 0); - - data.put("multi", Setting.MULTI_TRADE_DEFAULT.getInt()); - - json.savePlayer(data); + plugin.getDataStorage().savePlayer(plugin.getDataStorage().loadPlayer(player.getUniqueId())); if (player.hasPermission(Permissions.ADMIN.getPerm())) { BukkitVersion ver = new BukkitVersion(); diff --git a/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java b/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java index d46232dc..41920278 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java +++ b/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java @@ -43,7 +43,6 @@ import org.shanerx.tradeshop.objects.Shop; import org.shanerx.tradeshop.objects.ShopChest; import org.shanerx.tradeshop.objects.ShopUser; -import org.shanerx.tradeshop.utils.JsonConfiguration; import org.shanerx.tradeshop.utils.Tuple; import org.shanerx.tradeshop.utils.Utils; @@ -79,9 +78,7 @@ public void onSignChange(SignChangeEvent event) { return; } - JsonConfiguration chunk = new JsonConfiguration(shopSign.getChunk()); - - if (Setting.MAX_SHOPS_PER_CHUNK.getInt() <= chunk.getShopCount() + 1) { + if (Setting.MAX_SHOPS_PER_CHUNK.getInt() <= plugin.getDataStorage().getShopCountInChunk(shopSign.getChunk()) + 1) { failedSign(event, shopType, Message.TOO_MANY_CHESTS); return; } diff --git a/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java index d8bd501b..a69778c4 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java @@ -38,6 +38,7 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.enumys.Message; +import org.shanerx.tradeshop.enumys.PlayerData; import org.shanerx.tradeshop.enumys.Setting; import org.shanerx.tradeshop.enumys.ShopType; import org.shanerx.tradeshop.framework.events.PlayerTradeEvent; @@ -45,11 +46,9 @@ import org.shanerx.tradeshop.objects.Shop; import org.shanerx.tradeshop.objects.ShopItemStack; import org.shanerx.tradeshop.objects.ShopLocation; -import org.shanerx.tradeshop.utils.JsonConfiguration; import org.shanerx.tradeshop.utils.Utils; import java.util.ArrayList; -import java.util.Map; public class ShopTradeListener extends Utils implements Listener { @@ -70,8 +69,7 @@ public void onBlockInteract(PlayerInteractEvent e) { return; } - JsonConfiguration json = new JsonConfiguration(s.getChunk()); - shop = json.loadShop(new ShopLocation(s.getLocation())); + shop = plugin.getDataStorage().loadShopFromSign(new ShopLocation(s.getLocation())); if (shop == null) { s.setLine(0, ""); @@ -127,9 +125,7 @@ public void onBlockInteract(PlayerInteractEvent e) { } if (buyer.isSneaking() && Setting.ALLOW_MULTI_TRADE.getBoolean()) { - JsonConfiguration pJson = new JsonConfiguration(buyer.getUniqueId()); - Map data = pJson.loadPlayer(); - multiplier = data.get("multi"); + multiplier = plugin.getDataStorage().loadPlayer(buyer.getUniqueId()).getObject(PlayerData.MULTI); } @@ -138,7 +134,7 @@ public void onBlockInteract(PlayerInteractEvent e) { if (event.isCancelled()) return; e.setCancelled(true); - shop = json.loadShop(new ShopLocation(s.getLocation())); + shop = plugin.getDataStorage().loadShopFromSign(new ShopLocation(s.getLocation())); switch (canExchangeAll(shop, buyer.getInventory(), multiplier, e.getAction())) { case SHOP_NO_PRODUCT: diff --git a/src/main/java/org/shanerx/tradeshop/objects/Debug.java b/src/main/java/org/shanerx/tradeshop/objects/Debug.java index 0f5c4815..4c0c21c7 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/Debug.java +++ b/src/main/java/org/shanerx/tradeshop/objects/Debug.java @@ -61,8 +61,10 @@ public void reload() { } public void log(String message, DebugLevels level) { - if (level.getPosition() - 1 != -1 && binaryDebugLevel.charAt(level.getPosition() - 1) == '1') { + if (level.getPosition() > 0 && binaryDebugLevel.charAt(level.getPosition() - 1) == '1') { Bukkit.getLogger().log(level.getLogLevel(), PREFIX.replace("%level%", level.getPrefix()) + message); + } else if (level == DebugLevels.DISABLED) { + Bukkit.getLogger().log(level.getLogLevel(), PREFIX.replace(" Debug%level%", "") + message); } } } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java b/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java new file mode 100644 index 00000000..03ea4cbe --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.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.objects; + +import org.shanerx.tradeshop.enumys.PlayerData; + +import java.util.Map; +import java.util.UUID; + +public class PlayerSetting { + + private transient UUID uuid; + private transient Map data; + + public PlayerSetting(UUID playerUUID, Map data) { + this.uuid = playerUUID; + this.data = data; + for (PlayerData key : PlayerData.values()) { + if (!data.containsKey(key.getPath())) + data.putIfAbsent(key.getPath(), key.getDefaultValue()); + else + data.replace(key.getPath(), key.getDefaultValue()); + } + } + + public Integer getObject(PlayerData key) { + Integer value = data.get(key.getPath()); + return value != null ? value : key.getDefaultValue(); + } + + public void setObject(PlayerData key, Integer value) { + if (!data.containsKey(key.getPath())) + data.putIfAbsent(key.getPath(), value); + else + data.replace(key.getPath(), value); + } + + public UUID getUuid() { + return uuid; + } + + public Map getData() { + return data; + } +} + diff --git a/src/main/java/org/shanerx/tradeshop/objects/Shop.java b/src/main/java/org/shanerx/tradeshop/objects/Shop.java index 0f021912..69c53cf0 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/objects/Shop.java @@ -38,7 +38,6 @@ import org.shanerx.tradeshop.enumys.ShopRole; import org.shanerx.tradeshop.enumys.ShopStatus; import org.shanerx.tradeshop.enumys.ShopType; -import org.shanerx.tradeshop.utils.JsonConfiguration; import org.shanerx.tradeshop.utils.Tuple; import org.shanerx.tradeshop.utils.Utils; @@ -147,7 +146,7 @@ public static Shop deserialize(String serialized) { * @return The shop from file */ public static Shop loadShop(ShopLocation loc) { - return new JsonConfiguration(loc.getLocation().getChunk()).loadShop(loc); + return new Utils().plugin.getDataStorage().loadShopFromSign(loc); } /** @@ -609,7 +608,7 @@ public List getUsersUUID() { * Saves the shop too file */ public void saveShop() { - new JsonConfiguration(shopLoc.getLocation().getChunk()).saveShop(this); + new Utils().plugin.getDataStorage().saveShop(this); } /** @@ -805,9 +804,7 @@ public void setStatus(ShopStatus newStatus) { * Removes this shop from file */ public void remove() { - JsonConfiguration json = new JsonConfiguration(shopLoc.getLocation().getChunk()); - - json.removeShop(shopLoc); + new Utils().plugin.getDataStorage().removeShop(this); } /** diff --git a/src/main/java/org/shanerx/tradeshop/objects/ShopItemStack.java b/src/main/java/org/shanerx/tradeshop/objects/ShopItemStack.java index c5d6a904..70912c7a 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/objects/ShopItemStack.java @@ -161,6 +161,10 @@ public String getItemStackB64() { return itemStackB64; } + public boolean hasBase64() { + return itemStackB64 != null && !itemStackB64.isEmpty(); + } + public boolean isCompareBookAuthor() { return compareBookAuthor; } diff --git a/src/main/java/org/shanerx/tradeshop/objects/ShopLocation.java b/src/main/java/org/shanerx/tradeshop/objects/ShopLocation.java index bfcb74b3..5ef21d0b 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ShopLocation.java +++ b/src/main/java/org/shanerx/tradeshop/objects/ShopLocation.java @@ -26,6 +26,7 @@ package org.shanerx.tradeshop.objects; import org.bukkit.Bukkit; +import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; @@ -96,6 +97,10 @@ public double getZ() { return z; } + public Chunk getChunk() { + return getLocation().getChunk(); + } + public Location getLocation() { return new Location(world, x, y, z); } diff --git a/src/main/java/org/shanerx/tradeshop/utils/ItemSerializer.java b/src/main/java/org/shanerx/tradeshop/utils/ItemSerializer.java deleted file mode 100644 index ab92949b..00000000 --- a/src/main/java/org/shanerx/tradeshop/utils/ItemSerializer.java +++ /dev/null @@ -1,93 +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 org.bukkit.inventory.ItemStack; -import org.bukkit.util.io.BukkitObjectInputStream; -import org.bukkit.util.io.BukkitObjectOutputStream; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -public class ItemSerializer { - - /** - * - * Original code from https://gist.github.com/graywolf336/8153678 - * Tweaked for use with single itemstacks - * - */ - - - /** - * A method to serialize an {@link ItemStack} array to Base64 String. - * - * @param item to turn into a Base64 String. - * @return Base64 string of the items. - * @throws IllegalStateException if ItemStack cannot be saved - */ - public static String itemStackArrayToBase64(ItemStack item) throws IllegalStateException { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - - // Save every element in the list - dataOutput.writeObject(item); - - // Serialize that array - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Unable to save item stack.", e); - } - } - - /** - * Gets an array of ItemStacks from Base64 string. - * - * @param data Base64 string to convert to ItemStack array. - * @return ItemStack array created from the Base64 string. - * @throws IOException if class type could not be decoded - */ - public static ItemStack itemStackArrayFromBase64(String data) throws IOException { - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - ItemStack item; - - // Read the serialized inventory - item = (ItemStack) dataInput.readObject(); - - dataInput.close(); - return item; - } catch (ClassNotFoundException e) { - throw new IOException("Unable to decode class type.", e); - } - } - -} diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index c385b3ec..67d964dd 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -62,7 +62,7 @@ public class Utils { protected final String PREFIX = "&a[&eTradeShop&a] "; private final UUID KOPUUID = UUID.fromString("daf79be7-bc1d-47d3-9896-f97b8d4cea7d"); private final UUID LORIUUID = UUID.fromString("e296bc43-2972-4111-9843-48fc32302fd4"); - protected TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); + public TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"); protected PluginDescriptionFile pdf = plugin.getDescription(); public Debug debugger; diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java b/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java new file mode 100644 index 00000000..ecbc2d44 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java @@ -0,0 +1,150 @@ +/* + * + * 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.data; + +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.utils.Utils; + +import java.io.File; +import java.util.Objects; +import java.util.UUID; + +public class DataStorage extends Utils { + + private DataType dataType; + + public DataStorage(DataType dataType) { + this.dataType = dataType; + debugger.log("Data storage set to: " + dataType.name(), DebugLevels.DISABLED); + } + + public Shop loadShopFromSign(ShopLocation sign) { + switch (dataType) { + case FLATFILE: + return new JsonConfiguration(sign.getChunk()).loadShop(sign); + case SQLITE: + return null; //TODO add SQLITE support + } + return null; + } + + public Shop loadShopFromStorage(ShopLocation chest) { + switch (dataType) { + case FLATFILE: + return null; //TODO decide if/how we want to handle this since flatfile won't support chest lookup without some changes + case SQLITE: + return null; //TODO add SQLITE support + } + return null; + } + + public void saveShop(Shop shop) { + switch (dataType) { + case FLATFILE: + new JsonConfiguration(shop.getShopLocation().getChunk()).saveShop(shop); + break; + case SQLITE: + //TODO add SQLITE support + break; + } + } + + public void removeShop(Shop shop) { + switch (dataType) { + case FLATFILE: + new JsonConfiguration(shop.getShopLocation().getChunk()).removeShop(shop.getShopLocationAsSL()); + break; + case SQLITE: + //TODO add SQLITE support + break; + } + } + + public int getShopCountInChunk(Chunk chunk) { + switch (dataType) { + case FLATFILE: + return new JsonConfiguration(chunk).getShopCount(); + case SQLITE: + return 0; //TODO add SQLITE support + } + return 0; + } + + public int getShopCountInWorld(World world) { + int count = 0; + switch (dataType) { + case FLATFILE: + for (File file : Objects.requireNonNull(new File(plugin.getDataFolder().getAbsolutePath() + File.separator + "Data" + File.separator + world.getName()).listFiles())) { + count += new JsonConfiguration(ShopChunk.deserialize(file.getName().replace(".json", ""))).getShopCount(); + } + break; + case SQLITE: + //TODO add SQLITE support + break; + } + return count; + } + + public PlayerSetting loadPlayer(UUID uuid) { + switch (dataType) { + case FLATFILE: + return new PlayerSetting(uuid, new JsonConfiguration(uuid).loadPlayer()); + case SQLITE: + return null; //TODO add SQLITE support + } + return null; + } + + public void savePlayer(PlayerSetting playerSetting) { + switch (dataType) { + case FLATFILE: + new JsonConfiguration(playerSetting.getUuid()).savePlayer(playerSetting.getData()); + break; + case SQLITE: + //TODO add SQLITE support + break; + } + } + + public void removePlayer(PlayerSetting playerSetting) { + switch (dataType) { + case FLATFILE: + new JsonConfiguration(playerSetting.getUuid()).removePlayer(); + break; + case SQLITE: + //TODO add SQLITE support + break; + } + } + + +} \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/DataType.java b/src/main/java/org/shanerx/tradeshop/utils/data/DataType.java new file mode 100644 index 00000000..b814175f --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/data/DataType.java @@ -0,0 +1,31 @@ +/* + * + * 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.data; + +public enum DataType { + FLATFILE, + SQLITE +} diff --git a/src/main/java/org/shanerx/tradeshop/utils/JsonConfiguration.java b/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java similarity index 85% rename from src/main/java/org/shanerx/tradeshop/utils/JsonConfiguration.java rename to src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java index 8663f37e..134ea497 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/JsonConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java @@ -23,7 +23,7 @@ * */ -package org.shanerx.tradeshop.utils; +package org.shanerx.tradeshop.utils.data; import com.google.common.collect.Lists; import com.google.gson.*; @@ -34,6 +34,7 @@ import org.shanerx.tradeshop.objects.ShopChunk; import org.shanerx.tradeshop.objects.ShopItemStack; import org.shanerx.tradeshop.objects.ShopLocation; +import org.shanerx.tradeshop.utils.Utils; import java.io.*; import java.util.*; @@ -174,19 +175,17 @@ public Shop loadShop(ShopLocation loc) { 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("productListB64", gson.toJsonTree(b64OverstackFixer(str))); + jsonObj.getAsJsonObject(loc.serialize()).add("product", gson.toJsonTree(b64OverstackFixer(str))); saveContents(gson.toJson(jsonObj)); } 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("costListB64", gson.toJsonTree(b64OverstackFixer(str))); + jsonObj.getAsJsonObject(loc.serialize()).add("cost", gson.toJsonTree(b64OverstackFixer(str))); saveContents(gson.toJson(jsonObj)); } - - if (jsonObj.getAsJsonObject(loc.serialize()).has("productListB64")) { List productList = new ArrayList<>(); gson.fromJson(jsonObj.getAsJsonObject(loc.serialize()).get("productListB64"), List.class).forEach(item -> productList.add(new ShopItemStack(item.toString()))); @@ -215,35 +214,28 @@ public int getShopCount() { return jsonObj.size(); } - private List b64OverstackFixer(String oldB64) { - ItemStack oldStack = null; - if (oldB64.length() > 0) { - try { - oldStack = ItemSerializer.itemStackArrayFromBase64(oldB64); - } catch (IOException ex) { - ex.printStackTrace(); - } - } + private List b64OverstackFixer(String oldB64) { + ShopItemStack oldStack = new ShopItemStack(oldB64); - if (oldStack == null) + if (oldStack.hasBase64()) return null; - if (!(oldStack.getAmount() > oldStack.getMaxStackSize())) { - return Lists.newArrayList(ItemSerializer.itemStackArrayToBase64(oldStack)); + if (!(oldStack.getItemStack().getAmount() > oldStack.getItemStack().getMaxStackSize())) { + return Lists.newArrayList(oldStack); } else { - List newStacks = new ArrayList<>(); - int amount = oldStack.getAmount(); + List newStacks = new ArrayList<>(); + int amount = oldStack.getItemStack().getAmount(); while (amount > 0) { - if (oldStack.getMaxStackSize() < amount) { - ItemStack itm = oldStack.clone(); - itm.setAmount(oldStack.getMaxStackSize()); - newStacks.add(ItemSerializer.itemStackArrayToBase64(itm)); - amount -= oldStack.getMaxStackSize(); + 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.clone(); + ItemStack itm = oldStack.getItemStack().clone(); itm.setAmount(amount); - newStacks.add(ItemSerializer.itemStackArrayToBase64(itm)); + newStacks.add(new ShopItemStack(itm)); amount -= amount; } } @@ -251,4 +243,4 @@ private List b64OverstackFixer(String oldB64) { return newStacks; } } -} +} \ No newline at end of file From bf6bab4d48a6304b9647a38f6dd77329ca01d29b Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Sat, 26 Sep 2020 17:46:03 -0700 Subject: [PATCH 2/4] Changes and new data storage - Changes to make player data storage more versatile - Added relevant shops to player data file --- .../tradeshop/commands/CommandRunner.java | 12 +- .../shanerx/tradeshop/enumys/PlayerData.java | 47 -------- .../listeners/JoinEventListener.java | 4 +- .../listeners/ShopCreateListener.java | 2 +- .../listeners/ShopTradeListener.java | 3 +- .../tradeshop/objects/PlayerSetting.java | 103 ++++++++++++++---- .../org/shanerx/tradeshop/objects/Shop.java | 76 ++++++++----- .../tradeshop/utils/data/DataStorage.java | 11 +- .../utils/data/JsonConfiguration.java | 42 ++++--- 9 files changed, 174 insertions(+), 126 deletions(-) delete mode 100644 src/main/java/org/shanerx/tradeshop/enumys/PlayerData.java diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java index 3d2bd48a..e055b3d7 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java @@ -780,8 +780,8 @@ public void removeUser() { /** * Adds the specified player to the shop as a member */ - public void addMember() { - Shop shop = findShop(); + public void addMember() { + Shop shop = findShop(); if (shop == null) return; @@ -802,11 +802,11 @@ public void addMember() { sendMessage(Message.UNSUCCESSFUL_SHOP_MEMBERS.getPrefixed()); 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()); sendMessage(Message.UPDATED_SHOP_MEMBERS.getPrefixed()); @@ -824,7 +824,7 @@ public void multi() { PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(pSender.getUniqueId()); if (command.argsSize() == 1) { - sendMessage(Message.MULTI_AMOUNT.getPrefixed().replaceAll("%amount%", String.valueOf(playerSetting.getObject(PlayerData.MULTI)))); + sendMessage(Message.MULTI_AMOUNT.getPrefixed().replaceAll("%amount%", String.valueOf(playerSetting.getMulti()))); } else { int amount = Setting.MULTI_TRADE_DEFAULT.getInt(); @@ -836,7 +836,7 @@ public void multi() { else if (amount > Setting.MULTI_TRADE_MAX.getInt()) amount = Setting.MULTI_TRADE_MAX.getInt(); - playerSetting.setObject(PlayerData.MULTI, amount); + playerSetting.setMulti(amount); plugin.getDataStorage().savePlayer(playerSetting); sendMessage(Message.MULTI_UPDATE.getPrefixed().replaceAll("%amount%", String.valueOf(amount))); diff --git a/src/main/java/org/shanerx/tradeshop/enumys/PlayerData.java b/src/main/java/org/shanerx/tradeshop/enumys/PlayerData.java deleted file mode 100644 index 6de19b6c..00000000 --- a/src/main/java/org/shanerx/tradeshop/enumys/PlayerData.java +++ /dev/null @@ -1,47 +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.enumys; - -public enum PlayerData { - TYPE("type", 0), - MULTI("multi", Setting.MULTI_TRADE_DEFAULT.getInt()); - - String path; - int defaultValue; - - PlayerData(String path, int defaultValue) { - this.path = path; - this.defaultValue = defaultValue; - } - - public String getPath() { - return path; - } - - public int getDefaultValue() { - return defaultValue; - } -} diff --git a/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java b/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java index 60f2e770..ffb7c390 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java +++ b/src/main/java/org/shanerx/tradeshop/listeners/JoinEventListener.java @@ -33,6 +33,7 @@ import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.enumys.Message; 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.utils.Utils; @@ -49,7 +50,8 @@ public JoinEventListener(TradeShop instance) { public void onJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); - plugin.getDataStorage().savePlayer(plugin.getDataStorage().loadPlayer(player.getUniqueId())); + PlayerSetting playerSetting = plugin.getDataStorage().loadPlayer(player.getUniqueId()); + plugin.getDataStorage().savePlayer(playerSetting != null ? playerSetting : new PlayerSetting(player.getUniqueId())); if (player.hasPermission(Permissions.ADMIN.getPerm())) { BukkitVersion ver = new BukkitVersion(); diff --git a/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java b/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java index 41920278..a5d9529b 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java +++ b/src/main/java/org/shanerx/tradeshop/listeners/ShopCreateListener.java @@ -132,7 +132,7 @@ public void onSignChange(SignChangeEvent event) { event.setCancelled(true); return; } - + shop.updateSign(event); shop.removeEvent(); shop.saveShop(); diff --git a/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java b/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java index a69778c4..69e060c6 100644 --- a/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java +++ b/src/main/java/org/shanerx/tradeshop/listeners/ShopTradeListener.java @@ -38,7 +38,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.enumys.Message; -import org.shanerx.tradeshop.enumys.PlayerData; import org.shanerx.tradeshop.enumys.Setting; import org.shanerx.tradeshop.enumys.ShopType; import org.shanerx.tradeshop.framework.events.PlayerTradeEvent; @@ -125,7 +124,7 @@ public void onBlockInteract(PlayerInteractEvent e) { } if (buyer.isSneaking() && Setting.ALLOW_MULTI_TRADE.getBoolean()) { - multiplier = plugin.getDataStorage().loadPlayer(buyer.getUniqueId()).getObject(PlayerData.MULTI); + multiplier = plugin.getDataStorage().loadPlayer(buyer.getUniqueId()).getMulti(); } diff --git a/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java b/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java index 03ea4cbe..87d33f7c 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java +++ b/src/main/java/org/shanerx/tradeshop/objects/PlayerSetting.java @@ -25,45 +25,110 @@ package org.shanerx.tradeshop.objects; -import org.shanerx.tradeshop.enumys.PlayerData; +import com.google.common.collect.Sets; +import com.google.gson.Gson; +import org.shanerx.tradeshop.enumys.Setting; +import java.io.Serializable; import java.util.Map; +import java.util.Set; import java.util.UUID; -public class PlayerSetting { +public class PlayerSetting implements Serializable { private transient UUID uuid; - private transient Map data; + private String uuidString; + + private int type = 0, multi = Setting.MULTI_TRADE_DEFAULT.getInt(); + + private Set ownedShops, staffShops; public PlayerSetting(UUID playerUUID, Map data) { this.uuid = playerUUID; - this.data = data; - for (PlayerData key : PlayerData.values()) { - if (!data.containsKey(key.getPath())) - data.putIfAbsent(key.getPath(), key.getDefaultValue()); - else - data.replace(key.getPath(), key.getDefaultValue()); - } + this.uuidString = uuid.toString(); + + if (data.containsKey("type")) type = data.get("type"); + if (data.containsKey("multi")) multi = data.get("multi"); + + ownedShops = Sets.newHashSet(); + staffShops = Sets.newHashSet(); + + load(); } - public Integer getObject(PlayerData key) { - Integer value = data.get(key.getPath()); - return value != null ? value : key.getDefaultValue(); + public PlayerSetting(UUID playerUUID) { + this.uuid = playerUUID; + this.uuidString = uuid.toString(); + + ownedShops = Sets.newHashSet(); + staffShops = Sets.newHashSet(); + + load(); } - public void setObject(PlayerData key, Integer value) { - if (!data.containsKey(key.getPath())) - data.putIfAbsent(key.getPath(), value); + public static PlayerSetting deserialize(String serialized) { + PlayerSetting playerSetting = new Gson().fromJson(serialized, PlayerSetting.class); + playerSetting.load(); + return playerSetting; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public int getMulti() { + return multi; + } + + public void setMulti(int multi) { + this.multi = multi; + } + + public Set getOwnedShops() { + return ownedShops; + } + + 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) && + !ownedShops.contains(shop.getShopLocationAsSL().serialize())) + staffShops.add(shop.getShopLocationAsSL().serialize()); + } + + public void removeShop(Shop shop) { + ownedShops.remove(shop.getShopLocationAsSL().serialize()); + staffShops.remove(shop.getShopLocationAsSL().serialize()); + } + + public void updateShops(Shop shop) { + if (!shop.getUsersUUID().contains(uuid)) + removeShop(shop); else - data.replace(key.getPath(), value); + addShop(shop); + } public UUID getUuid() { return uuid; } - public Map getData() { - return data; + public Set getStaffShops() { + return staffShops; + } + + public void load() { + if (uuid == null) uuid = UUID.fromString(uuidString); + if (multi > Setting.MULTI_TRADE_MAX.getInt()) multi = Setting.MULTI_TRADE_MAX.getInt(); + } + + public String serialize() { + return new Gson().toJson(this); } } diff --git a/src/main/java/org/shanerx/tradeshop/objects/Shop.java b/src/main/java/org/shanerx/tradeshop/objects/Shop.java index 69c53cf0..9d33b55f 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/objects/Shop.java @@ -34,6 +34,7 @@ import org.bukkit.event.block.SignChangeEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.enumys.Setting; import org.shanerx.tradeshop.enumys.ShopRole; import org.shanerx.tradeshop.enumys.ShopStatus; @@ -45,7 +46,6 @@ import java.util.*; import java.util.stream.Collectors; -@SuppressWarnings("unused") public class Shop implements Serializable { private ShopUser owner; @@ -149,16 +149,6 @@ public static Shop loadShop(ShopLocation loc) { return new Utils().plugin.getDataStorage().loadShopFromSign(loc); } - /** - * Retrieves the Shop object based on a serialized ShopLocation of the sign - * - * @param serializedShopLocation ShopLocation in serialized string - * @return Shop object from file - */ - public static Shop loadShop(String serializedShopLocation) { - return loadShop(Objects.requireNonNull(ShopLocation.deserialize(serializedShopLocation))); - } - /** * Loads the shop from file * @@ -247,6 +237,7 @@ public List getUsers() { users.add(owner); users.addAll(getManagers()); users.addAll(getMembers()); + return users; } @@ -302,29 +293,53 @@ public boolean addManager(UUID newManager) { 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) { - if (getManagersUUID().contains(oldUser)) { - managers.remove(oldUser); - saveShop(); - updateSign(); - return true; - } + public boolean removeUser(UUID oldUser) { + boolean ret = false; + if (getManagersUUID().contains(oldUser)) { + managers.remove(oldUser); + ret = true; + } - if (getMembersUUID().contains(oldUser)) { - members.remove(oldUser); - saveShop(); - updateSign(); - return true; - } + if (getMembersUUID().contains(oldUser)) { + members.remove(oldUser); + ret = true; + } - return false; - } + saveShop(); + updateSign(); + + return ret; + } /** * Adds a member to the shop @@ -338,6 +353,7 @@ public boolean addMember(UUID newMember) { saveShop(); return true; } + return false; } @@ -609,6 +625,7 @@ public List getUsersUUID() { */ public void saveShop() { new Utils().plugin.getDataStorage().saveShop(this); + updateUserFiles(); } /** @@ -803,9 +820,10 @@ public void setStatus(ShopStatus newStatus) { /** * Removes this shop from file */ - public void remove() { - new Utils().plugin.getDataStorage().removeShop(this); - } + public void remove() { + purgeFromUserFiles(); + new Utils().plugin.getDataStorage().removeShop(this); + } /** * Checks if shop is open diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java b/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java index ecbc2d44..abc80ff7 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java +++ b/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java @@ -115,19 +115,22 @@ public int getShopCountInWorld(World world) { } public PlayerSetting loadPlayer(UUID uuid) { + PlayerSetting playerSetting = null; switch (dataType) { case FLATFILE: - return new PlayerSetting(uuid, new JsonConfiguration(uuid).loadPlayer()); + playerSetting = new JsonConfiguration(uuid).loadPlayer(); + break; case SQLITE: - return null; //TODO add SQLITE support + //TODO add SQLITE support + break; } - return null; + return playerSetting != null ? playerSetting : new PlayerSetting(uuid); } public void savePlayer(PlayerSetting playerSetting) { switch (dataType) { case FLATFILE: - new JsonConfiguration(playerSetting.getUuid()).savePlayer(playerSetting.getData()); + new JsonConfiguration(playerSetting.getUuid()).savePlayer(playerSetting); break; case SQLITE: //TODO add SQLITE support diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java b/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java index 134ea497..4ff3d5b1 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java @@ -26,18 +26,21 @@ package org.shanerx.tradeshop.utils.data; import com.google.common.collect.Lists; -import com.google.gson.*; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import org.bukkit.Chunk; 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.objects.*; import org.shanerx.tradeshop.utils.Utils; import java.io.*; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; public class JsonConfiguration extends Utils implements Serializable { private String pluginFolder; @@ -48,6 +51,8 @@ public class JsonConfiguration extends Utils implements Serializable { private int configType; private Gson gson; + private transient UUID playerUUID; + public JsonConfiguration(Chunk c) { gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); configType = 0; @@ -69,8 +74,9 @@ public JsonConfiguration(Chunk c) { } public JsonConfiguration(UUID uuid) { - gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().serializeNulls().create(); + gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); configType = 1; + playerUUID = uuid; this.pluginFolder = plugin.getDataFolder().getAbsolutePath(); this.path = this.pluginFolder + File.separator + "Data" + File.separator + "Players"; this.file = new File(path + File.separator + uuid.toString() + ".json"); @@ -110,12 +116,11 @@ private void saveContents(String str) { loadContents(); } - public void savePlayer(Map data) { + public void savePlayer(PlayerSetting playerSetting) { if (configType != 1) return; - JsonElement obj = gson.toJsonTree(data); - jsonObj.add("data", obj); + jsonObj.add(playerSetting.getUuid().toString(), gson.toJsonTree(playerSetting)); saveContents(gson.toJson(jsonObj)); } @@ -127,21 +132,24 @@ public void removePlayer() { file.delete(); } - public Map loadPlayer() { + public PlayerSetting loadPlayer() { if (configType != 1) return null; - Gson gson = new Gson(); - Map data; + Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); + PlayerSetting playerSetting; if (jsonObj.has("data")) { - data = gson.fromJson(jsonObj.get("data"), new TypeToken>() { - }.getType()); + playerSetting = new PlayerSetting(playerUUID, gson.fromJson(jsonObj.get("data"), new TypeToken>() { + }.getType())); + jsonObj.remove("data"); + saveContents(gson.toJson(jsonObj)); } else { - data = new HashMap<>(); + playerSetting = gson.fromJson(jsonObj.get(playerUUID.toString()), PlayerSetting.class); } - return data; + playerSetting.load(); + return playerSetting; } public void saveShop(Shop shop) { From 4077fa0497f1510e479e0406be9df80888c5a7f9 Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Sat, 26 Sep 2020 18:08:04 -0700 Subject: [PATCH 3/4] Catch for bad data setting - Changes to catch and stop plugin when data-storage-type is improperly set - Changes to Debug system to allow negative positions for error codes --- .../java/org/shanerx/tradeshop/TradeShop.java | 15 ++++++++++----- .../shanerx/tradeshop/commands/CommandRunner.java | 9 +++++++++ .../org/shanerx/tradeshop/enumys/DebugLevels.java | 1 + .../java/org/shanerx/tradeshop/objects/Debug.java | 2 ++ .../shanerx/tradeshop/utils/data/DataStorage.java | 5 +++++ 5 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/TradeShop.java b/src/main/java/org/shanerx/tradeshop/TradeShop.java index 19dd42d8..158a9879 100644 --- a/src/main/java/org/shanerx/tradeshop/TradeShop.java +++ b/src/main/java/org/shanerx/tradeshop/TradeShop.java @@ -31,10 +31,7 @@ import org.bukkit.plugin.java.JavaPlugin; import org.shanerx.tradeshop.commands.CommandCaller; import org.shanerx.tradeshop.commands.CommandTabCaller; -import org.shanerx.tradeshop.enumys.Message; -import org.shanerx.tradeshop.enumys.Setting; -import org.shanerx.tradeshop.enumys.ShopSign; -import org.shanerx.tradeshop.enumys.ShopStorage; +import org.shanerx.tradeshop.enumys.*; import org.shanerx.tradeshop.listeners.*; import org.shanerx.tradeshop.objects.Debug; import org.shanerx.tradeshop.objects.ListManager; @@ -84,7 +81,15 @@ public void onEnable() { signs = new ShopSign(); storages = new ShopStorage(); lists = new ListManager(); - dataStorage = new DataStorage(DataType.valueOf(Setting.DATA_STORAGE_TYPE.getString().toUpperCase())); + + try { + dataStorage = new DataStorage(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); + getServer().getPluginManager().disablePlugin(this); + return; + } PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new JoinEventListener(this), this); diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java index e055b3d7..baf8b85e 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java @@ -43,6 +43,7 @@ import org.shanerx.tradeshop.objects.*; import org.shanerx.tradeshop.utils.ObjectHolder; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.data.DataType; import java.util.ArrayList; import java.util.List; @@ -130,6 +131,14 @@ public void reload() { Message.reload(); Setting.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; + } sendMessage(getPrefix() + "&6The configuration files have been reloaded!"); } diff --git a/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java b/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java index 6c4633bf..28229106 100644 --- a/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java +++ b/src/main/java/org/shanerx/tradeshop/enumys/DebugLevels.java @@ -29,6 +29,7 @@ public enum DebugLevels { + DATA_ERROR(-1, Level.SEVERE), DISABLED(0, Level.INFO), LIST_MANAGER(1, Level.WARNING), STARTUP(2, Level.INFO), diff --git a/src/main/java/org/shanerx/tradeshop/objects/Debug.java b/src/main/java/org/shanerx/tradeshop/objects/Debug.java index 4c0c21c7..d86ca222 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/Debug.java +++ b/src/main/java/org/shanerx/tradeshop/objects/Debug.java @@ -65,6 +65,8 @@ public void log(String message, DebugLevels level) { Bukkit.getLogger().log(level.getLogLevel(), PREFIX.replace("%level%", level.getPrefix()) + message); } else if (level == DebugLevels.DISABLED) { Bukkit.getLogger().log(level.getLogLevel(), PREFIX.replace(" Debug%level%", "") + message); + } else if (level.getPosition() < 0) { + Bukkit.getLogger().log(level.getLogLevel(), PREFIX.replace("%level%", level.getPrefix()) + message); } } } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java b/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java index abc80ff7..26f699e6 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java +++ b/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java @@ -47,6 +47,11 @@ public DataStorage(DataType dataType) { debugger.log("Data storage set to: " + dataType.name(), DebugLevels.DISABLED); } + public void reload(DataType dataType) { + this.dataType = dataType; + debugger.log("Data storage set to: " + dataType.name(), DebugLevels.DISABLED); + } + public Shop loadShopFromSign(ShopLocation sign) { switch (dataType) { case FLATFILE: From 898667776061670669f4066cf81319716b5d9c9b Mon Sep 17 00:00:00 2001 From: KillerOfPie Date: Sat, 26 Sep 2020 21:09:52 -0700 Subject: [PATCH 4/4] Added stored Chest Linkage data for Json - May remove persistent data values later if this works well - Also fixed a missing .getString for a setting in Utils --- .../java/org/shanerx/tradeshop/TradeShop.java | 18 +++- .../tradeshop/commands/CommandRunner.java | 3 + .../tradeshop/objects/ListManager.java | 1 + .../org/shanerx/tradeshop/objects/Shop.java | 14 ++- .../org/shanerx/tradeshop/utils/Utils.java | 7 +- .../tradeshop/utils/data/DataStorage.java | 91 +++++++++++++++++-- .../utils/data/JsonConfiguration.java | 38 ++++++++ 7 files changed, 152 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/shanerx/tradeshop/TradeShop.java b/src/main/java/org/shanerx/tradeshop/TradeShop.java index 158a9879..993ffec6 100644 --- a/src/main/java/org/shanerx/tradeshop/TradeShop.java +++ b/src/main/java/org/shanerx/tradeshop/TradeShop.java @@ -45,7 +45,9 @@ public class TradeShop extends JavaPlugin { private final NamespacedKey storageKey = new NamespacedKey(this, "tradeshop-storage-data"); private final NamespacedKey signKey = new NamespacedKey(this, "tradeshop-sign-data"); + private final int bStatsPluginID = 1690; + private Metrics metrics; private ListManager lists; private DataStorage dataStorage; @@ -54,8 +56,6 @@ public class TradeShop extends JavaPlugin { private ShopSign signs; private ShopStorage storages; - private Metrics metrics; - private Debug debugger; @Override @@ -78,9 +78,6 @@ public void onEnable() { Message.reload(); debugger = new Debug(); - signs = new ShopSign(); - storages = new ShopStorage(); - lists = new ListManager(); try { dataStorage = new DataStorage(DataType.valueOf(Setting.DATA_STORAGE_TYPE.getString().toUpperCase())); @@ -91,6 +88,10 @@ public void onEnable() { return; } + signs = new ShopSign(); + storages = new ShopStorage(); + lists = new ListManager(); + PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new JoinEventListener(this), this); pm.registerEvents(new ShopProtectionListener(this), this); @@ -115,6 +116,13 @@ public void onEnable() { } + @Override + public void onDisable() { + dataStorage.saveChestLinkages(); + + getListManager().clearManager(); + } + public NamespacedKey getStorageKey() { return storageKey; } diff --git a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java index baf8b85e..e86e2220 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java +++ b/src/main/java/org/shanerx/tradeshop/commands/CommandRunner.java @@ -872,6 +872,9 @@ private Shop findShop() { 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 diff --git a/src/main/java/org/shanerx/tradeshop/objects/ListManager.java b/src/main/java/org/shanerx/tradeshop/objects/ListManager.java index 4b919dcd..fa216dd3 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/ListManager.java +++ b/src/main/java/org/shanerx/tradeshop/objects/ListManager.java @@ -109,6 +109,7 @@ public void clearManager() { directions.clear(); addOnMats.clear(); gameMats.clear(); + plugin.getDataStorage().clearChestLinkages(); } private void updateBlacklist() { diff --git a/src/main/java/org/shanerx/tradeshop/objects/Shop.java b/src/main/java/org/shanerx/tradeshop/objects/Shop.java index 9d33b55f..135492fa 100644 --- a/src/main/java/org/shanerx/tradeshop/objects/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/objects/Shop.java @@ -55,7 +55,7 @@ public class Shop implements Serializable { private List product, cost; private transient SignChangeEvent signChangeEvent; private transient Inventory storageInv; - private transient Utils utils; + private transient Utils utils = new Utils(); private ShopStatus status = ShopStatus.INCOMPLETE; /** @@ -71,6 +71,7 @@ public Shop(Tuple locations, ShopType shopType, ShopUser own shopLoc = new ShopLocation(locations.getLeft()); this.owner = owner; chestLoc = new ShopLocation(locations.getRight()); + utils.plugin.getDataStorage().addChestLinkage(chestLoc, shopLoc); this.shopType = shopType; managers = players.getLeft(); members = players.getRight(); @@ -95,6 +96,7 @@ public Shop(Tuple locations, ShopType shopType, ShopUser own 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(); @@ -391,6 +393,7 @@ public Location getInventoryLocation() { */ public void setInventoryLocation(Location newLoc) { chestLoc = new ShopLocation(newLoc); + utils.plugin.getDataStorage().addChestLinkage(chestLoc, shopLoc); } /** @@ -603,7 +606,8 @@ public ShopLocation getInventoryLocationAsSL() { * Fixes values that cannot be serialized after loading */ public void fixAfterLoad() { - utils = new Utils(); + if (utils == null) + utils = new Utils(); shopLoc.stringToWorld(); if (!shopType.isITrade() && chestLoc != null) chestLoc.stringToWorld(); @@ -624,7 +628,7 @@ public List getUsersUUID() { * Saves the shop too file */ public void saveShop() { - new Utils().plugin.getDataStorage().saveShop(this); + utils.plugin.getDataStorage().saveShop(this); updateUserFiles(); } @@ -749,6 +753,7 @@ public BlockState getStorage() { */ public void removeStorage() { if (hasStorage()) { + utils.plugin.getDataStorage().removeChestLinkage(chestLoc); chestLoc = null; } } @@ -822,7 +827,8 @@ public void setStatus(ShopStatus newStatus) { */ public void remove() { purgeFromUserFiles(); - new Utils().plugin.getDataStorage().removeShop(this); + removeStorage(); + utils.plugin.getDataStorage().removeShop(this); } /** diff --git a/src/main/java/org/shanerx/tradeshop/utils/Utils.java b/src/main/java/org/shanerx/tradeshop/utils/Utils.java index 67d964dd..323340a5 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/Utils.java +++ b/src/main/java/org/shanerx/tradeshop/utils/Utils.java @@ -47,6 +47,7 @@ import org.shanerx.tradeshop.objects.Debug; import org.shanerx.tradeshop.objects.Shop; import org.shanerx.tradeshop.objects.ShopItemStack; +import org.shanerx.tradeshop.objects.ShopLocation; import java.util.*; import java.util.logging.Level; @@ -209,7 +210,7 @@ public boolean canExchange(Inventory inv, ItemStack itmOut, ItemStack itmIn) { * @param shop Shoptype enum to get header */ public void failedSignReset(SignChangeEvent e, ShopType shop) { - e.setLine(0, colorize(Setting.SHOP_BAD_COLOUR + shop.toString())); + e.setLine(0, colorize(Setting.SHOP_BAD_COLOUR.getString() + shop.toString())); e.setLine(1, ""); e.setLine(2, ""); e.setLine(3, ""); @@ -288,6 +289,10 @@ public String colorize(String msg) { * @return the sign. */ public Sign findShopSign(Block chest) { + ShopLocation potentialLocation = plugin.getDataStorage().getChestLinkage(new ShopLocation(chest.getLocation())); + if (potentialLocation != null && ShopType.isShop(potentialLocation.getLocation().getBlock())) + return (Sign) potentialLocation.getLocation().getBlock().getState(); + ArrayList faces = plugin.getListManager().getDirections(); Collections.reverse(faces); ArrayList flatFaces = new ArrayList<>(Arrays.asList(BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST)); diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java b/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java index 26f699e6..68512f7e 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java +++ b/src/main/java/org/shanerx/tradeshop/utils/data/DataStorage.java @@ -28,23 +28,19 @@ 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.objects.*; import org.shanerx.tradeshop.utils.Utils; import java.io.File; -import java.util.Objects; -import java.util.UUID; +import java.util.*; public class DataStorage extends Utils { - private DataType dataType; + private transient DataType dataType; + private transient Map> chestLinkage = new HashMap<>(); public DataStorage(DataType dataType) { - this.dataType = dataType; - debugger.log("Data storage set to: " + dataType.name(), DebugLevels.DISABLED); + reload(dataType); } public void reload(DataType dataType) { @@ -65,7 +61,7 @@ public Shop loadShopFromSign(ShopLocation sign) { public Shop loadShopFromStorage(ShopLocation chest) { switch (dataType) { case FLATFILE: - return null; //TODO decide if/how we want to handle this since flatfile won't support chest lookup without some changes + return loadShopFromSign(getChestLinkage(chest)); case SQLITE: return null; //TODO add SQLITE support } @@ -154,5 +150,80 @@ public void removePlayer(PlayerSetting playerSetting) { } } + private boolean loadChestLinkage(World world) { + if (dataType != DataType.FLATFILE) + return false; + + Map loadedLinkage = new JsonConfiguration(world).loadChestLinkage(); + + if (loadedLinkage != null) { + chestLinkage.put(world, loadedLinkage); + return true; + } else { + return false; + } + } + + public ShopLocation getChestLinkage(ShopLocation chestLocation) { + switch (dataType) { + case FLATFILE: + if (loadChestLinkage(chestLocation.getWorld()) + && chestLinkage.containsKey(chestLocation.getWorld()) + && chestLinkage.get(chestLocation.getWorld()).containsKey(chestLocation.serialize())) { + return ShopLocation.deserialize(chestLinkage.get(chestLocation.getWorld()).get(chestLocation.serialize())); + } else { + ShopChest shopChest = new ShopChest(chestLocation.getLocation()); + if (shopChest.hasShopSign()) { + if (!chestLinkage.containsKey(chestLocation.getWorld())) { + chestLinkage.putIfAbsent(chestLocation.getWorld(), + Collections.singletonMap(chestLocation.serialize(), shopChest.getShopSign().serialize())); + } else { + if (chestLinkage.get(chestLocation.getWorld()).containsKey(chestLocation.serialize())) { + chestLinkage.get(chestLocation.getWorld()).replace(chestLocation.serialize(), shopChest.getShopSign().serialize()); + } else { + chestLinkage.get(chestLocation.getWorld()).put(chestLocation.serialize(), shopChest.getShopSign().serialize()); + } + } + saveChestLinkages(); + } + return shopChest.getShopSign(); + } + case SQLITE: + //TODO add SQLITE support + break; + } + + return null; + } + + public void removeChestLinkage(ShopLocation chestLocation) { + if (getChestLinkage(chestLocation) != null) { + chestLinkage.get(chestLocation.getWorld()).remove(chestLocation.serialize()); + new JsonConfiguration(chestLocation.getWorld()).saveChestLinkage(chestLinkage.get(chestLocation.getWorld())); + } + } + + public void addChestLinkage(ShopLocation chestLocation, ShopLocation shopLocation) { + if (chestLinkage.containsKey(chestLocation.getWorld())) { + if (chestLinkage.get(chestLocation.getWorld()).containsKey(chestLocation.serialize())) + chestLinkage.get(chestLocation.getWorld()).replace(chestLocation.serialize(), shopLocation.serialize()); + else + chestLinkage.get(chestLocation.getWorld()).put(chestLocation.serialize(), shopLocation.serialize()); + } else { + chestLinkage.put(chestLocation.getWorld(), Collections.singletonMap(chestLocation.serialize(), shopLocation.serialize())); + } + saveChestLinkages(); + } + + public void saveChestLinkages() { + for (World world : chestLinkage.keySet()) { + new JsonConfiguration(world).saveChestLinkage(chestLinkage.get(world)); + } + } + + public void clearChestLinkages() { + chestLinkage.clear(); + } + } \ No newline at end of file diff --git a/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java b/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java index 4ff3d5b1..0d7fa367 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/utils/data/JsonConfiguration.java @@ -32,6 +32,7 @@ import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import org.bukkit.Chunk; +import org.bukkit.World; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.objects.*; import org.shanerx.tradeshop.utils.Utils; @@ -93,6 +94,25 @@ public JsonConfiguration(UUID uuid) { loadContents(); } + public JsonConfiguration(World world) { + gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); + configType = 2; + this.pluginFolder = plugin.getDataFolder().getAbsolutePath(); + this.path = this.pluginFolder + File.separator + "Data" + File.separator + world.getName(); + this.file = new File(path + File.separator + "chest_linkage.json"); + this.filePath = new File(path); + this.filePath.mkdirs(); + if (!this.file.exists()) { + try { + this.file.createNewFile(); + } catch (Exception exception) { + throw new RuntimeException(exception); + } + } + + loadContents(); + } + private void loadContents() { try { jsonObj = new JsonParser().parse(new FileReader(file)).getAsJsonObject(); @@ -222,6 +242,24 @@ public int getShopCount() { return jsonObj.size(); } + public Map loadChestLinkage() { + if (configType != 2) + return null; + + Gson gson = new Gson(); + return gson.fromJson(jsonObj.get("linkage_data"), new TypeToken>() { + }.getType()); + } + + public void saveChestLinkage(Map linkageData) { + if (configType != 2) + return; + + jsonObj.add("linkage_data", gson.toJsonTree(linkageData)); + + saveContents(gson.toJson(jsonObj)); + } + private List b64OverstackFixer(String oldB64) { ShopItemStack oldStack = new ShopItemStack(oldB64);