From baeda89b74f5bce887767a20286d065a5d7b01ad Mon Sep 17 00:00:00 2001 From: Sparkling Comet Date: Wed, 6 Jul 2022 13:40:33 +0200 Subject: [PATCH 1/3] Update PULL_REQUEST_TEMPLATE.md --- .github/PULL_REQUEST_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 000d3569..24965d8e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -8,7 +8,7 @@ Replace `[ ]` with `[x]` to cross the checkbox. - [ ] I have checked the PRs for upcoming features/bug fixes. - [ ] I have read the [contributing guidelines][contributing]. -> It is sometimes better to include more changes in a single commit. +> It is sometimes better to include more _related_ changes in a single commit. If you find yourself having an overwhelming amount of commits, you can **rebase** your branch. 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 2/3] 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 From 4069f88ea824e6d18948fd68eddf7cdfc5adba59 Mon Sep 17 00:00:00 2001 From: BoyStijn <34859097+BoyStijn@users.noreply.github.com> Date: Mon, 28 Nov 2022 11:03:25 +0100 Subject: [PATCH 3/3] Fixed Merge Issues Fixed Merge Issues --- .../commands/commandrunners/EditCommand.java | 12 +- .../commands/commandrunners/GUICommand.java | 67 +++++----- .../commandrunners/ShopUserCommand.java | 14 +-- .../commands/commandrunners/WhatCommand.java | 4 +- .../tradeshop/data/storage/DataStorage.java | 2 +- .../data/storage/Json/JsonConfiguration.java | 7 +- .../Json/JsonLinkageConfiguration.java | 1 + .../storage/Json/JsonShopConfiguration.java | 14 +-- .../data/storage/LinkageConfiguration.java | 12 +- .../shanerx/tradeshop/item/ShopItemStack.java | 115 ++++++------------ .../tradeshop/player/PlayerSetting.java | 27 ++-- .../shanerx/tradeshop/player/ShopUser.java | 3 +- .../java/org/shanerx/tradeshop/shop/Shop.java | 53 +++++--- .../org/shanerx/tradeshop/shop/ShopChest.java | 4 +- .../org/shanerx/tradeshop/shop/ShopType.java | 4 +- .../listeners/ShopProtectionListener.java | 4 +- .../tradeshop/shoplocation/ShopChunk.java | 5 +- .../tradeshop/shoplocation/ShopLocation.java | 5 +- .../utils/gsonprocessing/GsonProcessor.java | 74 +++++++++++ .../ConfigurationSerializableAdapter.java | 80 ++++++++++++ .../tradeshop/utils/objects/ObjectHolder.java | 6 +- .../tradeshop/utils/objects/Tuple.java | 10 +- src/main/resources/builddate.yml | 2 +- 23 files changed, 336 insertions(+), 189 deletions(-) create mode 100644 src/main/java/org/shanerx/tradeshop/utils/gsonprocessing/GsonProcessor.java create mode 100644 src/main/java/org/shanerx/tradeshop/utils/gsonprocessing/typeadapters/ConfigurationSerializableAdapter.java 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 0a6f8233..c96e5ad8 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,11 @@ package org.shanerx.tradeshop.commands.commandrunners; -import de.themoep.inventorygui.*; +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 org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.shanerx.tradeshop.TradeShop; @@ -79,7 +83,7 @@ public void edit() { return; } - mainMenu = new InventoryGui(plugin, "Edit Menu-" + shop.getShopLocationAsSL().toString(), MENU_LAYOUT); + mainMenu = new InventoryGui(plugin, "Edit Menu-" + shop.getShopLocationAsSL().serialize(), MENU_LAYOUT); mainMenu.setFiller(new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1)); @@ -275,7 +279,7 @@ private GuiElement editCostMenu(char slotChar) { costEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.YELLOW_STAINED_GLASS_PANE), " ")); for (int i = 0; i < costItems.size(); i++) { - costGroup.addElement(itemSettingMenu(i, ShopItemSide.COST, true)); + costGroup.addElement(itemSettingMenu(shop, i, ShopItemSide.COST, true)); } costEdit.addElement(costGroup); @@ -319,7 +323,7 @@ private GuiElement editProductMenu(char slotChar) { productEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.YELLOW_STAINED_GLASS_PANE), " ")); for (int i = 0; i < productItems.size(); i++) { - productGroup.addElement(itemSettingMenu(i, ShopItemSide.PRODUCT, true)); + productGroup.addElement(itemSettingMenu(shop, i, ShopItemSide.PRODUCT, true)); } productEdit.addElement(productGroup); 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 74567967..2532990c 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/GUICommand.java @@ -25,7 +25,12 @@ package org.shanerx.tradeshop.commands.commandrunners; -import de.themoep.inventorygui.*; +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; @@ -37,6 +42,7 @@ import org.shanerx.tradeshop.item.ShopItemSide; import org.shanerx.tradeshop.item.ShopItemStack; import org.shanerx.tradeshop.item.ShopItemStackSettingKeys; +import org.shanerx.tradeshop.shop.Shop; import org.shanerx.tradeshop.utils.objects.ObjectHolder; import java.util.ArrayList; @@ -75,9 +81,9 @@ public GUICommand(TradeShop instance, CommandPass command) { //region Util Methods //------------------------------------------------------------------------------------------------------------------ - protected StaticGuiElement itemSettingMenu(int index, ShopItemSide side, boolean editable) { + protected StaticGuiElement itemSettingMenu(Shop shop, int index, ShopItemSide side, boolean editable) { ShopItemStack item = (side.equals(ShopItemSide.COST) ? costItems : productItems).get(index); - ItemStack tempStack = item.getItemStack(); + ItemStack tempStack = item.getItemStack().clone(); ItemMeta tempMeta = tempStack.getItemMeta(); List newLore = new ArrayList<>(); newLore.add(colorize("&8Amount &7ยป &f" + item.getAmount())); @@ -98,13 +104,6 @@ protected StaticGuiElement itemSettingMenu(int index, ShopItemSide side, boolean // Add Cancel button when editable and Back button when not - Goes to previous screen without saving changes itemEdit.addElement(getBackButton(editable)); - // 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; - }, "Save Changes")); - itemEdit.addElement(new StaticGuiElement('a', new ItemStack(Material.YELLOW_STAINED_GLASS_PANE), " ")); itemEdit.addElement(getNextButton()); itemEdit.addElement(getPrevButton()); @@ -184,78 +183,86 @@ protected StaticGuiElement itemSettingMenu(int index, ShopItemSide side, boolean itemEdit.addElement(itemGroup); itemEdit.addElement(settingGroup); + + // Add Save button only when editable - Saves and Goes to previous screen + if (editable) itemEdit.addElement(new StaticGuiElement('s', new ItemStack(Material.ANVIL), click3 -> { + shop.updateSideItem(side, item, index); + InventoryGui.goBack(pSender); + return true; + }, "Save Changes")); + itemEdit.show(pSender); return true; }); } - private GuiElement numericalOption(ShopItemStackSettingKeys setting, ShopItemStack tempItem, boolean editable) { + private GuiElement numericalOption(ShopItemStackSettingKeys setting, ShopItemStack item, boolean isScreenEditable) { ItemStack[] indexedTempItem = new ItemStack[]{getBooleanItem(false), new ItemStack(Material.IRON_BLOCK), getBooleanItem(true), new ItemStack(Material.GOLD_BLOCK)}; - if (setting.isUserEditable() && editable) { + if (setting.isUserEditable() && isScreenEditable) { return new GuiStateElement('e', - String.valueOf(tempItem.getShopSettingAsInteger(setting)), + String.valueOf(item.getShopSetting(setting).asInteger()), new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(2)); + item.setShopSettings(setting, new ObjectHolder<>(2)); }, "2", indexedTempItem[3], setting.makeReadable(), - tempItem.getStateString(new ObjectHolder<>(2))), + item.getStateString(new ObjectHolder<>(2))), new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(-1)); + item.setShopSettings(setting, new ObjectHolder<>(-1)); }, "-1", indexedTempItem[0], setting.makeReadable(), - tempItem.getStateString(new ObjectHolder<>(-1))), + item.getStateString(new ObjectHolder<>(-1))), new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(0)); + item.setShopSettings(setting, new ObjectHolder<>(0)); }, "0", indexedTempItem[1], setting.makeReadable(), - tempItem.getStateString(new ObjectHolder<>(0))), + item.getStateString(new ObjectHolder<>(0))), new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(1)); + item.setShopSettings(setting, new ObjectHolder<>(1)); }, "1", indexedTempItem[2], setting.makeReadable(), - tempItem.getStateString(new ObjectHolder<>(1)) + item.getStateString(new ObjectHolder<>(1)) )); } - return new StaticGuiElement('e', indexedTempItem[tempItem.getShopSettingAsInteger(setting) + 1], setting.makeReadable(), tempItem.getStateString(setting)); + return new StaticGuiElement('e', indexedTempItem[item.getShopSetting(setting).asInteger() + 1], setting.makeReadable(), item.getStateString(setting)); } - private GuiElement booleanOption(ShopItemStackSettingKeys setting, ShopItemStack tempItem, boolean editable) { - if (setting.isUserEditable() && editable) { + private GuiElement booleanOption(ShopItemStackSettingKeys setting, ShopItemStack item, boolean isScreenEditable) { + if (setting.isUserEditable() && isScreenEditable) { return new GuiStateElement('e', - String.valueOf(tempItem.getShopSettingAsBoolean(setting)), + String.valueOf(item.getShopSetting(setting).asBoolean()), new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(true)); + item.setShopSettings(setting, new ObjectHolder<>(true)); }, "true", getBooleanItem(true), setting.makeReadable(), - tempItem.getStateString(new ObjectHolder<>(true)) + item.getStateString(new ObjectHolder<>(true)) ), new GuiStateElement.State(change -> { - tempItem.setShopSettings(setting, new ObjectHolder<>(false)); + item.setShopSettings(setting, new ObjectHolder<>(false)); }, "false", getBooleanItem(false), setting.makeReadable(), - tempItem.getStateString(new ObjectHolder<>(false)) + item.getStateString(new ObjectHolder<>(false)) )); } - return new StaticGuiElement('e', tempItem.getShopSettingAsBoolean(setting) ? getBooleanItem(true) : getBooleanItem(false), setting.makeReadable(), tempItem.getStateString(setting)); + return new StaticGuiElement('e', getBooleanItem(item.getShopSetting(setting).asBoolean()), setting.makeReadable(), item.getStateString(setting)); } private StaticGuiElement settingDisplayItem(ShopItemStackSettingKeys setting, ShopItemStack tempItem) { 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 86cb6e2f..40c19697 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.fromString(location))); + ownedShops.add(plugin.getDataStorage().loadShopFromSign(ShopLocation.deserialize(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().toString(), UserOperationStatus.FAILED_MISSING.toString()); + updateStatuses.put(shop.getShopLocationAsSL().serialize(), 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().toString(), UserOperationStatus.FAILED_EXISTING.toString()); + 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().toString(), UserOperationStatus.FAILED_CAPACITY.toString()); + 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().toString(), UserOperationStatus.FAILED_CAPACITY.toString()); + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED_CAPACITY.toString()); break eachOwnedShop; } break; @@ -205,9 +205,9 @@ public void editUser(ShopRole role, ShopChange change) { } if (success) - updateStatuses.put(shop.getShopLocationAsSL().toString(), UserOperationStatus.SUCCESSFUL.toString()); + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.SUCCESSFUL.toString()); else - updateStatuses.put(shop.getShopLocationAsSL().toString(), UserOperationStatus.FAILED.toString()); + updateStatuses.put(shop.getShopLocationAsSL().serialize(), UserOperationStatus.FAILED.toString()); } } 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 a1699523..7b87c0dd 100644 --- a/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java +++ b/src/main/java/org/shanerx/tradeshop/commands/commandrunners/WhatCommand.java @@ -92,11 +92,11 @@ public void what() { for (int i = 0; i < costItems.size(); i++) { - costGroup.addElement(itemSettingMenu(i, ShopItemSide.COST, false)); + costGroup.addElement(itemSettingMenu(shop, i, ShopItemSide.COST, false)); } for (int i = 0; i < productItems.size(); i++) { - productGroup.addElement(itemSettingMenu(i, ShopItemSide.PRODUCT, false)); + productGroup.addElement(itemSettingMenu(shop, i, ShopItemSide.PRODUCT, false)); } gui.addElement(new StaticGuiElement('1', new ItemStack(Material.LIME_STAINED_GLASS_PANE), 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 06ccf458..6fe71971 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.fromString(file.getName().replace(".json", ""))).size(); + count += new JsonShopConfiguration(ShopChunk.deserialize(file.getName().replace(".json", ""))).size(); } } break; diff --git a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonConfiguration.java b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonConfiguration.java index 3080720e..6c06f124 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonConfiguration.java @@ -25,11 +25,10 @@ package org.shanerx.tradeshop.data.storage.Json; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.gsonprocessing.GsonProcessor; import java.io.File; import java.io.FileNotFoundException; @@ -40,7 +39,7 @@ class JsonConfiguration extends Utils { protected final String path; - protected final Gson gson; + protected final GsonProcessor gson; protected File file, pathFile; protected JsonObject jsonObj; @@ -51,7 +50,7 @@ class JsonConfiguration extends Utils { * @param fileName name of the file to load without extension */ protected JsonConfiguration(String folderFromData, String fileName) { - this.gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); + this.gson = new GsonProcessor(); this.path = PLUGIN.getDataFolder().getAbsolutePath() + File.separator + "Data" + File.separator + folderFromData; this.pathFile = new File(path); this.file = new File(path + File.separator + fileName + ".json"); 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 index 8cfb0eb7..c585c3e5 100644 --- a/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonLinkageConfiguration.java +++ b/src/main/java/org/shanerx/tradeshop/data/storage/Json/JsonLinkageConfiguration.java @@ -45,6 +45,7 @@ public JsonLinkageConfiguration(World world) { public void load() { linkageData = gson.fromJson(jsonObj.get("linkage_data"), new TypeToken>() { }.getType()); + if (linkageData == null) linkageData = new HashMap<>(); } 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 3b45aea0..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 @@ -40,7 +40,7 @@ public class JsonShopConfiguration extends JsonConfiguration implements ShopConf private final ShopChunk chunk; public JsonShopConfiguration(ShopChunk chunk) { - super(chunk.getWorld().getName(), chunk.toString()); + super(chunk.getWorld().getName(), chunk.serialize()); 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.toString().replace(";;", "_") + ".json"; + String oldFile = path + File.separator + chunk.serialize().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.fromString(entry.getKey()).toString(), entry.getValue()); + jsonObj.add(ShopLocation.deserialize(entry.getKey()).serialize(), entry.getValue()); jsonObj.remove(entry.getKey()); } } @@ -65,15 +65,15 @@ public void loadFile() { @Override public void save(Shop shop) { - jsonObj.add(shop.getShopLocationAsSL().toString(), gson.toJsonTree(shop)); + jsonObj.add(shop.getShopLocationAsSL().serialize(), gson.toJsonTree(shop)); saveFile(); } @Override public void remove(ShopLocation loc) { - if (jsonObj.has(loc.toString())) - jsonObj.remove(loc.toString()); + if (jsonObj.has(loc.serialize())) + jsonObj.remove(loc.serialize()); saveFile(); } @@ -81,7 +81,7 @@ public void remove(ShopLocation loc) { @Override public Shop load(ShopLocation loc) { Shop shop; - String locStr = loc.toString(); + String locStr = loc.serialize(); 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 53d9a330..b82435e5 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.toString(); - return getLinkageData().containsKey(loc) ? ShopLocation.fromString(getLinkageData().get(chestLocation.toString())) : null; + String loc = chestLocation.serialize(); + return getLinkageData().containsKey(loc) ? ShopLocation.deserialize(getLinkageData().get(chestLocation.serialize())) : null; } default int size() { @@ -50,10 +50,10 @@ default int size() { } default void addLinkage(ShopLocation chestLocation, ShopLocation shopLocation) { - if (getLinkageData().containsKey(chestLocation.toString())) - getLinkageData().replace(chestLocation.toString(), shopLocation.toString()); + if (getLinkageData().containsKey(chestLocation.serialize())) + getLinkageData().replace(chestLocation.serialize(), shopLocation.serialize()); else - getLinkageData().put(chestLocation.toString(), shopLocation.toString()); + getLinkageData().put(chestLocation.serialize(), shopLocation.serialize()); save(); } @@ -74,7 +74,7 @@ default void removeChest(ShopLocation chestLocation) { default void removeShop(ShopLocation shopLocation) { List removeChests = new ArrayList<>(); - String shopLoc = shopLocation.toString(); + String shopLoc = shopLocation.serialize(); 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 9899b48b..028d04e9 100644 --- a/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java +++ b/src/main/java/org/shanerx/tradeshop/item/ShopItemStack.java @@ -26,22 +26,26 @@ package org.shanerx.tradeshop.item; 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; -import org.bukkit.Bukkit; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.block.ShulkerBox; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.*; +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.util.io.BukkitObjectInputStream; 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.gsonprocessing.GsonProcessor; import org.shanerx.tradeshop.utils.objects.ObjectHolder; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; @@ -54,15 +58,13 @@ public class ShopItemStack implements Cloneable { - private transient ItemStack itemStack; + @Expose + private ItemStack itemStack; private transient Debug debugger; - @Expose(serialize = false) + @Expose(serialize = false, deserialize = true) private String itemStackB64; - @Expose - private Map serialItemStack; - @Expose @SerializedName(value = "itemSettings", alternate = "shopSettings") private Map> itemSettings; @@ -75,7 +77,6 @@ public ShopItemStack(ItemStack itemStack, HashMap> itemS itemSettings.forEach((key, value) -> this.itemSettings.put(ShopItemStackSettingKeys.match(key), value)); buildMap(); - loadData(); + loadLegacyData(); } //Re-added for backwards compatibility @@ -115,36 +116,21 @@ public ShopItemStack(String itemStackB64, int compareDurability, boolean compare itemSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS, new ObjectHolder<>(compareEnchantments)); buildMap(); - loadData(); + loadLegacyData(); } public Map> getItemSettings() { return itemSettings; } - - public boolean getShopSettingAsBoolean(ShopItemStackSettingKeys key) { - if (key.isUserEditable()) { - try { - ObjectHolder tempObj = itemSettings.get(key); - return itemSettings.containsKey(key) ? (Boolean) tempObj.getObject() : (Boolean) key.getDefaultValue().getObject(); - } catch (ClassCastException | NullPointerException ignored) { - } - } - - return (Boolean) key.getDefaultValue().getObject(); - } - - public int getShopSettingAsInteger(ShopItemStackSettingKeys key) { - if (key.isUserEditable()) { - try { - ObjectHolder tempObj = itemSettings.get(key); - return itemSettings.containsKey(key) ? (Integer) tempObj.getObject() : (Integer) key.getDefaultValue().getObject(); - } catch (ClassCastException | NullPointerException ignored) { - } + public ObjectHolder getShopSetting(ShopItemStackSettingKeys key) { + if (key.isUserEditable() && itemSettings.containsKey(key)) { + ObjectHolder tempObj = itemSettings.get(key); + if (tempObj != null && tempObj.getObject() != null) + return tempObj; } - return (Integer) key.getDefaultValue().getObject(); + return key.getDefaultValue(); } private void buildMap() { @@ -187,7 +173,6 @@ public int getAmount() { public void setAmount(int amount) { itemStack.setAmount(amount); - packData(); } public String getItemStackB64() { @@ -231,7 +216,7 @@ public boolean isSimilar(ItemStack toCompare) { // If compareShulkerInventory is on if (itemStack.getType().toString().endsWith("SHULKER_BOX") && - getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY)) { + getShopSetting(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY).asBoolean()) { try { ArrayList itemStackContents = Lists.newArrayList(((ShulkerBox) ((BlockStateMeta) toCompareMeta).getBlockState()).getInventory().getContents()), toCompareContents = Lists.newArrayList(((ShulkerBox) ((BlockStateMeta) itemStackMeta).getBlockState()).getInventory().getContents()); @@ -258,7 +243,7 @@ public boolean isSimilar(ItemStack toCompare) { // If compareBundleInventory is on and version is above 1.17 also check Bundles if (new Utils().PLUGIN.getVersion().isAtLeast(1, 17) && itemStack.getType().equals(Material.BUNDLE) && - getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BUNDLE_INVENTORY)) { + getShopSetting(ShopItemStackSettingKeys.COMPARE_BUNDLE_INVENTORY).asBoolean()) { try { ArrayList itemStackContents = Lists.newArrayList(((BundleMeta) toCompareMeta).getItems()), toCompareContents = Lists.newArrayList(((BundleMeta) itemStackMeta).getItems()); @@ -283,7 +268,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If compareDurability is on - int compareDurability = getShopSettingAsInteger(ShopItemStackSettingKeys.COMPARE_DURABILITY); + int compareDurability = getShopSetting(ShopItemStackSettingKeys.COMPARE_DURABILITY).asInteger(); if (compareDurability > -1 && compareDurability < 3 && useMeta) { // Return False if Damageable is not equal (one has and one doesn't) @@ -322,7 +307,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If compareEnchantments is on - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS) && useMeta) { + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS).asBoolean() && useMeta) { if (itemStackMeta instanceof EnchantmentStorageMeta && toCompareMeta instanceof EnchantmentStorageMeta) { EnchantmentStorageMeta itemStackEnchantmentStorageMeta = (EnchantmentStorageMeta) itemStackMeta, toCompareEnchantmentStorageMeta = (EnchantmentStorageMeta) toCompareMeta; @@ -353,7 +338,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If compareName is on - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_NAME)) { + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_NAME).asBoolean()) { debugger.log("ShopItemStack > isSimilar > getDisplayName: " + itemStackMeta.getDisplayName() + " - " + toCompareMeta.getDisplayName(), DebugLevels.NAME_COMPARE); // If ItemStack Meta are BookMeta then compare title, otherwise compare displayname @@ -375,7 +360,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If useBookMeta and compareBookAuthor are true - if (useBookMeta && getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR)) { + if (useBookMeta && getShopSetting(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR).asBoolean()) { // Return False if hasAuthor differs (one has one doesn't) debugger.log("itemStackBookMeta hasAuthor: " + itemStackBookMeta.hasAuthor(), DebugLevels.ITEM_COMPARE); debugger.log("toCompareBookMeta hasAuthor: " + toCompareBookMeta.hasAuthor(), DebugLevels.ITEM_COMPARE); @@ -392,7 +377,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If useBookMeta and compareBookPages are true - if (useBookMeta && getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES)) { + if (useBookMeta && getShopSetting(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES).asBoolean()) { // Return False if hasPages differs (one has one doesn't) debugger.log("itemStackBookMeta hasPages: " + itemStackBookMeta.hasPages(), DebugLevels.ITEM_COMPARE); debugger.log("toCompareBookMeta hasPages: " + toCompareBookMeta.hasPages(), DebugLevels.ITEM_COMPARE); @@ -409,7 +394,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If compareLore is on - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_LORE) && useMeta) { + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_LORE).asBoolean() && useMeta) { // Return False if hasLore differs (one has one doesn't) if (itemStackMeta.hasLore() != toCompareMeta.hasLore()) return false; @@ -419,7 +404,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If compareCustomModelData is on - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA) && useMeta) { + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA).asBoolean() && useMeta) { // Return False if hasCustomModelData differs (one has one doesn't) if (itemStackMeta.hasCustomModelData() != toCompareMeta.hasCustomModelData()) return false; @@ -429,7 +414,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If compareItemFlags is on - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS) && useMeta) { + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS).asBoolean() && useMeta) { // Return False if getItemFlags sizes differs if (itemStackMeta.getItemFlags().size() != toCompareMeta.getItemFlags().size()) return false; @@ -438,7 +423,7 @@ public boolean isSimilar(ItemStack toCompare) { } // Return False if compareUnbreakable is on and isUnbreakable differs - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE) && useMeta && itemStackMeta.isUnbreakable() != toCompareMeta.isUnbreakable()) + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE).asBoolean() && useMeta && itemStackMeta.isUnbreakable() != toCompareMeta.isUnbreakable()) return false; // If item is firework rocket @@ -447,13 +432,13 @@ public boolean isSimilar(ItemStack toCompare) { FireworkMeta toCompareFireworkMeta = (FireworkMeta) toCompareMeta; // If server compare firework duration is disabled local setting is ignores - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_FIREWORK_DURATION)) { + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_FIREWORK_DURATION).asBoolean()) { if (fireworkMeta.getPower() != toCompareFireworkMeta.getPower()) { return false; } } - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_FIREWORK_EFFECTS)) { + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_FIREWORK_EFFECTS).asBoolean()) { if (fireworkMeta.hasEffects()) { if (fireworkMeta.getEffects().size() != toCompareFireworkMeta.getEffects().size()) { return false; @@ -471,7 +456,7 @@ public boolean isSimilar(ItemStack toCompare) { } // If compareAttributeModifier is on - if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER) && useMeta) { + if (getShopSetting(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER).asBoolean() && useMeta) { if (itemStackMeta.hasAttributeModifiers() != toCompareMeta.hasAttributeModifiers()) return false; // Return False if itemStack hasAttributeModifiers && getAttributeModifiers are not equal @@ -483,7 +468,7 @@ public boolean isSimilar(ItemStack toCompare) { public ItemStack getItemStack() { if (itemStack == null) - loadData(); + loadLegacyData(); return itemStack; } @@ -521,8 +506,8 @@ public String getStateString(ObjectHolder stateSetting) { } else { ret = "False"; } - } else if (stateSetting.isInteger() || stateSetting.isDouble()) { - switch (stateSetting.isDouble() ? ((Double) stateSetting.getObject()).intValue() : (Integer) stateSetting.getObject()) { + } else if (stateSetting.isInteger()) { + switch (stateSetting.asInteger()) { case 2: ret = ">="; break; @@ -549,10 +534,7 @@ public String getStateString(ObjectHolder stateSetting) { @Override public String toString() { - return "ShopItemStack{" + - "itemStack=" + getItemStack().serialize() + - ", shopSettings=" + itemSettings + - '}'; + return new GsonProcessor().toJson(this); } /** @@ -562,24 +544,10 @@ public String toString() { * */ - /** - * Converts the {@link ItemStack} to a store-able object - */ - private void packData() { - if (itemStack != null) { - itemStackB64 = null; - serialItemStack = itemStack.serialize(); - } - } - /** * Sets the objects {@link ItemStack} from its Base64. */ - private void loadData() { - if (serialItemStack != null && !serialItemStack.isEmpty()) { - itemStack = ItemStack.deserialize(serialItemStack); - } - + private void loadLegacyData() { if (itemStack == null && hasBase64()) { try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(itemStackB64)); @@ -593,14 +561,11 @@ private void loadData() { itemStack = null; } } - } - public int getItemSize() { - packData(); - return serialItemStack.toString().length(); + itemStackB64 = ""; } public String toConsoleText() { - return new GsonBuilder().setPrettyPrinting().create().toJson(this); + return new GsonProcessor().toJson(this); } } \ 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 c7d3252a..bad1dbe8 100644 --- a/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java +++ b/src/main/java/org/shanerx/tradeshop/player/PlayerSetting.java @@ -26,7 +26,6 @@ package org.shanerx.tradeshop.player; import com.google.common.collect.Sets; -import com.google.gson.Gson; import de.themoep.inventorygui.GuiElementGroup; import de.themoep.inventorygui.GuiPageElement; import de.themoep.inventorygui.InventoryGui; @@ -39,8 +38,8 @@ import org.shanerx.tradeshop.shoplocation.IllegalWorldException; import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.gsonprocessing.GsonProcessor; -import java.io.Serializable; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -102,16 +101,16 @@ public Set getOwnedShops() { public void addShop(Shop shop) { if (shop.getOwner().getUUID().equals(uuid) && - !ownedShops.contains(shop.getShopLocationAsSL().toString())) - ownedShops.add(shop.getShopLocationAsSL().toString()); + !ownedShops.contains(shop.getShopLocationAsSL().serialize())) + ownedShops.add(shop.getShopLocationAsSL().serialize()); else if (shop.getUsersUUID(ShopRole.MANAGER, ShopRole.MEMBER).contains(uuid) && - !ownedShops.contains(shop.getShopLocationAsSL().toString())) - staffShops.add(shop.getShopLocationAsSL().toString()); + !ownedShops.contains(shop.getShopLocationAsSL().serialize())) + staffShops.add(shop.getShopLocationAsSL().serialize()); } public void removeShop(Shop shop) { - ownedShops.remove(shop.getShopLocationAsSL().toString()); - staffShops.remove(shop.getShopLocationAsSL().toString()); + ownedShops.remove(shop.getShopLocationAsSL().serialize()); + staffShops.remove(shop.getShopLocationAsSL().serialize()); } public void removeShop(String shop) { @@ -141,10 +140,6 @@ public void load() { utils = new Utils(); } - public String serialize() { - return new Gson().toJson(this); - } - public String getInvolvedStatusesString() { Set nullShops = new HashSet<>(); StringBuilder sb = new StringBuilder(); @@ -153,7 +148,7 @@ public String getInvolvedStatusesString() { if (getOwnedShops().size() > 0) { getOwnedShops().forEach(s -> { try { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.fromString(s)); + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); if (shop == null) { nullShops.add(s); } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { @@ -171,7 +166,7 @@ public String getInvolvedStatusesString() { if (getStaffShops().size() > 0) { getStaffShops().forEach(s -> { try { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.fromString(s)); + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); if (shop == null) { nullShops.add(s); } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { @@ -200,7 +195,7 @@ public InventoryGui getInvolvedStatusesInventory() { if (getOwnedShops().size() > 0) { getOwnedShops().forEach(s -> { try { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.fromString(s)); + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(s)); if (shop == null) { nullShops.add(s); } else if (shop.checkRole(uuid) != ShopRole.SHOPPER) { @@ -226,7 +221,7 @@ public InventoryGui getInvolvedStatusesInventory() { if (getStaffShops().size() > 0) { getStaffShops().forEach(s -> { try { - Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.fromString(s)); + Shop shop = utils.PLUGIN.getDataStorage().loadShopFromSign(ShopLocation.deserialize(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 ae775dcc..8e7a28dc 100644 --- a/src/main/java/org/shanerx/tradeshop/player/ShopUser.java +++ b/src/main/java/org/shanerx/tradeshop/player/ShopUser.java @@ -25,15 +25,14 @@ package org.shanerx.tradeshop.player; -import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; +import org.shanerx.tradeshop.utils.gsonprocessing.GsonProcessor; -import java.io.Serializable; import java.util.UUID; @SuppressWarnings("unused") diff --git a/src/main/java/org/shanerx/tradeshop/shop/Shop.java b/src/main/java/org/shanerx/tradeshop/shop/Shop.java index df6171c0..2ef5c905 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/Shop.java +++ b/src/main/java/org/shanerx/tradeshop/shop/Shop.java @@ -25,7 +25,6 @@ package org.shanerx.tradeshop.shop; -import com.google.gson.Gson; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; @@ -47,11 +46,18 @@ import org.shanerx.tradeshop.shoplocation.ShopChunk; import org.shanerx.tradeshop.shoplocation.ShopLocation; import org.shanerx.tradeshop.utils.Utils; +import org.shanerx.tradeshop.utils.gsonprocessing.GsonProcessor; import org.shanerx.tradeshop.utils.objects.ObjectHolder; import org.shanerx.tradeshop.utils.objects.Tuple; -import java.io.Serializable; -import java.util.*; +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.stream.Collectors; public class Shop { @@ -288,11 +294,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()).toString()).append("\n"); - sb.append("Sign Location: ").append(shopLoc).append("\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().toString() : "N/A").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"); @@ -951,6 +957,7 @@ public void fixSide(ShopItemSide side) { if (ogItems.size() > 1 && ogItems.size() != matSet.size()) { List scrapList = new ArrayList<>(ogItems); (side.equals(ShopItemSide.PRODUCT) ? product : cost).clear(); + (side.equals(ShopItemSide.PRODUCT) ? product : cost).clear(); ogItems.forEach((item) -> { while (scrapList.contains(item)) { @@ -1142,16 +1149,34 @@ public boolean isSideValid(ShopItemSide side) { * Updates list on specified side * * @param side Side to be updated - * @param updatedCostList list to set as new CostList + * @param updatedItemList list to set updatedItemList to */ - public void updateSide(ShopItemSide side, List updatedCostList) { + public void updateSide(ShopItemSide side, List updatedItemList) { 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; - } + updatedItemList.removeIf(item -> item.getItemStack().getType().toString().endsWith("SHULKER_BOX") && getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")); + + if (side.equals(ShopItemSide.PRODUCT)) product = updatedItemList; + else cost = updatedItemList; + + saveShop(); + updateSign(); + } + + /** + * Updates item on specified side at index + * + * @param side Side to be updated + * @param updatedItem Item to be updated at the specified index and side + * @param index index of the item t be updated + */ + public void updateSideItem(ShopItemSide side, ShopItemStack updatedItem, int index) { + if (!getShopType().isITrade() && + chestLoc != null && + updatedItem.getItemStack().getType().toString().endsWith("SHULKER_BOX") && + getInventoryLocation().getBlock().getType().toString().endsWith("SHULKER_BOX")) + return; + + (side.equals(ShopItemSide.PRODUCT) ? product : cost).set(index, updatedItem); saveShop(); updateSign(); diff --git a/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java b/src/main/java/org/shanerx/tradeshop/shop/ShopChest.java index 9731c885..45a8bed4 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.fromString(chestData.get("Sign")); + shopSign = ShopLocation.deserialize(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.toString()); + sb.append(shopSign.serialize()); 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 4ea28947..cd13e877 100644 --- a/src/main/java/org/shanerx/tradeshop/shop/ShopType.java +++ b/src/main/java/org/shanerx/tradeshop/shop/ShopType.java @@ -25,7 +25,6 @@ package org.shanerx.tradeshop.shop; -import com.google.gson.Gson; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.block.Block; @@ -34,8 +33,7 @@ import org.shanerx.tradeshop.TradeShop; import org.shanerx.tradeshop.data.config.Setting; import org.shanerx.tradeshop.player.Permissions; - -import java.io.Serializable; +import org.shanerx.tradeshop.utils.gsonprocessing.GsonProcessor; public enum ShopType { 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 352a6dc3..17669242 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().toString(), 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, @@ -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().toString(), DebugLevels.PROTECTION); + plugin.getDebugger().log("Shop Being updated from ProtectionListener...\n " + shop.getShopLocationAsSL().serialize(), 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 266d40c6..a18faf60 100644 --- a/src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopChunk.java @@ -53,7 +53,7 @@ public ShopChunk(Chunk c) { chunk = c; } - public static ShopChunk fromString(String loc) { + public static ShopChunk deserialize(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,8 +67,7 @@ public static ShopChunk fromString(String loc) { return null; } - @Override - public String toString() { + public String serialize() { 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 b73b4a7c..66b42327 100644 --- a/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java +++ b/src/main/java/org/shanerx/tradeshop/shoplocation/ShopLocation.java @@ -57,7 +57,7 @@ public ShopLocation(Location loc) { this.z = loc.getZ(); } - public static ShopLocation fromString(String loc) { + public static ShopLocation deserialize(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,8 +77,7 @@ public static ShopLocation fromString(String loc) { return null; } - @Override - public String toString() { + public String serialize() { return "l" + div + world.getName() + div + x + div + y + div + z; } diff --git a/src/main/java/org/shanerx/tradeshop/utils/gsonprocessing/GsonProcessor.java b/src/main/java/org/shanerx/tradeshop/utils/gsonprocessing/GsonProcessor.java new file mode 100644 index 00000000..5e592ee9 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/gsonprocessing/GsonProcessor.java @@ -0,0 +1,74 @@ +/* + * + * 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.gsonprocessing; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonSyntaxException; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.shanerx.tradeshop.utils.gsonprocessing.typeadapters.ConfigurationSerializableAdapter; + +import java.lang.reflect.Type; + +public class GsonProcessor { + private final Gson globalGson; + + public GsonProcessor(boolean doPrettyPrinting) { + GsonBuilder gsonBuilder = new GsonBuilder() + .disableHtmlEscaping() + .serializeNulls() + .registerTypeHierarchyAdapter(ConfigurationSerializable.class, new ConfigurationSerializableAdapter()); + + if (doPrettyPrinting) gsonBuilder.setPrettyPrinting(); + + globalGson = gsonBuilder.create(); + } + + public GsonProcessor() { + this(true); + } + + public T fromJson(String json, Class classOfT) throws JsonSyntaxException { + return globalGson.fromJson(json, (Type) classOfT); + } + + public T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException { + return globalGson.fromJson(json, typeOfT); + } + + public String toJson(Object src) { + return globalGson.toJson(src, src.getClass()); + } + + public JsonElement toJsonTree(Object src) { + return globalGson.toJsonTree(src, src.getClass()); + } + + public Gson getGlobalGson() { + return globalGson; + } +} diff --git a/src/main/java/org/shanerx/tradeshop/utils/gsonprocessing/typeadapters/ConfigurationSerializableAdapter.java b/src/main/java/org/shanerx/tradeshop/utils/gsonprocessing/typeadapters/ConfigurationSerializableAdapter.java new file mode 100644 index 00000000..a8f56859 --- /dev/null +++ b/src/main/java/org/shanerx/tradeshop/utils/gsonprocessing/typeadapters/ConfigurationSerializableAdapter.java @@ -0,0 +1,80 @@ +/* + * + * 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.gsonprocessing.typeadapters; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.reflect.TypeToken; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +import java.lang.reflect.Type; +import java.util.LinkedHashMap; +import java.util.Map; + +//Based off of ConfigurationSerializableAdapter by Schottky @ https://www.spigotmc.org/threads/configurationserializable-to-json-using-gson.467776/ +public class ConfigurationSerializableAdapter implements JsonSerializer, JsonDeserializer { + + final Type objectStringMapType = new TypeToken>() { + }.getType(); + + @Override + public ConfigurationSerializable deserialize( + JsonElement json, + Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { + final Map map = new LinkedHashMap<>(); + + for (Map.Entry entry : json.getAsJsonObject().entrySet()) { + final JsonElement value = entry.getValue(); + final String name = entry.getKey(); + + if (value.isJsonObject() && value.getAsJsonObject().has(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { + map.put(name, this.deserialize(value, value.getClass(), context)); + } else { + Object val = context.deserialize(value, Object.class); + map.put(name, val instanceof Double && ((Double) val) % 1 == 0 ? ((Double) val).intValue() : val); + } + } + + return ConfigurationSerialization.deserializeObject(map); + } + + @Override + public JsonElement serialize( + ConfigurationSerializable src, + Type typeOfSrc, + JsonSerializationContext context) { + final Map map = new LinkedHashMap<>(); + map.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(src.getClass())); + map.putAll(src.serialize()); + return context.serialize(map, objectStringMapType); + } +} 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 cc695d02..9d072960 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/ObjectHolder.java @@ -45,11 +45,11 @@ public boolean isBoolean() { } public boolean isInteger() { - return obj != null && obj instanceof Integer; + return obj != null && (obj instanceof Integer || (obj instanceof Double && Double.parseDouble(obj.toString()) % 1 == 0)); } public boolean isDouble() { - return obj != null && obj instanceof Double; + return obj != null && (obj instanceof Double || obj instanceof Integer); } public boolean isString() { @@ -61,7 +61,7 @@ public Boolean asBoolean() { } public Integer asInteger() { - return isInteger() ? Integer.parseInt(obj.toString()) : null; + return isInteger() ? (int) Double.parseDouble(obj.toString()) : null; } public Double asDouble() { 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 aa5e9686..cf3082fc 100644 --- a/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java +++ b/src/main/java/org/shanerx/tradeshop/utils/objects/Tuple.java @@ -25,10 +25,8 @@ package org.shanerx.tradeshop.utils.objects; -import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; - -import java.io.Serializable; +import org.shanerx.tradeshop.utils.gsonprocessing.GsonProcessor; public class Tuple { @@ -58,8 +56,12 @@ public L getLeft() { return l; } + public String serialize() { + return new GsonProcessor().toJson(this); + } + @Override public String toString() { - return new Gson().toJson(this); + return serialize(); } } \ No newline at end of file diff --git a/src/main/resources/builddate.yml b/src/main/resources/builddate.yml index 88a4696f..d3bf9e7f 100644 --- a/src/main/resources/builddate.yml +++ b/src/main/resources/builddate.yml @@ -1 +1 @@ -buildtime: ${timestamp} \ No newline at end of file +buildtime: ${timeStamp} \ No newline at end of file